Python Refactoring: 'while True' Infinite Loops & The 'input' Function

preview_player
Показать описание

In this video I'm refactoring some Python code that a reader sent me over Twitter and asked me to make it more Pythonic. It features reading user input from the command-line with Python's built-in "input()" function. The program runs an infinite "while" loop until the user enters either "yes" or "no". I'm taking this example through a couple of refactorings to remove code duplication and to make it more resilient to bad user input.

The refactored solution features a (still infinite) "while True:" loop and removes the duplicated lines of code to make the function more maintainable. It's funny how sometimes even a function that's just a few lines long in Python can be cleaned up and refactored further so that it's more resilient and robust.

What we end up here is the Python equivalent of a "do while" loop in other programming languages. A native "Python do while" doesn't exist, but I think this solution is fairly close and just as readable.

Watch the full video to see how you can remove extra spaces and other whitespace characters from a Python string. You'll also learn some other techniques for normalizing user input, like converting the user input string to lowercase first with Python's "lower()" method.

This video also features "Thonny", a cute little Python development environment that features a debugger you can use to visualize the execution of your Python programs. Hopefully that makes it easier for you to follow along with the code examples I give in the video. Leave a comment below if you found it helpful.

* * *

FREE Python Tutorials & News:
Рекомендации по теме
Комментарии
Автор

I like the concept of this video.
i.e. Talking through simple code & refactoring
More please.

bensmith
Автор

You can simplify it a little bit more by using a walrus operator from 3.8.0 as well:
def get_answer(prompt):
while (answer := not in ("yes", "no"):
continue
return answer

lucassilvas
Автор

Finally... i get the solution to this simple yes/no issue. you just got all my doubts!

aztrodj
Автор

Dan, question? This function only works if the prompt is 'yes or no'. Can it be made more general - say if the prompt is 'Enter Seat number' and we want to make sure the seat num entered is a digit, or 'Enter seat' might be 'N14'? can we add multiple if statement? depending on the prompt?
Thanks for your tips and videos - big help for early python converter, steve

swellsca
Автор

Thanks! Im joining my robotics team in my school so I was looking for coding channels and i found you! Super helpful and clear 👌👌👍

inktex
Автор

Awesome video, explained exactly what I was struggling with. Thank you!

MarsLanding
Автор

Can we replace the code 'return' with code 'break'? What difference does it make?

wongkk
Автор

I am a beginner and I have never thought of using the str.strip method when getting input. Thank you....

heshankumarasinghe
Автор

Can u help me out .. iam currently working on gaia data with python ..
There iam dealing with fits file containing large data of 6M rows and 31 columns .. i need to bin the data according to some conditions that i need to apply to two of the coloumns .. and bin the entire data according to that .. and store data in each bin (like a box) in seperate fits files. Can you help me out

saroons
Автор

Can i get any key input without stop the while loop and without install an module? Sorry for my bad englisch im a german😂

julius
Автор

So is while-True-return or while-True-break the general pythonic answer to do-while?

zomaarwat
Автор

I love your concepts, it's just so wonderful. I tried to use the .split() and .lower() concept on a short code having to do with lists. I know .lower() doesn't work with lists, but is there away I can go about this, please? I will appreciate a solution. Thanks.

store = list()

while True:
user_input = input("Enter something: ")
grouper = store.append(user_input)
if user_input == ("ok").split().lower():
break
print(store)

emekaonah
Автор

sir what python Ide you are using can you mention what....

srikanthbadampudi
Автор

Thanks for giving this video it saved me....as it is a day before exam preparation

ashifkasala
Автор

very cool about strip() and lower(), simple and useful, thanks, Dan!

neofit
Автор

can anyone explain why it prints yes or no depending whatever you answer with

otherleader
Автор

What's the deal with the italicized font suddenly materializing? Is that a "Thonny" thing?

phormynx
Автор

I prefer this approach but I've seen some people say it's best to make sure the exit condition is clear from the while statement.

humanrays
Автор

For membership checking I normally like to work with sets. They have some handy features like being able to subtract on set from the other or issubset().

MaxHolzapfel
Автор

I like the video a lot can u explain how we write this in Python - while(true);//this is from C to tell that stay in the loop I.e do nothing while condition is true

chinmaykulkarni