Skip to content

Sample code for the article on control flow #666

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions python-control-flow/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Control Flow Structures in Python

This folder provides the code examples for the Real Python tutorial [Control Flow Structures in Python](https://realpython.com/python-control-flow/).
30 changes: 30 additions & 0 deletions python-control-flow/call_api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import os
import random


def main():
user_key = input("Please enter your API key: ")
os.environ["API_KEY"] = user_key
print(f"Temporary API key set: {os.environ['API_KEY']}")

try:
run_api_call(os.environ["API_KEY"])
except Exception as e:
print(f"Error: {e}")
else:
print("API call completed successfully.")
finally:
del os.environ["API_KEY"]
print("API key cleaned up!")


def run_api_call(api_key):
# Simulate an API call
if random.choice([True, False]):
print(f"Running API call with key: {api_key}")
else:
raise Exception("API call failed.")


if __name__ == "__main__":
main()
13 changes: 13 additions & 0 deletions python-control-flow/comprehensions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
emails = [
" alice@example.org ",
"BOB@example.com",
"charlie@EXAMPLE.com",
"David@example.net",
" bob@example.com",
"JohnDoe@example.com",
"DAVID@Example.net",
]

# emails = [email.strip().lower() for email in emails]

emails = {email.strip().lower() for email in emails}
9 changes: 9 additions & 0 deletions python-control-flow/continue.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
for i in range(5):
print("Before continue")
continue
# print("After continue")

for i in range(5):
print("Before break")
break
# print("After break")
17 changes: 17 additions & 0 deletions python-control-flow/else_loop.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
numbers = [1, 3, 5, 9]

target = 7
for number in numbers:
if number == target:
print("Found!")
break
else:
print("Not found.")

target = 3
for number in numbers:
if number == target:
print("Found!")
break
else:
print("Not found.")
30 changes: 30 additions & 0 deletions python-control-flow/fizz_buzz.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
def fizzbuzz_bad(number):
if number % 3 == 0:
return "fizz"
elif number % 5 == 0:
return "buzz"
elif number % 15 == 0:
return "fizz buzz"
else:
return number


def fizzbuzz_good(number):
if number % 15 == 0:
return "fizz buzz"
elif number % 3 == 0:
return "fizz"
elif number % 5 == 0:
return "buzz"
else:
return number


def fizzbuzz_better(number):
if number % 15 == 0:
return "fizz buzz"
if number % 3 == 0:
return "fizz"
if number % 5 == 0:
return "buzz"
return number
30 changes: 30 additions & 0 deletions python-control-flow/matching.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import csv
import json
from pathlib import Path


def read_file(file_path):
path = Path(file_path)
if not path.exists():
print(f"File not found: {file_path}")
return None

with path.open(mode="r", encoding="utf-8") as file:
match path.suffix.lower():
case ".json":
data = json.load(file)
print("Loaded JSON data.")
return data
case ".csv":
reader = csv.DictReader(file)
data = list(reader)
print("Loaded CSV data.")
return data
case _:
print(f"Unsupported file type: {path.suffix}")
return None


for file_path in ["test.json", "test.csv", "test.toml", "test.txt"]:
result = read_file(file_path)
print(result)
19 changes: 19 additions & 0 deletions python-control-flow/number_guesser.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from random import randint

LOW, HIGH = 1, 10

secret_number = randint(LOW, HIGH)
clue = ""

# Game loop
while True:
guess = input(f"Guess a number between {LOW} and {HIGH} {clue} ")
number = int(guess)
if number > secret_number:
clue = f"(less than {number})"
elif number < secret_number:
clue = f"(greater than {number})"
else:
break

print(f"You guessed it! The secret number is {number}")
12 changes: 12 additions & 0 deletions python-control-flow/odd_even.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
def odd_even(numbers):
for number in numbers:
if number % 2 == 0:
yield f"{number} is even"
else:
yield f"{number} is odd"


# Example usage
numbers = [2, 2, 3, 11, 4, 5, 7, 4]
for result in odd_even(numbers):
print(result)
16 changes: 16 additions & 0 deletions python-control-flow/speed.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import random


def check_speed_limit(limit=80):
speed = read_speedometer()
if speed > limit:
print("You are over the speed limit! Slow down.")


def read_speedometer():
speed = random.randint(30, 130)
print(f"Speedometer reading: {speed} km/h")
return speed


check_speed_limit()
3 changes: 3 additions & 0 deletions python-control-flow/test.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
name,job,country
John Doe,Software Engineer,USA
Jane Doe,Data Scientist,Canada
4 changes: 4 additions & 0 deletions python-control-flow/test.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
[
{"name": "John", "job": "Software Engineer", "country": "USA"},
{"name": "Jane", "job": "Data Scientist", "country": "Canada"}
]
7 changes: 7 additions & 0 deletions python-control-flow/test.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
name: John Doe
job: Software Engineer
country: USA

name: Jane Doe
job: Data Scientist
country: Canada
8 changes: 8 additions & 0 deletions python-control-flow/user_input.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
user_input = input("Enter an integer number: ")

try:
number = int(user_input)
except ValueError as e:
print(f"Error: {e}")
else:
print(f"Success: you entered {number}")