Control flow and conditional statements
Pythons Tutorials
Control flow is like the GPS for your code. It guides your program’s execution, ensuring it follows the right route. The following are some of the ways you can control the flow of your code.
1. If Statements:
With if
statements, you can create decision points in your code. If a condition is met, certain code blocks are executed.
Example: Simple If Statement
temperature = 25
if temperature > 20:
print("It's a warm day!")
2.If-Else Statements(Alternatives)
Sometimes, you want to account for both scenarios. That’s where if-else
statements come in, allowing your code to choose between two paths.
Example: If-Else Statement
age = 17
if age >= 18:
print("You can vote!")
else:
print("Sorry, you're not old enough to vote yet.")
3.Elif Statements(Multiple Options)
When you have multiple conditions to check, elif
(short for “else if”) Let you explore several possibilities.
Example: Elif Statement
grade = 85
if grade >= 90:
print("You got an A!")
elif grade >= 80:
print("You got a B.")
else:
print("You can do better next time!")
5. Nested Conditional Statements:
Sometimes, you need conditions within conditions. Nested statements allow you to achieve that by layering your logic.
Example: Nested If Statements
is_raining = True
has_umbrella = False
if is_raining:
print("It's raining!")
if not has_umbrella:
print("And you forgot your umbrella. Stay dry!")
Now, a quick note on indentation: In Python, spaces or tabs are used to show which code is inside a certain block. It’s crucial for readability and understanding. Remember, consistent indentation is your code’s best friend!