Python Institute PCAP – Control Flow Part 5
- Accepting Input From a User
Have something run and print things to the screen or anything. So I’m sure you’re dying to make your programs more interactive. And don’t worry, we’re going to get into all of that much later. But for now, I just want to introduce the ability for you to prompt a user to type something and then you can use that text or whatever they typed in your program. And so the way to do that, to accept user input, and there’s many ways of accepting user input input.
A user could be uploading a spreadsheet or something into your program, could be uploading documents into your program, could be typing up data. But a simple way of getting started here is to accept input right on the console, okay? And this is the console down here. When your program runs, it will prompt something to the user. For example, enter your name and then the program is going to accept that input and do certain things with that name or however you deal with the data in the instructions of your program. So let’s get started. It’s very simple to accept user input. You just use the input function.
And as an argument to this function, you pass in the text that you would like displayed on the console so that the user knows what they need to type. So for example, if I say enter your name. Now when I run this program, this is what’s going to be displayed here in the console. And the program will continue to run until the user gives some kind of input.
So let’s hit the play button and let this program run. And notice on the top right, you’ll see the red square indicating that if you want to stop the application, you could press that and it will stop. But until then, this will continue to run. And the only way to really stop it is to give some kind of input from the user and the input is going to be from the keyboard. And so if I enter my name, first things first, I’d have to, first of all, make sure that I’m clicking after this text, right, because this is being displayed in the console when your program runs. That’s what’s being simulated here. This program running and it’s in this console.
And so I would have to type in my name. So let me just put a space and enter my name. As a matter of fact, I can put multiple spaces here and enter my name and type in MTOs. Hit enter and boom. As soon as you hit enter, the program exits. And as you can see, process finished with exit code zero. Exit code zero means it was successfully run. Now, it did nothing with the data that we provided. We provided this data to. It our name, and the program really didn’t do anything with it.
So if we wanted to use that data, we would have to accept that data into a variable of some kind. So I can say name, so the name variable and then I can print a greeting and say hello there, put a space after hello, there, and then put a plus sign to concatenate the name variable to this greeting. And so now let’s run this and notice it’s going to print well, first it’s going to prompt the user to, hey, enter a name. So let’s enter a name. I can choose to put spaces or whatever, but I’m going to just put the word MTOs here.
Okay, now keep in mind you can’t press Enter. You can only use spaces and backspace. So let’s put a bunch of spaces. I’m doing this intentionally so you can see the output, and then I type in Mt OS. Okay. And let’s hit enter. And boom. Now the program ends, and as you can see, process finished with exit code zero. But look at what it printed. It printed hello there, but then with a lot of spaces. Okay, what are all these spaces doing? Well, the name variable captured all of the spaces along with the text that I typed. So the name variable contains all of these spaces, including my name MTR’s, right. To prevent the variable from containing those extra spaces, we can let’s run this again.
It’s going to prompt us to enter our name, and without putting any spaces, I’m just going to put Mtrs like that and hit Enter. And now it prints as expected. Okay, so if you want to make this a bit more legible, what you could do is maybe put a colon in the prompt statement and put a space there, right? Just so that it’s a bit easier to read. So let’s run that again.
And you’ll be able to see when I click here, it gives me the ability to sort of go a little bit ahead of this text. And now I can write Mtrs, and it’s going to run as expected. Okay, now we can’t really control the way the user uses this app, so we need to take into consideration certain instructions in our program. So to prevent the spaces to be captured in the name variable, what we could do is we can strip the name of any white space. All right, there is a strip function.
I don’t know if I’ve covered it so far, but we’re going to talk about that right now. So let’s say let me run this with the strip function. So if I do name strip, this is actually going to remove any leading or trailing white space in the text that they type. And that removing is going to happen when the data is printed, okay? Because during the printing step is where I’m adding this strip method, right, so let’s run this again. And now this time, I’m going to add a bunch of spaces. In the beginning, I’m going to write my name, and then I add a bunch of spaces towards the end, hit enter and boom. Notice that it still only includes one space. Now where is this one space coming from?
That space is of course coming from right here in the prompt that we give to the user. Initially, the white space from the name is actually being removed because we’re invoking the strip method on that variable. Now keep in mind, whatever the user types in the prompt, it’s always going to be taken as a string, okay? Even if they type a number. So for example, let me run this again. If I type in the number twelve, this twelve is going to be treated as a string in our program, all right? And so let me show you what can happen if we try to, for example, add the number five or any number to a given number that the user enters. So let’s do that instead of writing hello there, I’m just going to print the I’m just going to say five plus number.
Let’s change this to a number variable because now we’re moving on to the number example. So let’s change that to number and it will say enter your number. And so this is supposed to or we would like it to add the number that the user enters with the number five. But notice what happens. Let’s run this. Enter your number, let’s enter ten. For example, hit enter. We run into an error. And what is the error? It’s saying unsupported operates type plus for int and string. We talked about types earlier in this course, right? And this should be a familiar error to you. We’ve seen this before. So it’s saying that what do you want me to do with this plus, because one of the data points is an integer and the other data point is a string. You can plus two strings together, which is known as concatenation. You can plus two integers together, which is known as summation. But you can’t add a string to an integer. You’d have to convert it. Now, if we were to use the STR function on this on the five, that wouldn’t make sense because let’s run this, let’s enter the number ten.
Notice it puts five before and then concatenates the ten. Now ten is of course always going to be taken as a string again, no matter what the user types here, it’s going to be interpreted as a string when this program runs. So it’s basically concatenating that. So what we need to do, the solution here is to change the input type to an integer. And if you hover your mouse, you’ll notice expected type int got string instead, right? So before even running this program, pie Charm is smart enough to let us know that, hey, you’re trying to add an integer to a string because input is going to return a string version of the data, whatever the data is that the user types, whether it’s a number or anything. And so we need to make sure that we turn this into an int so we can use the int function.
And now the string is going to be interpreted as an integer. It’s going to be converted to an integer. This is known as casting. We talked about this. We’re casting the string to an integer and now we’ll actually get the proper result. So let’s run this. And now let’s add the number ten, hit enter and there we go. We see the proper answer, which is 15.
Now let’s run that again and notice that I had removed the strip method, right? So then if I put a bunch of spaces here and put ten, this int is smart enough to cast all of these spaces, including the number, right? So let’s run this. Oops, we got to click here in the console and hit enter. And there we go. It’s 15, right? Int by default, actually strips the string so that it gets rid of all the white spaces and just gets the integer that it finds in the string. So play around with this. This should add more creativity to your practice in programming. Create if else statements. If a person enters a number, do this. Otherwise if they enter a string that you want a different type of message being printed. Use all the knowledge that we’ve provided so far in this.
- Section 4 Assignments: Part 1
This is an important section. This is section four where we spoke about loops and if else, statements and conditionals and all that you learned about how to control the flow of your program. And this is the foundation of any programming language, right? I would say 90% of software development has to do with what we’ve covered in this section, OK? Control flow and giving instructions to the computer to run code in a certain way way based on the decisions that you have programmed in the code. If L statements, loops, these are foundations and you need to really have a strong handle in these foundations to be a successful software developer. Everything else, trust me, will come very easy. Right?
Now you might think you know, loops and if L statements, but when you’re giving up, when you’re given a problem and you have to break that problem down into smaller pieces, that’s where people struggle. Believe it or not. There are many software developers that have many years of experience, but they still struggle with logic and controlling the flow of the program, right? They may have expertise in databases and framework, design and services, and front end, back end, they may understand the whole thing. But then when it’s a tricky puzzle type of problem where there’s a loop or anfl statement that they just can’t wrap their head around, that’s no good, right?
So that’s what this section is targeted towards. I’m going to really challenge you in trying to complete these problems. And if you are struggling, great. That’s what I want from you. I want you to struggle with some of these problems. Some of them will be easy, others will be much more challenging. And as we proceed in the course, I’m going to continue to make more comprehensive problems. But these are the building blocks. This section is a golden section. Try to do all of these problems on your own, even if it takes you a day or a week to go through a single problem. No worries. Okay, so we’re going to start off easy. Here’s the first one in section four, assignment one. It says create a method called twelveRR that accepts two integer arguments A and B and the method should return true if one of the arguments is twelve or if the sum of both arguments equals twelve.
So here are some example runs. When you run this method, with the first argument being a three and the second being a twelve, well, guess what? One of them is a twelve, isn’t it? So it’s going to return true in the second example, none of them are twelve. So we have to check for whether if we were to add these two numbers together, would it result in twelve? And we know that nine plus four is actually 13. So it’s going to return false. In this third example, none of these are twelve. But if we were to add them together, nine plus three it does equal twelve. And in that case, of course it’s returning true, right? So you have to check for each of these to see if either one is a twelve. And if it is, you return true. Otherwise you also check for if they sum to the number twelve. And in that case you would return true. If both of those situations are not present, then it’s supposed to return false.
So let’s try this out. I want you to pause the video now and try this out on your own. And then you can resume to watch my solution. Okay, welcome back. Hopefully that wasn’t too difficult. So all we have to do is do a single check. Really? And if you do an if statement and say that if A is equal to twelve or if B is equal to twelve. Because remember, we have to check for both of these, either one could be twelve. So that’s why we have an or. And then finally we also check for whether adding them together would result in twelve. And so for that we also need another or. A plus B is equal to twelve. And then if one of these conditions is true, then that means we return true, all right? Otherwise else we return false. Okay? So hopefully this makes sense.
We can make this code much neater because guess what, this is an expression and this expression together is a boolean expression. It’s going to return either a true or false, right? All of this evaluates to either a true or a false. So we don’t even need this if else statement. We can just return this directly. And whatever the result of that is going to be, it’s going to say either true or false. So what I can do is just type in return and give that expression as the return value, this expression. Okay? Based on the data that we pass to these arguments, this is going to return either a true or false. So hopefully that wasn’t too difficult. Let’s move on to the next assignment, which is assignment two. So here it says create a method called pay extra that accepts two parameters working and hour. Okay? So before I go over, the rest of this looks like a long paragraph that we have to read.
Let’s quickly define that method. So we do def pay extra and the first argument is working. And the second argument is our. So we’ll say working and then our. Okay? And then for now, I’m just going to put a pass here just so that it compiles. So let’s continue on with the with what it’s asking us to do. So it says that this method will be used to decide whether an employee will receive extra pay or not. Okay? If an employee is working during the hours of 08:00 P. m. Until 08:00 A. m. In the morning, that means they should be paid extra. Makes sense, right? In that situation, they’re working the night shift, right? So in that situation, the method should return true, otherwise it should return false, okay? So if they’re working between the hours of 08:00 A. m. , excuse me, 08:00 P. m. Until 08:00 A. m. , that means all night, they’re working the night shift, it should return true. Otherwise, this method is supposed to return false. So notice it says in the notes, it says that the hour parameter should be from either zero to 23. So they’re using sort of a military time. And so that’s what the hour parameter will contain, either from a number between zero to 23. All right? And so 08:00 A. m.
Is our eight and 08:00 P. m. Is our 20. Okay? Hopefully you can translate that. So let’s go over this example. Run. They run pay extra with true, which means that the person is working and the hour eleven. So 11:00 A. m is past 08:00 A. m. . So of course these are working hours, so we don’t have to pay extra, okay? And then in this case, in the second example, even though this five is not a working hour, it’s really early 05:00 A. m. In the morning. But since they’re not working false, it returns a false. In this third example, it returns true because 06:00 A. m. Is quite early. Based on our definition, they’re working before 08:00 A. m. . And of course, the working example, the working parameter is true, so it’s going to return true. So how do we code this thing?
Well, it’s also very similar to the previous assignment where we’re just going to deal with a boolean expression. So if we just start by writing an if statement and saying that working, we can either do true like that and we can have another expression in here, say, where the hour is less than eight or the hour parameter is greater than 20. If this all evaluates to true, of course, then of course we’re going to go into this block and the if statement, it’s going to just return. Make sure I have the indentation, right? It’s going to return true, else it’s going to return false, right? So very similar to the previous assignment. And what you learned in the previous assignment is this is going to evaluate to either a true or false. So we don’t need to type up all of these extra lines of code.
We could just return this directly and just instead of having a NIFT statement, we could just say return like that and get rid of the colon at the end. And another thing we could do is instead of saying working is equal to true, we could just do working like that. Because guess what, they’re going to pass in either a true or false. All right? And by the way, this is actually supposed to be a capital T, not a lowercase. So let’s change this to F and this should be T uppercase. So they’re going to be passing in a true or false here. So working is going to be a boolean anyway. And then we have this and clause. That means that both of these conditions need to be true, the working as well as this for this to return true, otherwise it would return false. So that’s it for assignment two. It’s that simple. Hopefully you were able to finish this. Now let’s move on to some loops. And if l statements, we’re going to get practice with those in assignment number three.
Okay, so let’s bring that up here. So, assignment number three, given an array of INTs return true, this actually should be a list. So given a list of INTs return true, if the sequence of numbers one, two, three appears in the list anywhere, false. Otherwise okay, so again, given a list of INTs return true, if the sequence of numbers one, two, three, this particular sequence appears in the list anywhere, right? So it has to be in this order. So if this particular list contains one, two, three anywhere, it should return true. So notice in the first example, one, two, three does exist, so it’s going to return true. In the second example run, we have one, we have two, but we don’t have three after that. So this is going to return false. Let’s go over to the third section. We have 1112-1123 is at the end, so it’s going to return true. And then one, two, of course, is going to return false. If it’s empty, it’s supposed to return false. So why don’t you pause the video and try this assignment out on your own and then you can resume to watch my solution. Okay, so welcome back.
So this is going to require a for loop as well as an if statement. All right, so this is a little bit more involved than the previous assignments that we looked at. So the first thing we need to do is we’re going to need a loop over this entire list so the user can pass an empty list like they’re doing here, or they can pass a really long list. However many items there are in the list, we need to of course, loop through the entire thing to make sure that we find a sequence of one, two, three. Now, if we find that sequence before, like in the beginning of the list, then we don’t have to loop anymore. We could just exit, right? We can just say return true, we found the sequence, but if it doesn’t contain the sequence and we have to loop through every single item in the list.
So we need the for loop. So we could do four in range and in the range we have to pass in the number of items in the list. Right? But there’s a caveat for this particular puzzle, and you’ll see why in just a moment. But let me just show you. Let’s do a len of the NUM list. That’s the list argument they’re passing. So at this point, we’re looping over all of the items and each item here is being treated with an index position number 0123. So we’re going all the way at the end of the list. But keep in mind that we have to check for a sequence. So you’ll see what happens and you’ll see why we’re going to need to change this loop mechanism in just a moment. But if I do where numb list, if NUM list at the Ith index position is equal to one, the next element over is supposed to be a two if we’re looking for the sequence. So we need an and clause and say NUM list at the I plus one position is equal to the number two. And we do a similar thing for the third check.
So we do NUM list at I plus two is equal to the number three. This way we can actually check. For example, if we’re looping and if I is this position, we check for whether this is equal to one. And then I plus one would be this value and then I plus two would be this value. And since I is going to change every iteration, each of these is going to get an opportunity to be I. And then we do an I plus one to check the second value, I plus two to check the third value. But you’ll see that we run into an error. Let’s say I gets to this position right here. If I is this, I plus one would be this. But then I plus two does not exist in this list. That position is not even there. That element doesn’t exist. So we’re going to run into an error at this point, right?
So you might have guessed that this range, this looping mechanism needs to change a bit and we’ll go over how we could do that. But I just want to show this error to you before we fix it. So let’s return true. So if all of these are true, then that means we of course return true. Otherwise we return false. So outside of this loop, we have to return false. We can’t do an else clause here and say false because it’s going to immediately break out of the loop. It’s either true or false. So in the first iteration, it’s just going to immediately exit. So that’s why we need this entire loop to function. If it searches the entire list and it doesn’t find the value, only then we return false. And that’s why this return false needs to be outside of this for loop. Okay, now let me show you how this is going to crash. Let’s invoke sequence with let’s just pick this thing right here and in here. Instead of having a one, two, three, I’m just going to change this to a two. So now we’re guaranteed to search through the whole thing because there is no one, two, three. It’s going to go to the final value and it’s going to crash. Because guess what? When I is this value, I plus one doesn’t exist. I plus two doesn’t exist. It’s actually going to crash before that because when I get to this point, I plus one is here, and I plus two doesn’t exist. So you can see that we’re going to run into an index out of bound exception.
I want you to look at what that error looks like. Let’s right click here, let’s run assignment three and boom, there we go. Notice it says list index out of range. Okay, so what do we do to fix this? Well, all we have to do is do a minus two like that. So we get the length of the list, and then if we do a minus two, that’s going to bring us two index positions in, right? And if we do that, then this should never cause an exception. After that, we won’t run into this issue. And so now with that correction, when we add a minus two there, let’s run this again. And now notice it’s working fine. If I print, let me print the invocation of sequence. We’ll put that in print statement. Let’s run this and notice it returns false. If I change this to a three right here, like that, one, two, three, and run it, it’s going to return true. Now, sometimes you need to be careful because what you’re testing, the data that you’re testing might seem to work, but your code will fail with some other data. Let’s say if I change this to a one, two, three right here, and then we change this to one and a one, and if we had forgotten to put this minus two here, this code will still run successfully and this will return true in this case.
So let’s right click this and run it. It does return true because the sequence was discovered right in the beginning of the list. So as soon as it discovered that sequence, this broke out of the loop because it returns true. It broke out of that method or function rather. But we know that this code is flawed if we don’t have that minus two here. Okay? So make sure you test various values to make sure that your code is working as you practice these assignments.
Now, let’s try to pass in an empty string. Excuse me, an empty list. Instead of having any values, let’s put it an empty list here and let’s run this. Notice it returns false. So this code is working. Now, why did this work? Well, if we do a length of zero NUM list, right, there’s no elements. If we do a length function on a zero element list, it’s going to return zero, right? That’s what the length is going to be. But then when we’re doing a minus two, it’s going to take it to a negative number. Well, this, the structure of a loop is supposed to go up to a given value.
So I is going to start from zero, and then it goes up to the range negative. Immediately, it’s going to stop. It’s not even going to execute the loop, and it’s going to break out of the loop, and it’s going to return false. Okay? So that’s why an empty sequence list also works as well as the other examples that you can see here. This would also return a false. All right, so we covered three assignments in this video. We have a couple more assignments to go, so I’m going to save them for the next.