filmov
tv
Python Refactoring: 'while True' Infinite Loops & The 'input' Function
![preview_player](https://i.ytimg.com/vi/ez-qYc0NlMk/maxresdefault.jpg)
Показать описание
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:
Комментарии