Python Tutorial-If Statements

The If statement is where you start to see how a program actually works. Think of an If statement as you would part of your everyday life. For example, If I feel better tomorrow I will go to work, or else I will stay home. If my favorite sports team is in the championship game I will buy tickets, or else I will stay home and watch the game.

I am intentionally writing the sentences that way even though they are not exactly perfect English. In Python (and other programming languages) the If statement uses an Else statement to tell Python what to execute in the event the If Statement is not satisfied. Let’s take a look…

For starters we will not be entering the above into IDLE. We are actually going to write a very basic program now. From IDLE go to File>New File. Enter the code into the new file and save it. Give it whatever name you want but make sure it has the .py extension. Now in the new file window go to Run>Run Module and you will get a response of Else Satisfied in IDLE. We set the variable myNum to 25 and then told Python what to do if myNum was greater than 26. myNum is not greater than 26 so if is false. As a result Python executes the else statement.

I also want to point out something that we have not seen until now. You will notice that the print statements are indented. The Python shell should do this automatically. This is how blocks of code are separated for readability. If the formatting is not correct you will get errors when trying to execute the code.

What if there are actually more than 2 possible conditions? Well we can address that as well. Take a look.

What do you think you will get? What did you get?

A few more notes about your programming. Take notice of the colon (:) after each condition. This makes Python programming a little cleaner than others. For example in Java there would be curly brackets {} that had to be opened and closed. Beginner programmers often forget brackets causing errors that can take some time to figure out. Not to say that won’t happen with colons but it is a lot cleaner.

The standard indent in Python is 4 spaces but you don’t have to use 4 spaces. You can use 3 or 5 or whatever you want but you should be consistent across your program. Again, the Python shell should take care of this for you.