if and else
temperature = int(input("Temperature: ")) if temperature > 30: print("It is hot") else: print("It is pleasant")
Uses the input 34
Write Python. Understand every error.
Python basics · topic 8 of 25
An if statement runs a block of code only when a condition is True. The line ends with a colon, and the block below is indented by 4 spaces.
marks = 55 if marks >= 40: print("Pass") else: print("Fail")
else runs when the condition is false. To check several conditions in turn, use elif (short for "else if"). Python checks from the top and runs only the first block whose condition is true.
if marks >= 90: print("A") elif marks >= 60: print("B") else: print("C")
if, elif and else line ends with :.== to compare, never =.and and or.if, elif and else line ends with a colon, and the indented lines below it belong to that branch.== to compare and = to store.and and or. Python also allows chained comparisons such as 60 <= m < 80.if line. Read the SyntaxError guide.if x = 5: instead of if x == 5:. Read the SyntaxError guide.
temperature = int(input("Temperature: ")) if temperature > 30: print("It is hot") else: print("It is pleasant")
Uses the input 34
marks = 72 if marks >= 90: print("Grade A") elif marks >= 75: print("Grade B") elif marks >= 40: print("Grade C") else: print("Fail")
age = 25 member = False if age >= 18 and member: print("Welcome back") elif age >= 18: print("Please register") else: print("Too young")
5 quick questions to check your understanding. Choose an answer for each, then press Check answers.
x = 15 if x > 10: print("big") elif x > 5: print("medium") else: print("small")
Only the first branch whose condition is True runs.
x = 7 if x % 2 == 0: print("even") else: print("odd")
7 % 2 is 1, not 0, so the else branch runs.
if x = 5:?Use == to compare. A single = stores a value, so Python reports a SyntaxError.
age = 20 print("adult" if age >= 18 else "minor")
This is a one-line if/else (a conditional expression).
m = 72 if 60 <= m < 80: print("B") else: print("other")
Python allows chained comparisons: 60 <= 72 < 80 is True.