Control the Flow of Your Program (Solution)
00:00 Here you’re back in an IDLE window. Now I have on the left side the interactive window, and on the right side, I have a script file open that is currently not saved yet, but just this is where we’re going to start building the program and then eventually run it to see its output.
I could either calculate this every time I do the check, or I could do it once for this script. Now I’m going to just do it once, as I’m going to say
len(string_to_check). And you could also wrap this around the input and then right away just get the length of the string.
02:03 But I want to keep the string around because maybe I want to display it back to the user or something. So now I have two variables. I have the string variable that the user inputted, and then I also have the length variable, how long it is.
Now I can do my control flow using
elif statements. I’m going to say
if string_length < 5: I want to print a descriptive message, and the task was very specific about it, so I am just going to copy it from the task so I don’t have to type it out.
Let me move these windows a bit, get some more space. So here’s the first conditional check. I’m checking whether the string length is smaller than five, and I’m going to print it’s less than five characters long. And then I want to know
elif string_length > 5: then I want to print different string.
I’m going to say essentially the same, just greater than five characters.
"Your input is greater than 5 characters long." And then finally, I’m going say
else, so if it’s not less than or greater than, then it’s going to be exactly five. I’m going to say,
"Your input is 5 characters long."
03:36 Okay, I think this is the script that I want. I want to display specific strings depending on the length of the user input. And I want to collect the user input first. All right, let’s save this and try it out.
Save. And here on the left side, now you can see that once I saved the script and ran it using F5, here in IDLE, I get the input here that I defined,
Check string length: . All right, I’m going to say
04:39 Seems to be working fine. Okay, so this is how I solved this challenge. Now, you don’t necessarily need this intermediate variable. You could also instead do a length check in here every time, but I’m using it twice, so I just thought, all right, I’ll define the variable and then reuse it down there.
and that should work as well. But in this case, it’s, nice to have this
else clause just to catch anything because the only condition that would come down here after these two, less than and bigger than, would be equals to.
So you could just catch it with the
else like I did before. And then I also left a comment that kind of, like, indicates that the
else clause in this case means that it’s exactly five characters long.
Become a Member to join the conversation.