if and else
Section 3: ConditionsLesson 3.1 · ⏱ 8 min
if asks a question: if it is true, it runs the indented lines under it. And else is for everything else. Notice the colon : and the indent of four spaces.
age = int(input("Age? "))
if age >= 10:
print("You can join the robotics team!")
else:
print("Wait a little and join us")
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗Age? 12 You can join the robotics team!
==equals, and!=does not equal.>bigger,<smaller, and>=bigger or equal.
📌 Another example: even or odd
The remainder when dividing by 2: zero = even.
When the program asks, we type: 7.
n = int(input("A number: "))
if n % 2 == 0:
print(n, "is even")
else:
print(n, "is odd")
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗A number: 7 7 is odd
✍️ Practise
Try the lesson's examples here: copy the code, change it, and click ▶ Run.
✍️ Practise here in the lesson✖ Close the labor open the lab in a new page ↗
🎯 Challenge yourself
Easy
Ask for the age: 18 or more = adult, otherwise child.
👀 Show the solution🙈 Hide the solution
When the program asks, we type: 12.
age = int(input("Age: "))
if age >= 18:
print("adult")
else:
print("child")
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗Age: 12 child
Result: child
Medium
Ask for the temperature: above 30 = hot, otherwise nice.
👀 Show the solution🙈 Hide the solution
When the program asks, we type: 36.
t = int(input("Temperature: "))
if t > 30:
print("hot")
else:
print("nice")
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗Temperature: 36 hot
Result: hot
Hard
Ask for two numbers, and print the bigger one.
👀 Show the solution🙈 Hide the solution
When the program asks, we type: 4, then 9.
a = int(input("a: "))
b = int(input("b: "))
if a > b:
print("bigger:", a)
else:
print("bigger:", b)
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗a: 4 b: 9 bigger: 9
Result: bigger: 9

