If
The if statement used when you want to run certain code.
NOTE: Make sure that you tab or put four spaces after the if statement. Python is very sensitive about spaces.
if.py
age = 10 # The == means you are checking if age equals 10 if age == 10: print("I'm ", age) if age > 10: print("I'm more than 10") if age < 10: print("I'm less than 10")
Output:
10
Now change the age variable to 9.
Output:
I'm less than 10
Now change the age variable to 11.
Output:
I'm more than 10
More Comparisons
if2.py
age = 11 # The >= means you are checking if age greater than or equal to 10 if age >= 10: print("I'm greater than or equal to 10") if age <= 10: print("I'm less than or equal to 10")
Output:
I'm greater than or equal to 10
Now change the age variable to 9.
Output:
I'm less than or equal to 10
Not Equals
if3.py
age = 11 if age != 10: print("I'm not equal to 10")
Output:
I'm not equal to 10
Links
Exercises (5 mins)
-
What is wrong with this program? Can you fix it?
# Enter a number number = input("Enter a number: ") if number < 10: print(number, "is less than 10")
Complete the following program.
# Enter your first number first_input = input("Enter your first number: ") # Enter your second number second_input = # Convert inputs into numbers (first_number, second_number) first_number = int(first_input) second_number = # Check if the first number is smaller than the second number if first_number < second_number: print(first_number, "is less than", second_number) # Check if the first number is equal to the second number # Check if the first number is greater than the second number
Output:
Enter your first number: 1 Enter your second number: 2 1 is less than 2 Enter your first number: 3 Enter your second number: 2 3 is greater than 2 Enter your first number: 1 Enter your second number: 1 1 is equal to 1