Python - Conditions and Loops
If and Else
Types of Conditional Statements in Python
if condition: # code to execute if condition is truenum = 8 if num > 0: print("The number is positive.")
if condition: # code to execute if condition is true else: # code to execute if condition is falsenum = 11 if num % 2 == 0: print("The number is even.") else: print("The number is odd.")
if condition1: if condition2: # code for both conditions being true else: # code for condition1 true, condition2 false else: # code for condition1 falsenum = 3 if num > 0: if num % 2 == 0: print("The number is positive and even.") else: print("The number is positive but odd.") else: print("The number is not positive.")
if condition1: # code block 1 elif condition2: # code block 2 elif condition3: # code block 3 else: # default code blockx = 11 if x == 2: print("x is equal to 2") elif x == 3: print("x is equal to 3") elif x == 4: print("x is equal to 4") else: print("x is not equal to 2, 3, or 4")
value_if_true if condition else value_if_falseresult = 'pass' if grade >= 50 else 'fail' print(result)
While loop
For loop
Types of for Loops in Python
for Loops in PythonLast updated