Home » Chapter 3 : Decisions
if Statements
Very often in programming, we need to make decisions. Decisions can be simple or very complex. Python provides several ways to make decisions in the language. One of the first decision constructs in Python to consider is the if statement.
The general form of the if statement looks like this:
if condition:
code_block
The flowchart depicts the general form of the if statement as well. The execution flow represents the flow of the program up to the point of the if condition. When the if condition is evaluated by the interpreter, the result will be either True or False. If the result is True then execution flow moves into the code_block and that code runs. When it is finished flow continues to the next statement after the indented code_block. If, however, the if condition returns False, then the code_block is skipped and execution flow continues to the next statement after the indented code_block.
Let's take a look at an example:
low = 1
high = 10
secret_number = 8
print("Program started.")
guess = int(input("Enter your guess between " + str(low) + " and " + str(high) + ": "))
if guess == secret_number:
print("You guessed right!")
print("Program complete.")
Program started.
Enter your guess between 1 and 10: 8
You guessed right!
Program complete.
The if statement examples provided above contain a single condition (x == y for example), however, our conditions can be more complex and make several comparisons in one compound condition. To create more complex conditions, we need a way to connect more than one condition together, which we do with logical operators. Here is a list of the logical operators in Python:
if Statement w/Compound Condition: Write a Python program that prompts the user for their age. If their age is between 40 and 50 inclusive, print "You are middle-aged."
Please enter your age: 43
You are middle-aged.