This tutorial is designed to guide you through best practices in controlling flow in Python. The goal is to build a solid understanding of how to use If-Else and Elif statements, For and While loops, as well as Break, Continue, and Pass statements in Python effectively.
By the end of this tutorial, you will be able to:
- Understand the concept of control flow in Python
- Write If-Else and Elif statements effectively.
- Use For and While loops efficiently.
- Understand and properly use Break, Continue, and Pass statements.
The prerequisites for this tutorial are basic knowledge of Python programming.
if
statement checks a condition. If the condition is true, it executes the block of code inside it.elif
statement (which stands for else if) checks another condition if the previous if
condition wasn't met.else
statement executes a block of code if none of the previous conditions were met.for
loop goes through items in a sequence one by one, executing a block of code for each item.while
loop continues as long as a certain condition is met.break
statement stops the loop and moves the control flow to the statement following the loop.continue
statement stops the current iteration and moves the control flow to the next iteration of the loop.pass
statement is used when you need a statement for syntax purposes, but you don't want to do anything.# Define a variable
a = 10
# If statement
if a > 0:
print("a is positive")
# Elif statement
elif a < 0:
print("a is negative")
# Else statement
else:
print("a is zero")
Expected output: a is positive
# For loop
for i in range(3):
print(i)
# Expected output: 0, 1, 2
# While loop
counter = 0
while counter < 3:
print(counter)
counter += 1
# Expected output: 0, 1, 2
# Break statement
for i in range(5):
if i == 2:
break
print(i)
# Expected output: 0, 1
# Continue statement
for i in range(5):
if i == 2:
continue
print(i)
# Expected output: 0, 1, 3, 4
# Pass statement
if True:
pass
In this tutorial, you learned how to use control flow statements in Python effectively. You learned how to use If-Else and Elif statements, For and While loops, as well as Break, Continue, and Pass statements. You also saw examples of how to use these concepts.
Next steps would include learning about functions in Python, which would allow you to create reusable pieces of code. You should also learn about exception handling for dealing with error conditions.
# For loop with if statement
for i in range(11):
if i % 2 == 0:
print(i)
# User input with for loop and if statement
num = int(input("Enter a number: "))
for i in range(1, num + 1):
if num % i == 0:
print(i)
Continue practicing and writing code. Try to solve more complex problems. Happy coding!