Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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-while-loop/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Python while Loops: Repeating Tasks Conditionally

This folder provides the code examples for the Real Python tutorial [Python while Loops: Repeating Tasks Conditionally](https://realpython.com/python-while-loop/).
29 changes: 29 additions & 0 deletions python-while-loop/api_calls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import random
import time


def is_api_available():
"""Simulate API availability."""
time.sleep(1)
return random.choice([True, False, False, False])


def make_api_call(request):
print(f"Making API call: {request}")
time.sleep(0.5)


requests = iter(["Request 1", "Request 2", "Request 3"])
request = next(requests)

while True:
if not is_api_available():
print("API not available. Retrying in 1 sec...")
continue
make_api_call(request)
try:
request = next(requests)
except StopIteration:
break

print("All requests processed.")
15 changes: 15 additions & 0 deletions python-while-loop/check_file.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import time
from pathlib import Path

filename = Path("hello.txt")

print(f"Waiting for {filename.name} to be created...")

while not filename.exists():
print("File not found. Retrying in 1 second...")
time.sleep(1)

print(f"{filename} found! Proceeding with processing.")
with open(filename) as file:
print("File contents:")
print(file.read())
18 changes: 18 additions & 0 deletions python-while-loop/connection.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import random
import time

MAX_RETRIES = 5
attempts = 0

while attempts < MAX_RETRIES:
attempts += 1
print(f"Attempt {attempts}: Connecting to the server...")
# Simulating a connection scenario
time.sleep(0.5)
if random.choice([False, False, False, True]):
print("Connection successful!")
break

print("Connection failed. Retrying...")
else:
print("All attempts failed. Unable to connect.")
18 changes: 18 additions & 0 deletions python-while-loop/infinite.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# number = 5
# while number != 0:
# print(number)
# number -= 2


number = 5
while number > 0:
print(number)
number -= 2


number = 5
while number != 0:
if number <= 0:
break
print(number)
number -= 2
16 changes: 16 additions & 0 deletions python-while-loop/logfile.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import time

with open("file.log", mode="r") as file:
file.seek(0, 2)

while True:
line = file.readline()
if line:
line_content = line.strip()
if line_content == "END":
print("File processing done.")
break
print(f"Processing line content: {line_content}")
else:
time.sleep(1)
print("No new content. Retrying in 1 second...")
19 changes: 19 additions & 0 deletions python-while-loop/password.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
MAX_ATTEMPTS = 3

correct_password = "secret123"
attempts = 0


while True:
password = input("Password: ").strip()

attempts += 1
if attempts >= MAX_ATTEMPTS:
print("Too many failed attempts.")
break

if password == correct_password:
print("Login successful! Welcome!")
break
else:
print(f"Incorrect password. {MAX_ATTEMPTS - attempts} attempts left.")
5 changes: 5 additions & 0 deletions python-while-loop/remove.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
colors = ["red", "blue", "yellow", "green"]

while colors:
color = colors.pop(-1)
print(f"Processing color: {color}")
16 changes: 16 additions & 0 deletions python-while-loop/temperature.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import random
import time


def read_temperature():
time.sleep(1)
return random.uniform(20.0, 30.0)


while True:
temperature = read_temperature()
print(f"Temperature: {temperature:.2f}°C")

if temperature >= 25:
print("Required temperature reached! Stopping monitoring.")
break
9 changes: 9 additions & 0 deletions python-while-loop/user_input.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
line = input("Type some text: ")

while line != "stop":
print(line)
line = input("Type some text: ")


while (line := input("Type some text: ")) != "stop":
print(line)