From eb2a167267771bc9cf61e48c73d20e36ddca58cb Mon Sep 17 00:00:00 2001 From: Leodanis Pozo Ramos Date: Mon, 5 May 2025 16:50:48 +0200 Subject: [PATCH 1/2] Sample code for the article on control flow --- python-control-flow/README.md | 3 +++ python-control-flow/call_api.py | 30 +++++++++++++++++++++++++++ python-control-flow/comprehensions.py | 13 ++++++++++++ python-control-flow/continue.py | 9 ++++++++ python-control-flow/else_loop.py | 17 +++++++++++++++ python-control-flow/matching.py | 30 +++++++++++++++++++++++++++ python-control-flow/odd_even.py | 12 +++++++++++ python-control-flow/speed.py | 16 ++++++++++++++ python-control-flow/test.csv | 3 +++ python-control-flow/test.json | 4 ++++ python-control-flow/test.txt | 7 +++++++ python-control-flow/user_input.py | 8 +++++++ 12 files changed, 152 insertions(+) create mode 100644 python-control-flow/README.md create mode 100644 python-control-flow/call_api.py create mode 100644 python-control-flow/comprehensions.py create mode 100644 python-control-flow/continue.py create mode 100644 python-control-flow/else_loop.py create mode 100644 python-control-flow/matching.py create mode 100644 python-control-flow/odd_even.py create mode 100644 python-control-flow/speed.py create mode 100644 python-control-flow/test.csv create mode 100644 python-control-flow/test.json create mode 100644 python-control-flow/test.txt create mode 100644 python-control-flow/user_input.py diff --git a/python-control-flow/README.md b/python-control-flow/README.md new file mode 100644 index 0000000000..3208feb7be --- /dev/null +++ b/python-control-flow/README.md @@ -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/). diff --git a/python-control-flow/call_api.py b/python-control-flow/call_api.py new file mode 100644 index 0000000000..efb3af235c --- /dev/null +++ b/python-control-flow/call_api.py @@ -0,0 +1,30 @@ +import os +import random + + +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.") + + +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!") + + +if __name__ == "__main__": + main() diff --git a/python-control-flow/comprehensions.py b/python-control-flow/comprehensions.py new file mode 100644 index 0000000000..c41c7177f6 --- /dev/null +++ b/python-control-flow/comprehensions.py @@ -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} diff --git a/python-control-flow/continue.py b/python-control-flow/continue.py new file mode 100644 index 0000000000..9925127d77 --- /dev/null +++ b/python-control-flow/continue.py @@ -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") diff --git a/python-control-flow/else_loop.py b/python-control-flow/else_loop.py new file mode 100644 index 0000000000..0fa4eb804a --- /dev/null +++ b/python-control-flow/else_loop.py @@ -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.") diff --git a/python-control-flow/matching.py b/python-control-flow/matching.py new file mode 100644 index 0000000000..bb3b0fe9ed --- /dev/null +++ b/python-control-flow/matching.py @@ -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) diff --git a/python-control-flow/odd_even.py b/python-control-flow/odd_even.py new file mode 100644 index 0000000000..3cfa0c30bd --- /dev/null +++ b/python-control-flow/odd_even.py @@ -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) diff --git a/python-control-flow/speed.py b/python-control-flow/speed.py new file mode 100644 index 0000000000..5273acb9c8 --- /dev/null +++ b/python-control-flow/speed.py @@ -0,0 +1,16 @@ +import random + + +def read_speedometer(): + speed = random.randint(30, 130) + print(f"Speedometer reading: {speed} km/h") + return speed + + +def check_speed_limit(limit=80): + speed = read_speedometer() + if speed > limit: + print("You are over the speed limit! Slow down.") + + +check_speed_limit() diff --git a/python-control-flow/test.csv b/python-control-flow/test.csv new file mode 100644 index 0000000000..3b624ff070 --- /dev/null +++ b/python-control-flow/test.csv @@ -0,0 +1,3 @@ +name,job,country +John Doe,Software Engineer,USA +Jane Doe,Data Scientist,Canada \ No newline at end of file diff --git a/python-control-flow/test.json b/python-control-flow/test.json new file mode 100644 index 0000000000..702e4f9e84 --- /dev/null +++ b/python-control-flow/test.json @@ -0,0 +1,4 @@ +[ + {"name": "John", "job": "Software Engineer", "country": "USA"}, + {"name": "Jane", "job": "Data Scientist", "country": "Canada"} +] \ No newline at end of file diff --git a/python-control-flow/test.txt b/python-control-flow/test.txt new file mode 100644 index 0000000000..9b72bd34c7 --- /dev/null +++ b/python-control-flow/test.txt @@ -0,0 +1,7 @@ +name: John Doe +job: Software Engineer +country: USA + +name: Jane Doe +job: Data Scientist +country: Canada \ No newline at end of file diff --git a/python-control-flow/user_input.py b/python-control-flow/user_input.py new file mode 100644 index 0000000000..e6262f31ac --- /dev/null +++ b/python-control-flow/user_input.py @@ -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}") From e51157a4a6852a898a50dc06b4a4673e65749412 Mon Sep 17 00:00:00 2001 From: Leodanis Pozo Ramos Date: Fri, 9 May 2025 19:28:22 +0200 Subject: [PATCH 2/2] TR update, first round --- python-control-flow/call_api.py | 16 +++++++------- python-control-flow/fizz_buzz.py | 30 +++++++++++++++++++++++++++ python-control-flow/number_guesser.py | 19 +++++++++++++++++ python-control-flow/speed.py | 12 +++++------ 4 files changed, 63 insertions(+), 14 deletions(-) create mode 100644 python-control-flow/fizz_buzz.py create mode 100644 python-control-flow/number_guesser.py diff --git a/python-control-flow/call_api.py b/python-control-flow/call_api.py index efb3af235c..bc12d901f5 100644 --- a/python-control-flow/call_api.py +++ b/python-control-flow/call_api.py @@ -2,14 +2,6 @@ import random -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.") - - def main(): user_key = input("Please enter your API key: ") os.environ["API_KEY"] = user_key @@ -26,5 +18,13 @@ def main(): 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() diff --git a/python-control-flow/fizz_buzz.py b/python-control-flow/fizz_buzz.py new file mode 100644 index 0000000000..041f6a6ab3 --- /dev/null +++ b/python-control-flow/fizz_buzz.py @@ -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 diff --git a/python-control-flow/number_guesser.py b/python-control-flow/number_guesser.py new file mode 100644 index 0000000000..38494e2bde --- /dev/null +++ b/python-control-flow/number_guesser.py @@ -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}") diff --git a/python-control-flow/speed.py b/python-control-flow/speed.py index 5273acb9c8..dd013b62b9 100644 --- a/python-control-flow/speed.py +++ b/python-control-flow/speed.py @@ -1,16 +1,16 @@ import random -def read_speedometer(): - speed = random.randint(30, 130) - print(f"Speedometer reading: {speed} km/h") - return speed - - 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()