Branching and Conditional Operators in Python for Beginners
In many programs, you need to run a part of the code only when a specific condition is met. For example, if a user enters incorrect data, you need to show an error message.
To execute code only when a condition is met, use the if statement.
The simplest way to understand this statement is through an example. Let’s write a “Guess the Number” program. If you’re a beginner, try writing this program yourself to get hands-on experience. The computer picks a random number, the player tries to guess it, and the program tells the user if their guess is correct.
import random
num = random.randint(1, 10)
guess = int(input('Enter a number from 1 to 10: '))
if guess == num:
print('You guessed it!')
The syntax of the if statement is straightforward: write the keyword if, followed by the condition, and end the line with a colon.
All lines of code that should run when the condition is true must be indented by four spaces relative to the if keyword. Python uses indentation to determine which lines belong to the if statement and will execute them only if the condition is true. In our example, “You guessed it!” will only print if the user enters the correct number.
We’ll discuss modules later, but for now, know that random.randint gets a random number, and import random loads the module for working with random numbers into our program. You can explore what this module can do on this page. For now, let’s continue with conditions:
import random
num = random.randint(1, 10)
guess = int(input('Enter a number from 1 to 10: '))
if guess == num:
print('You guessed it!')
else:
print('Sorry, the number was', num)
We added the else statement, which runs code if the if condition is false. This combination can be read as “if a condition is true, run this code; otherwise, run some other code.”
Besides if and else, you can use elif for more complex conditions. For example, we can enhance our “Guess the Number” game with additional checks to see if the entered number is out of bounds:
import random
num = random.randint(1, 10)
guess = int(input('Enter a number from 1 to 10: '))
if guess == num:
print('You guessed it!')
elif guess > 10:
print('The number cannot be greater than 10')
elif guess < 1:
print('The number cannot be less than 1')
else:
print('Sorry, the number was', num)