View Single Post
Old 2019-11-19, 02:24   #10
Dylan14's Avatar
Mar 2017

2×293 Posts
Default If/else, part 1: the if command and the else command

Now that we have dealt with the print command and other related commands (such as the format command and the input command), it's time to move on to stuff that will form the backbone of many programs: loops and if/else statements.
We can classify these as follows:
* if/elif/else - We test if a logical statement (possibly a chain of logical statements) is true or not. If it is true, we execute something. If not, then depending on what we have following it, we will run something else.
* for loop - We have a counter (usually i, but it doesn't have to be). This is initialized to some value. The loop will iterate for some number of iterations. During one of these iterations, we do something.
* while - While a logical statement is true, we run whatever is in the loop. As soon as the logical is no longer true, we stop.

Loops will come later, after we deal with modules and functions. For now, we will focus on the first part of the list: if/else statements(*).

If/else statements:

In real life, we often do stuff based on whether certain conditions are true. For example (using mersenneforum's favorite program):

If the temperature is less than 40 degrees Fahrenheit, I will run Prime95 on my computers to warm the room.
Today's high temperature is 38 degrees.
Therefore, I will run Prime95 today.

Much like in real life, certain code will run if a certain condition is true or not. The way we can implement this in Python (and really any programming language) is to use if statements.
Systematically, the if statement works like this:

We will break this down further. The first line in the if statement reads "if(expr)". This is interpreted as follows: We test the truthiness of the expression inside the parentheses. There are two outcomes of testing the expression:
a) The expression evaluates True. If this is the case, then we evaluate whatever is in the body, which is everything after the colon (i.e., we do something). Note that whatever is in the block must be indented(**). If it isn't, you will get a IndentationError.
b) The expression evaluates False. If this is the case, then we skip over the code and move to the next piece of code, or we stop if this is the last piece of code.

If we want to implement our good piece of advice, we could type the following into our shell:

temp = input("Enter a number")
if(float(temp) <= 40):
   print("run Prime95")
What this does is if the user enters a number, then we check if the input is less than or equal to 40. If it is, then we are told to run Prime95. If not, then we get nothing. If we don't get a number as input, then we get an error.

Now we only have one thing inside the block. We can of course have as many statements as we like inside the block. We can even have more if statements within the block, as long as we indent properly.

Now, say we want the code to do something else if our expression evaluates as false. We can do this by using else statements. Else statements must follow an if statement, they can't be alone. For example, if we type this in:

we will get a SyntaxError. Systematically, the if/else construct works like this:
    #code to run if expr is true
else:  #code to run if expr is false
Note the indentation!
So let's suppose that we have the computers off when the temperature is above 40 degrees. We can modify the code as follows:
temp = input("Enter a number")
if(float(temp) <= 40):
   print("run Prime95")
else:  #temp > 40
    print("Turn your computers off, it's warm out there!")
Now, if the input is below 40, we run prime95. If not, then the input is either a number above 40, or it's something else. If it is a number, then we are told that we should keep our computers off. If it is something else, we will get an error.
A few more notes:
1) Expressions can be compounded using the operators "and" and "or". So we can have something like this for an if statement:
if(expr1 and expr2):  #evaluates if expr1 and expr2 are both true
or this
if(expr1 or expr2):  #evaluates if expr1 or expr2 are true
or something more complicated, like (expr1 and (expr2 or expr3)). Using "and" and "or", you can fine tune exactly when a piece of code runs.
2) You can write if/else expressions in a single line, and if you have multiple statements you want to run, then you separate with semicolons. For example, this is perfectly valid:
temp = input("Enter a number: ")
if(float(temp)<=40): print('run Prime95'); print(str(temp))
However, for complicated statements, this can be quite messy to read. I will avoid using this style, and just use the indents(***).
3) If you have an if or else statement with nothing in it, you will get an error:
if(3 > 2):
yields a SyntaxError due to an unexpected end of file. To fix this, you can use the Pass command, which does nothing, but is included to ensure proper syntax. So this would be valid:

if(3 > 2):
    pass  #don't do anything
here, 3 is indeed bigger than 2, but we don't do anything, since we have the pass command inside the if block.

(*) The elif command is more useful for when we have more complicated logical chains, or when we are defining functions with recursion. We will cover this in the next section.
(**) As I have stated before, most text editors will have their own definition of an indent in Python. See the section "Basic Syntax" for more information.
(***) Even though they can be a pain to ensure they line up properly here.
Dylan14 is offline