Skip to content

Commit eb2a167

Browse files
committed
Sample code for the article on control flow
1 parent 20a870a commit eb2a167

File tree

12 files changed

+152
-0
lines changed

12 files changed

+152
-0
lines changed

python-control-flow/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# Control Flow Structures in Python
2+
3+
This folder provides the code examples for the Real Python tutorial [Control Flow Structures in Python](https://realpython.com/python-control-flow/).

python-control-flow/call_api.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import os
2+
import random
3+
4+
5+
def run_api_call(api_key):
6+
# Simulate an API call
7+
if random.choice([True, False]):
8+
print(f"Running API call with key: {api_key}")
9+
else:
10+
raise Exception("API call failed.")
11+
12+
13+
def main():
14+
user_key = input("Please enter your API key: ")
15+
os.environ["API_KEY"] = user_key
16+
print(f"Temporary API key set: {os.environ['API_KEY']}")
17+
18+
try:
19+
run_api_call(os.environ["API_KEY"])
20+
except Exception as e:
21+
print(f"Error: {e}")
22+
else:
23+
print("API call completed successfully.")
24+
finally:
25+
del os.environ["API_KEY"]
26+
print("API key cleaned up!")
27+
28+
29+
if __name__ == "__main__":
30+
main()
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
emails = [
2+
3+
4+
5+
6+
7+
8+
9+
]
10+
11+
# emails = [email.strip().lower() for email in emails]
12+
13+
emails = {email.strip().lower() for email in emails}

python-control-flow/continue.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
for i in range(5):
2+
print("Before continue")
3+
continue
4+
# print("After continue")
5+
6+
for i in range(5):
7+
print("Before break")
8+
break
9+
# print("After break")

python-control-flow/else_loop.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
numbers = [1, 3, 5, 9]
2+
3+
target = 7
4+
for number in numbers:
5+
if number == target:
6+
print("Found!")
7+
break
8+
else:
9+
print("Not found.")
10+
11+
target = 3
12+
for number in numbers:
13+
if number == target:
14+
print("Found!")
15+
break
16+
else:
17+
print("Not found.")

python-control-flow/matching.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import csv
2+
import json
3+
from pathlib import Path
4+
5+
6+
def read_file(file_path):
7+
path = Path(file_path)
8+
if not path.exists():
9+
print(f"File not found: {file_path}")
10+
return None
11+
12+
with path.open(mode="r", encoding="utf-8") as file:
13+
match path.suffix.lower():
14+
case ".json":
15+
data = json.load(file)
16+
print("Loaded JSON data.")
17+
return data
18+
case ".csv":
19+
reader = csv.DictReader(file)
20+
data = list(reader)
21+
print("Loaded CSV data.")
22+
return data
23+
case _:
24+
print(f"Unsupported file type: {path.suffix}")
25+
return None
26+
27+
28+
for file_path in ["test.json", "test.csv", "test.toml", "test.txt"]:
29+
result = read_file(file_path)
30+
print(result)

python-control-flow/odd_even.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
def odd_even(numbers):
2+
for number in numbers:
3+
if number % 2 == 0:
4+
yield f"{number} is even"
5+
else:
6+
yield f"{number} is odd"
7+
8+
9+
# Example usage
10+
numbers = [2, 2, 3, 11, 4, 5, 7, 4]
11+
for result in odd_even(numbers):
12+
print(result)

python-control-flow/speed.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import random
2+
3+
4+
def read_speedometer():
5+
speed = random.randint(30, 130)
6+
print(f"Speedometer reading: {speed} km/h")
7+
return speed
8+
9+
10+
def check_speed_limit(limit=80):
11+
speed = read_speedometer()
12+
if speed > limit:
13+
print("You are over the speed limit! Slow down.")
14+
15+
16+
check_speed_limit()

python-control-flow/test.csv

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
name,job,country
2+
John Doe,Software Engineer,USA
3+
Jane Doe,Data Scientist,Canada

python-control-flow/test.json

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
[
2+
{"name": "John", "job": "Software Engineer", "country": "USA"},
3+
{"name": "Jane", "job": "Data Scientist", "country": "Canada"}
4+
]

0 commit comments

Comments
 (0)