Welcome to Control Flow! This tutorial will teach you how to make decisions and create logic in your programs. You’ll learn how to write code that can choose different paths based on conditions.
3.2 What is Control Flow?
Control flow is how your program makes decisions. Instead of just running code line by line, you can make your program: - Execute code only when certain conditions are met - Choose between different options - Skip code that isn’t needed
Think of it like a flowchart where your code can take different paths!
3.3 Comparison Operators
Before we make decisions, we need to know how to compare values. Comparison operators let you test relationships between values and always return True or False.
The Comparison Operators
Operator
Meaning
Example
Result
==
Equal to
5 == 5
True
!=
Not equal to
5 != 3
True
<
Less than
3 < 5
True
>
Greater than
5 > 3
True
<=
Less than or equal to
5 <= 5
True
>=
Greater than or equal to
5 >= 3
True
Comparison Examples
# Number comparisonsx =10y =5print(f"x = {x}, y = {y}")print(f"x == y: {x == y}") # Equal toprint(f"x != y: {x != y}") # Not equal toprint(f"x > y: {x > y}") # Greater thanprint(f"x < y: {x < y}") # Less thanprint(f"x >= y: {x >= y}") # Greater than or equalprint(f"x <= y: {x <= y}") # Less than or equal
x = 10, y = 5
x == y: False
x != y: True
x > y: True
x < y: False
x >= y: True
x <= y: False
Important: Use == for comparison and = for assignment!
# This is assignment (storing a value)age =25# This is comparison (checking equality)is_adult = age ==25print(f"Is adult? {is_adult}")
Is adult? True
3.4 The if Statement
The if statement lets you run code only when a condition is true.
Syntax:
if condition:# code to run if condition is True# must be indented!
Basic if Examples
# Simple if statementtemperature =30if temperature >25:print("It's hot outside! 🌞")print("Don't forget sunscreen!")
It's hot outside! 🌞
Don't forget sunscreen!
# Another exampleage =18if age >=18:print("You are an adult!")print("You can vote!")
You are an adult!
You can vote!
# Example where condition is Falsescore =45if score >=50:print("You passed!") # This won't print because condition is Falseprint("Test complete") # This always prints (not indented under if)
Test complete
Key Points: - The condition must end with a colon : - The code to run must be indented (usually 4 spaces) - If the condition is False, the indented code is skipped
3.5 The else Statement
The else statement provides an alternative when the if condition is False.
Syntax:
if condition:# runs if condition is Trueelse:# runs if condition is False
if-else Examples
# Simple if-elseage =15if age >=18:print("You can vote!")else:print("You're too young to vote.") years_until_voting =18- ageprint(f"Wait {years_until_voting} more years.")
You're too young to vote.
Wait 3 more years.
# Checking even or odd numbersnumber =7if number %2==0:print(f"{number} is even")else:print(f"{number} is odd")
7 is odd
# Password checkerpassword ="python123"iflen(password) >=8:print("✅ Password is strong enough")else:print("❌ Password is too short")print(f" Add {8-len(password)} more characters")
✅ Password is strong enough
3.6 The elif Statement
elif (short for “else if”) lets you check multiple conditions in sequence. It’s like saying “if not that, then check this instead.”
Syntax:
if condition1:# runs if condition1 is Trueelif condition2:# runs if condition1 is False and condition2 is Trueelse:# runs if all conditions are False
# Time of day greetinghour =14if hour <12: greeting ="Good morning!"elif hour <18: greeting ="Good afternoon!"else: greeting ="Good evening!"print(greeting)
Good afternoon!
Important: Python checks conditions in order and stops at the first True condition!
# Demonstrating order mattersx =15# This works correctlyif x >10:print("x is greater than 10")elif x >5:print("x is greater than 5") # Won't reach here even though it's true!
x is greater than 10
3.7 Logical Operators
You can combine multiple conditions using logical operators:
Operator
Meaning
Example
and
Both must be True
age >= 18 and has_license
or
At least one must be True
is_weekend or is_holiday
not
Reverses the condition
not is_raining
Logical Operator Examples
# Using 'and' - both conditions must be Trueage =20has_ticket =Trueif age >=18and has_ticket:print("✅ You can enter the concert!")else:print("❌ You cannot enter")
✅ You can enter the concert!
# More 'and' examplestemperature =25is_sunny =Trueif temperature >20and is_sunny:print("Perfect day for the beach! 🏖️")
Perfect day for the beach! 🏖️
# Using 'or' - at least one condition must be Trueday ="Saturday"if day =="Saturday"or day =="Sunday":print("It's the weekend! 🎉")else:print("It's a weekday 😴")
It's the weekend! 🎉
# Using 'not' - reverses the booleanis_raining =Falseifnot is_raining:print("Let's go outside!")else:print("Let's stay inside")
Let's go outside!
# Combining multiple logical operatorsage =25is_student =Truehas_id =Trueif age >=18and (is_student or age >=65) and has_id:print("✅ You qualify for a discount!")if is_student: discount =20else: discount =15print(f"Your discount: {discount}%")else:print("Regular price applies")
✅ You qualify for a discount!
Your discount: 20%
3.8 Nested if Statements
You can put if statements inside other if statements. This is called nesting.
Account found
✅ Purchase successful!
Remaining balance: $50
# Another nested exampleage =25has_license =Truehas_car =Falseif age >=18:print("Age requirement met")if has_license:print("License verified")if has_car:print("✅ You can drive!")else:print("⚠️ You need to rent a car")else:print("❌ You need a license")else:print("❌ You must be 18 or older")
Age requirement met
License verified
⚠️ You need to rent a car
Tip: Try to avoid too many nested levels. It makes code harder to read. Often you can use and instead:
# Instead of deeply nested ifs, use 'and'age =25has_license =Truehas_car =True# Clear and readableif age >=18and has_license and has_car:print("✅ You can drive!")else:print("❌ Requirements not met")
✅ You can drive!
3.9 The Membership Operator ‘in’
The in operator checks if a value exists in a sequence (like a string or list).
# Check if character is in stringword ="Python"if"y"in word:print("Found 'y' in Python")if"x"in word:print("Found 'x'")else:print("'x' is not in Python")
Found 'y' in Python
'x' is not in Python
# Check if item is in a listfruits = ["apple", "banana", "orange"]if"banana"in fruits:print("We have bananas! 🍌")if"grape"notin fruits:print("Sorry, no grapes available")
We have bananas! 🍌
Sorry, no grapes available
# Using 'in' with if-elif-elseuser_input ="yes"if user_input in ["yes", "y", "Yeah", "sure"]:print("Great! Let's proceed.")elif user_input in ["no", "n", "nope"]:print("Okay, maybe next time.")else:print("I didn't understand that.")
Great! Let's proceed.
3.10 Ternary Operator (Conditional Expression)
Python has a shorthand way to write simple if-else statements in one line.
Syntax:
value_if_true if condition else value_if_false
# Regular if-elseage =20if age >=18: status ="adult"else: status ="minor"print(status)# Same thing with ternary operatorage =20status ="adult"if age >=18else"minor"print(status)
adult
adult
# More ternary examplestemperature =28weather ="hot"if temperature >25else"comfortable"print(f"It's {weather}")score =85result ="Pass"if score >=50else"Fail"print(f"Result: {result}")number =7parity ="even"if number %2==0else"odd"print(f"{number} is {parity}")
It's hot
Result: Pass
7 is odd
When to use: Ternary operators are great for simple conditions, but use regular if-else for complex logic!
# Wrong - missing colonif age >=18print("Adult")# Correctif age >=18:print("Adult")
Mistake 2: Incorrect indentation
# Wrong - not indentedif age >=18:print("Adult")# Correctif age >=18:print("Adult")
Mistake 3: Using = instead of ==
# Wrong - this is assignment, not comparisonif age =18:print("Adult")# Correctif age ==18:print("Adult")
Mistake 4: Comparing different types
# Be careful with types!age_str ="18"# This is a stringage_num =18# This is a numberprint(age_str == age_num) # False! Different types# Solution: convert typesprint(int(age_str) == age_num) # True!
False
True
3.13 Practice Exercises
Now it’s your turn! Try these exercises:
Exercise 1: Number Classifier
Write code to classify a number as positive, negative, or zero.
number =-5# Your code here:# Print whether the number is positive, negative, or zero
Exercise 2: Ticket Price Calculator
Calculate ticket prices based on age: - Under 3: Free - 3-12: $10 - 13-64: $25 - 65+: $15
age =8# Your code here:# Calculate and print the ticket price
Exercise 3: Leap Year Checker
A year is a leap year if: - It’s divisible by 4 AND - If it’s divisible by 100, it must also be divisible by 400
year =2024# Your code here:# Print whether it's a leap year or not
Exercise 4: Grade with Plus/Minus
Expand the grade calculator to include + and - grades: - 93-100: A - 90-92: A- - 87-89: B+ - 83-86: B - 80-82: B- - etc.
score =87# Your code here:# Print the grade with + or -
3.14 Solutions
Solution 1: Number Classifier
Click to show solution
number =-5if number >0:print(f"{number} is positive")elif number <0:print(f"{number} is negative")else:print(f"{number} is zero")
-5 is negative
Solution 2: Ticket Price Calculator
Click to show solution
age =8if age <3: price =0print(f"Age {age}: Free!")elif age <=12: price =10print(f"Age {age}: Child ticket - ${price}")elif age <=64: price =25print(f"Age {age}: Adult ticket - ${price}")else: price =15print(f"Age {age}: Senior ticket - ${price}")
Age 8: Child ticket - $10
Solution 3: Leap Year Checker
Click to show solution
year =2024if year %4==0:if year %100==0:if year %400==0:print(f"{year} is a leap year! 🎉")else:print(f"{year} is not a leap year")else:print(f"{year} is a leap year! 🎉")else:print(f"{year} is not a leap year")# Alternative solution using 'and'/'or'if (year %4==0and year %100!=0) or (year %400==0):print(f"{year} is a leap year! 🎉")else:print(f"{year} is not a leap year")
Comparison Operators: Use ==, !=, <, >, <=, >= to compare values
if statement: Runs code only when condition is True
else statement: Provides alternative when condition is False
elif statement: Checks multiple conditions in sequence
Logical operators: Use and, or, not to combine conditions
Indentation matters: Code blocks must be properly indented
Order matters: Python checks conditions from top to bottom
Use == for comparison, = for assignment
3.16 Quick Reference Card
# Basic ifif condition:# code# if-elseif condition:# codeelse:# code# if-elif-elseif condition1:# codeelif condition2:# codeelse:# code# Logical operatorsif condition1 and condition2: # Both must be Trueif condition1 or condition2: # At least one must be Trueifnot condition: # Reverse the condition# Ternaryvalue = true_result if condition else false_result
3.17 Next Steps
Now that you understand control flow, you’re ready to learn: - Loops - Repeating code with for and while - Functions - Organizing code into reusable blocks - Lists and Dictionaries - Working with collections of data - Error handling - Using try/except blocks
Keep practicing! The more you write conditional statements, the more natural they’ll become. Control flow is fundamental to all programming! 🚀
---title: "Control Flow"jupyter: python3---## Making Decisions in PythonWelcome to Control Flow! This tutorial will teach you how to make decisions and create logic in your programs. You'll learn how to write code that can choose different paths based on conditions.## What is Control Flow?Control flow is how your program makes decisions. Instead of just running code line by line, you can make your program:- Execute code only when certain conditions are met- Choose between different options- Skip code that isn't neededThink of it like a flowchart where your code can take different paths!## Comparison OperatorsBefore we make decisions, we need to know how to compare values. Comparison operators let you test relationships between values and always return `True` or `False`.### The Comparison Operators {.unnumbered}| Operator | Meaning | Example | Result ||----------|---------|---------|--------|| `==` | Equal to | `5 == 5` | `True` || `!=` | Not equal to | `5 != 3` | `True` || `<` | Less than | `3 < 5` | `True` || `>` | Greater than | `5 > 3` | `True` || `<=` | Less than or equal to | `5 <= 5` | `True` || `>=` | Greater than or equal to | `5 >= 3` | `True` |### Comparison Examples {.unnumbered}```{python}# Number comparisonsx =10y =5print(f"x = {x}, y = {y}")print(f"x == y: {x == y}") # Equal toprint(f"x != y: {x != y}") # Not equal toprint(f"x > y: {x > y}") # Greater thanprint(f"x < y: {x < y}") # Less thanprint(f"x >= y: {x >= y}") # Greater than or equalprint(f"x <= y: {x <= y}") # Less than or equal``````{python}# String comparisonsname1 ="Alice"name2 ="Bob"name3 ="Alice"print(f"\nString comparisons:")print(f"'{name1}' == '{name2}': {name1 == name2}")print(f"'{name1}' == '{name3}': {name1 == name3}")print(f"'{name1}' != '{name2}': {name1 != name2}")```**Important:** Use `==` for comparison and `=` for assignment!```{python}# This is assignment (storing a value)age =25# This is comparison (checking equality)is_adult = age ==25print(f"Is adult? {is_adult}")```## The if StatementThe `if` statement lets you run code only when a condition is true.**Syntax:**```pythonif condition:# code to run if condition is True# must be indented!```### Basic if Examples {.unnumbered}```{python}# Simple if statementtemperature =30if temperature >25:print("It's hot outside! 🌞")print("Don't forget sunscreen!")``````{python}# Another exampleage =18if age >=18:print("You are an adult!")print("You can vote!")``````{python}# Example where condition is Falsescore =45if score >=50:print("You passed!") # This won't print because condition is Falseprint("Test complete") # This always prints (not indented under if)```**Key Points:**- The condition must end with a colon `:`- The code to run must be **indented** (usually 4 spaces)- If the condition is `False`, the indented code is skipped## The else StatementThe `else` statement provides an alternative when the `if` condition is `False`.**Syntax:**```pythonif condition:# runs if condition is Trueelse:# runs if condition is False```### if-else Examples {.unnumbered}```{python}# Simple if-elseage =15if age >=18:print("You can vote!")else:print("You're too young to vote.") years_until_voting =18- ageprint(f"Wait {years_until_voting} more years.")``````{python}# Checking even or odd numbersnumber =7if number %2==0:print(f"{number} is even")else:print(f"{number} is odd")``````{python}# Password checkerpassword ="python123"iflen(password) >=8:print("✅ Password is strong enough")else:print("❌ Password is too short")print(f" Add {8-len(password)} more characters")```## The elif Statement`elif` (short for "else if") lets you check multiple conditions in sequence. It's like saying "if not that, then check this instead."**Syntax:**```pythonif condition1:# runs if condition1 is Trueelif condition2:# runs if condition1 is False and condition2 is Trueelse:# runs if all conditions are False```### elif Examples {.unnumbered}```{python}# Grade calculatorscore =85if score >=90: grade ="A"elif score >=80: grade ="B"elif score >=70: grade ="C"elif score >=60: grade ="D"else: grade ="F"print(f"Score: {score}")print(f"Grade: {grade}")``````{python}# Temperature descriptiontemp =15if temp >30: description ="very hot" emoji ="🥵"elif temp >20: description ="warm" emoji ="😊"elif temp >10: description ="cool" emoji ="😌"elif temp >0: description ="cold" emoji ="🥶"else: description ="freezing" emoji ="🧊"print(f"It's {description} at {temp}°C {emoji}")``````{python}# Time of day greetinghour =14if hour <12: greeting ="Good morning!"elif hour <18: greeting ="Good afternoon!"else: greeting ="Good evening!"print(greeting)```**Important:** Python checks conditions in order and stops at the first `True` condition!```{python}# Demonstrating order mattersx =15# This works correctlyif x >10:print("x is greater than 10")elif x >5:print("x is greater than 5") # Won't reach here even though it's true!```## Logical OperatorsYou can combine multiple conditions using logical operators:| Operator | Meaning | Example ||----------|---------|---------|| `and` | Both must be True | `age >= 18 and has_license` || `or` | At least one must be True | `is_weekend or is_holiday` || `not` | Reverses the condition | `not is_raining` |### Logical Operator Examples {.unnumbered}```{python}# Using 'and' - both conditions must be Trueage =20has_ticket =Trueif age >=18and has_ticket:print("✅ You can enter the concert!")else:print("❌ You cannot enter")``````{python}# More 'and' examplestemperature =25is_sunny =Trueif temperature >20and is_sunny:print("Perfect day for the beach! 🏖️")``````{python}# Using 'or' - at least one condition must be Trueday ="Saturday"if day =="Saturday"or day =="Sunday":print("It's the weekend! 🎉")else:print("It's a weekday 😴")``````{python}# Using 'not' - reverses the booleanis_raining =Falseifnot is_raining:print("Let's go outside!")else:print("Let's stay inside")``````{python}# Combining multiple logical operatorsage =25is_student =Truehas_id =Trueif age >=18and (is_student or age >=65) and has_id:print("✅ You qualify for a discount!")if is_student: discount =20else: discount =15print(f"Your discount: {discount}%")else:print("Regular price applies")```## Nested if StatementsYou can put `if` statements inside other `if` statements. This is called nesting.```{python}# Nested if examplehas_account =Truebalance =150purchase_amount =100if has_account:print("Account found")if balance >= purchase_amount: balance = balance - purchase_amountprint(f"✅ Purchase successful!")print(f"Remaining balance: ${balance}")else:print("❌ Insufficient funds")print(f"You need ${purchase_amount - balance} more")else:print("❌ No account found")``````{python}# Another nested exampleage =25has_license =Truehas_car =Falseif age >=18:print("Age requirement met")if has_license:print("License verified")if has_car:print("✅ You can drive!")else:print("⚠️ You need to rent a car")else:print("❌ You need a license")else:print("❌ You must be 18 or older")```**Tip:** Try to avoid too many nested levels. It makes code harder to read. Often you can use `and` instead:```{python}# Instead of deeply nested ifs, use 'and'age =25has_license =Truehas_car =True# Clear and readableif age >=18and has_license and has_car:print("✅ You can drive!")else:print("❌ Requirements not met")```## The Membership Operator 'in'The `in` operator checks if a value exists in a sequence (like a string or list).```{python}# Check if character is in stringword ="Python"if"y"in word:print("Found 'y' in Python")if"x"in word:print("Found 'x'")else:print("'x' is not in Python")``````{python}# Check if item is in a listfruits = ["apple", "banana", "orange"]if"banana"in fruits:print("We have bananas! 🍌")if"grape"notin fruits:print("Sorry, no grapes available")``````{python}# Using 'in' with if-elif-elseuser_input ="yes"if user_input in ["yes", "y", "Yeah", "sure"]:print("Great! Let's proceed.")elif user_input in ["no", "n", "nope"]:print("Okay, maybe next time.")else:print("I didn't understand that.")```## Ternary Operator (Conditional Expression)Python has a shorthand way to write simple if-else statements in one line.**Syntax:**```pythonvalue_if_true if condition else value_if_false``````{python}# Regular if-elseage =20if age >=18: status ="adult"else: status ="minor"print(status)# Same thing with ternary operatorage =20status ="adult"if age >=18else"minor"print(status)``````{python}# More ternary examplestemperature =28weather ="hot"if temperature >25else"comfortable"print(f"It's {weather}")score =85result ="Pass"if score >=50else"Fail"print(f"Result: {result}")number =7parity ="even"if number %2==0else"odd"print(f"{number} is {parity}")```**When to use:** Ternary operators are great for simple conditions, but use regular if-else for complex logic!## Real-World Examples### Example 1: Login System {.unnumbered}```{python}# Simple login validatorusername ="alice"password ="secret123"correct_username ="alice"correct_password ="secret123"if username == correct_username and password == correct_password:print("✅ Login successful!")print(f"Welcome back, {username}!")elif username == correct_username:print("❌ Incorrect password")else:print("❌ Username not found")```### Example 2: Shipping Calculator {.unnumbered}```{python}# Calculate shipping cost based on weight and destinationweight =5# kgdestination ="international"if destination =="local":if weight <=1: shipping_cost =5elif weight <=5: shipping_cost =10else: shipping_cost =15elif destination =="international":if weight <=1: shipping_cost =20elif weight <=5: shipping_cost =40else: shipping_cost =60else: shipping_cost =0print("Invalid destination")if shipping_cost >0:print(f"Weight: {weight}kg")print(f"Destination: {destination}")print(f"Shipping cost: ${shipping_cost}")```### Example 3: BMI Calculator {.unnumbered}```{python}# Body Mass Index calculator with interpretationweight_kg =70height_m =1.75bmi = weight_kg / (height_m **2)print(f"Your BMI: {bmi:.1f}")if bmi <18.5: category ="Underweight" emoji ="⚠️"elif bmi <25: category ="Normal weight" emoji ="✅"elif bmi <30: category ="Overweight" emoji ="⚠️"else: category ="Obese" emoji ="🚨"print(f"{emoji} Category: {category}")```## Common Mistakes to Avoid### Mistake 1: Forgetting the colon {.unnumbered}```{python}#| eval: false# Wrong - missing colonif age >=18print("Adult")# Correctif age >=18:print("Adult")```### Mistake 2: Incorrect indentation {.unnumbered}```{python}#| eval: false# Wrong - not indentedif age >=18:print("Adult")# Correctif age >=18:print("Adult")```### Mistake 3: Using = instead of == {.unnumbered}```{python}#| eval: false# Wrong - this is assignment, not comparisonif age =18:print("Adult")# Correctif age ==18:print("Adult")```### Mistake 4: Comparing different types {.unnumbered}```{python}# Be careful with types!age_str ="18"# This is a stringage_num =18# This is a numberprint(age_str == age_num) # False! Different types# Solution: convert typesprint(int(age_str) == age_num) # True!```## Practice ExercisesNow it's your turn! Try these exercises:### Exercise 1: Number Classifier {.unnumbered}Write code to classify a number as positive, negative, or zero.```{python}#| eval: falsenumber =-5# Your code here:# Print whether the number is positive, negative, or zero```### Exercise 2: Ticket Price Calculator {.unnumbered}Calculate ticket prices based on age:- Under 3: Free- 3-12: $10- 13-64: $25- 65+: $15```{python}#| eval: falseage =8# Your code here:# Calculate and print the ticket price```### Exercise 3: Leap Year Checker {.unnumbered}A year is a leap year if:- It's divisible by 4 AND- If it's divisible by 100, it must also be divisible by 400```{python}#| eval: falseyear =2024# Your code here:# Print whether it's a leap year or not```### Exercise 4: Grade with Plus/Minus {.unnumbered}Expand the grade calculator to include + and - grades:- 93-100: A- 90-92: A-- 87-89: B+- 83-86: B- 80-82: B-- etc.```{python}#| eval: falsescore =87# Your code here:# Print the grade with + or -```## Solutions### Solution 1: Number Classifier {.unnumbered}```{python}#| code-fold: true#| code-summary: "Click to show solution"number =-5if number >0:print(f"{number} is positive")elif number <0:print(f"{number} is negative")else:print(f"{number} is zero")```### Solution 2: Ticket Price Calculator {.unnumbered}```{python}#| code-fold: true#| code-summary: "Click to show solution"age =8if age <3: price =0print(f"Age {age}: Free!")elif age <=12: price =10print(f"Age {age}: Child ticket - ${price}")elif age <=64: price =25print(f"Age {age}: Adult ticket - ${price}")else: price =15print(f"Age {age}: Senior ticket - ${price}")```### Solution 3: Leap Year Checker {.unnumbered}```{python}#| code-fold: true#| code-summary: "Click to show solution"year =2024if year %4==0:if year %100==0:if year %400==0:print(f"{year} is a leap year! 🎉")else:print(f"{year} is not a leap year")else:print(f"{year} is a leap year! 🎉")else:print(f"{year} is not a leap year")# Alternative solution using 'and'/'or'if (year %4==0and year %100!=0) or (year %400==0):print(f"{year} is a leap year! 🎉")else:print(f"{year} is not a leap year")```### Solution 4: Grade with Plus/Minus {.unnumbered}```{python}#| code-fold: true#| code-summary: "Click to show solution"score =87if score >=93: grade ="A"elif score >=90: grade ="A-"elif score >=87: grade ="B+"elif score >=83: grade ="B"elif score >=80: grade ="B-"elif score >=77: grade ="C+"elif score >=73: grade ="C"elif score >=70: grade ="C-"elif score >=67: grade ="D+"elif score >=63: grade ="D"elif score >=60: grade ="D-"else: grade ="F"print(f"Score: {score} = Grade: {grade}")```## Key Takeaways✨ **Remember:**1. **Comparison Operators:** Use `==`, `!=`, `<`, `>`, `<=`, `>=` to compare values2. **if statement:** Runs code only when condition is `True`3. **else statement:** Provides alternative when condition is `False`4. **elif statement:** Checks multiple conditions in sequence5. **Logical operators:** Use `and`, `or`, `not` to combine conditions6. **Indentation matters:** Code blocks must be properly indented7. **Order matters:** Python checks conditions from top to bottom8. **Use `==` for comparison, `=` for assignment**## Quick Reference Card```python# Basic ifif condition:# code# if-elseif condition:# codeelse:# code# if-elif-elseif condition1:# codeelif condition2:# codeelse:# code# Logical operatorsif condition1 and condition2: # Both must be Trueif condition1 or condition2: # At least one must be Trueifnot condition: # Reverse the condition# Ternaryvalue = true_result if condition else false_result```## Next StepsNow that you understand control flow, you're ready to learn:- **Loops** - Repeating code with `for` and `while`- **Functions** - Organizing code into reusable blocks- **Lists and Dictionaries** - Working with collections of data- **Error handling** - Using try/except blocksKeep practicing! The more you write conditional statements, the more natural they'll become. Control flow is fundamental to all programming! 🚀