Python Programming/Conditional Statements

Decisions
A Decision is when a program has more than one choice of actions depending on a variable's value. Think of a traffic light. When it is green, we continue our drive. When we see the light turn yellow, we reduce our speed, and when it is red, we stop. These are logical decisions that depend on the value of the traffic light. Luckily, Python has a decision statement to help us when our application needs to make such decision for the user.

If statements
Here is a warm-up exercise - a short program to compute the absolute value of a number:

absoval.py

Here is the output from the two times that I ran this program: Integer? -34 The absolute value of -34 is 34

Integer? 1 The absolute value of 1 is 1

What does the computer do when it sees this piece of code? First it prompts the user for a number with the statement "n = input("Integer? ")". Next it reads the line "if n < 0:". If  n is less than zero Python runs the line "print ("The absolute value of",n,"is",-n)". Otherwise python runs the line "print ("The absolute value of",n,"is",n)".

More formally, Python looks at whether the expression  n < 0 is true or false. An  if statement is followed by an indented block of statements that are run when the expression is true. After the <tt> if</tt> statement is an optional <tt> else</tt> statement and another indented block of statements. This 2nd block of statements is run if the expression is false.

Expressions can be tested several different ways. Here is a table of all of them:

Another feature of the <tt> if</tt> command is the <tt> elif </tt> statement. It stands for "else if," which means that if the original <tt> if</tt> statement is false and the <tt> elif</tt> statement is true, execute the block of code following the <tt>elif</tt> statement. Here's an example:

ifloop.py

and the output:

1 <= 7 2 <= 7 3 <= 7 4 <= 7 5 <= 7 6 > 5 7 > 5 8 > 5 9 > 5 10 > 5

Notice how the <tt> elif a <= 7</tt> is only tested when the <tt> if</tt> statement fails to be true. <tt> elif</tt> allows multiple tests to be done in a single if statement.

If Example
Sample run: Let's play the guessing game! What number am I thinking of? 22 Little higher What number am I thinking of? 25 Little Lower What number am I thinking of? 23 MINDREADER!!!

As it states in its comments, this code is not prepared to handle invalid input (i.e., strings instead of numbers). If you are wondering how you would implement such functionality in Python, you are referred to the Errors Chapter of this book, where you will learn about error handling. For the above code you may try this slight modification of the <tt>while</tt> loop:

Sample runs. Tell me a number: 3 3 is odd.

Tell me a number: 2 2 is even.

Tell me a number: 3.14159 3.14159 is very strange.

Sample runs Welcome to the average calculator program NOTE- THIS PROGRAM ONLY CALCULATES AVERAGES FOR 3 NUMBERS Please enter the first number 7 Please enter the second number 6 Please enter the third number 4 5.66666666667

Sample runs This program will take several numbers, then average them. How many numbers would you like to sum: 2 Number 0 Enter a number: 3 Number 1 Enter a number: 5 The average was: 4.0

This program will take several numbers, then average them. How many numbers would you like to sum: 3 Number 0 Enter a number: 1 Number 1 Enter a number: 4 Number 2 Enter a number: 3 The average was: 2.66666666667

Sample runs Welcome to the Average Calculator, please insert a number New number 1 The current average is 1.0 New number 3 The current average is 2.0 New number 6 The current average is 3.333 New number 6 The current average is 4.0 New number

If Exercises

 * 1) Write a password guessing program to keep track of how many times the user has entered the password wrong. If it is more than 3 times, print You have been denied access. and terminate the program. If the password is correct, print You have successfully logged in. and terminate the program.
 * 2) Write a program that asks for two numbers. If the sum of the numbers is greater than 100, print That is a big number and terminate the program.
 * 3) Write a program that asks the user their name. If they enter your name, say "That is a nice name."  If they enter "John Cleese" or "Michael Palin", tell them how you feel about them ;), otherwise tell them "You have a nice name."
 * 4) Ask the user to enter the password. If the password is correct print "You have successfully logged in" and exit the program. If the password is wrong print "Sorry the password is wrong" and ask the user to enter the password 3 times. If the password is wrong print "You have been denied access" and exit the program.

Conditional Statements
Many languages (like Java and PHP) have the concept of a one-line conditional (called The Ternary Operator), often used to simplify conditionally accessing a value. For instance (in Java):

For many years Python did not have the same construct natively, however you could replicate it by constructing a tuple of results and calling the test as the index of the tuple, like so:

It is important to note that, unlike a built in conditional statement, both the true and false branches are evaluated before returning, which can lead to unexpected results and slower executions if you're not careful. To resolve this issue, and as a better practice, wrap whatever you put in the tuple in anonymous function calls (lambda notation) to prevent them from being evaluated until the desired branch is called:

Since Python 2.5 however, there has been an equivalent operator to The Ternary Operator (though not called such, and with a totally different syntax):

Switch
A switch is a control statement present in most computer programming languages to minimize a bunch of If - elif statements. The switch case functionality was added to Python 3.10 with a new syntax called match case. Prior to version 3.10 switch was not officially supported. The switch statement can be recreated by cleverly using an array or dictionary.

This works because Python stores a reference of the function in the array at its particular index, and by adding a pair of parentheses we are actually calling the function. Here the last line is equivalent to:

Another way
Another way is to use lambdas. Code pasted here with permissions1

For more information on lambda see anonymous functions in the function section.