Break Out of the Pattern (Solution)
Here we are back in IDLE in a script. I made a new script and put in a short comment just to keep the context for me what I’m supposed to do here. I’m going to run an infinite loop until they use a types
while True is a good way to do an infinite loop, and then to get out of it, I’m going to need something and then a
break keyword at some point. All right, so the task is that I want to collect user input.
'q' or 'Q' to quit: ". That gives them the instructions. And then I need to compare their input. So I’m going to say
if user_input ==
"q". I need to make sure that it’s both lowercase and uppercase. In this case, I’m going to just say
.lower(), use the string method on it to say if the user input that comes in, lowercased, is equals to a lowercase
"q", that would catch both lowercase and uppercase
"Q" inputs from the user, then I want to break out of the loop.
02:53 Now just for fun, because I keep saying that there’s always different solutions for it, and also trying to show that to to you. Yeah, you don’t have to worry about if you get a different solution, as long as it has the same functionality, right?
So I want to show you something here that’s another way of handling this. Python 3.8 introduced something called an assignment expression. So I could take this and instead of using
while True, I’m going to say
while user_input and then use the assignment expression, which is also dubbed the walrus operator (
:=) because it’s this little sign looks a little like a walrus with its eyes and tusks. All right?
And then the funny thing is I don’t need anything in here. In this
while loop, I’ve moved the whole logic into just the first line of code, and then I’m using an ellipsis here, which is similar to
pass. Well, actually, maybe this is better.
What happened here? Okay, we’re back to normal, and the lower, just the lowercase
q quits the program. So, this is a strange and much less readable alternative solution that uses the pattern 3.8 walrus operator, or assignment expression.
So essentially, this whole thing is going to be
True as long as the user doesn’t input
"q", and it keeps evaluating in here. And so you’re essentially creating this
while True loop with a very, very not well-readable line of code up here, but it’s going to evaluate every round, and once the user inputs a
"q", this whole expression is going to be false, and the loop is going to stop.
05:48 So you don’t even need any code in the loop body for this solution. Okay? But this is just a weird sidenote, and I don’t expect you to read or write this type of code because it’s much less readable than the other solution.
Become a Member to join the conversation.