Control Flow in Python

Control flow in Python includes the use of various statements such as if, elif, else, for, while, break, continue, pass, and match.

Here’s an example of how these statements can be used in a Python program:

# Example of control flow in Python

# Using if, elif, and else statements
x = int(input(“Please enter an integer: “))
if x < 0:
x = 0
print(‘Negative changed to zero’)
elif x == 0:
print(‘Zero’)
elif x == 1:
print(‘Single’)
else:
print(‘More’)

# Using for loop
words = [‘cat’, ‘window’, ‘defenestrate’] for w in words:
print(w, len(w))

# Using while loop
i = 0
while i < 5:
print(i)
i += 1

# Using break statement
for i in range(10):
if i == 5:
break
print(i)

# Using continue statement
for num in range(2, 10):
if num % 2 == 0:
print(“Found an even number”, num)
continue
print(“Found an odd number”, num)

# Using pass statement
while True:
pass # Busy-wait for keyboard interrupt (Ctrl+C)

# Using match statement
def http_error(status):
match status:
case 400:
return “Bad request”
case 404:
return “Not found”
case 418:
return “I’m a teapot”
case _:
return “Something’s wrong with the internet”

The above code demonstrates the use of various control flow statements in Python, including if, elif, else, for, while, break, continue, pass, and match statements.

Related posts:

About Author


Discover more from SURFCLOUD TECHNOLOGY

Subscribe to get the latest posts sent to your email.

Leave a Reply

Your email address will not be published. Required fields are marked *

Discover more from SURFCLOUD TECHNOLOGY

Subscribe now to keep reading and get access to the full archive.

Continue reading