Skip to content

Commit 4353417

Browse files
authored
Merge pull request #639 from realpython/python-while-loop
Sample code for the article on `while` loops
2 parents 62c140f + 24e559b commit 4353417

File tree

10 files changed

+148
-0
lines changed

10 files changed

+148
-0
lines changed

python-while-loop/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# Python while Loops: Repeating Tasks Conditionally
2+
3+
This folder provides the code examples for the Real Python tutorial [Python while Loops: Repeating Tasks Conditionally](https://realpython.com/python-while-loop/).

python-while-loop/api_calls.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import random
2+
import time
3+
4+
5+
def is_api_available():
6+
"""Simulate API availability."""
7+
time.sleep(1)
8+
return random.choice([True, False, False, False])
9+
10+
11+
def make_api_call(request):
12+
print(f"Making API call: {request}")
13+
time.sleep(0.5)
14+
15+
16+
requests = iter(["Request 1", "Request 2", "Request 3"])
17+
request = next(requests)
18+
19+
while True:
20+
if not is_api_available():
21+
print("API not available. Retrying in 1 sec...")
22+
continue
23+
make_api_call(request)
24+
try:
25+
request = next(requests)
26+
except StopIteration:
27+
break
28+
29+
print("All requests processed.")

python-while-loop/check_file.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import time
2+
from pathlib import Path
3+
4+
filename = Path("hello.txt")
5+
6+
print(f"Waiting for {filename.name} to be created...")
7+
8+
while not filename.exists():
9+
print("File not found. Retrying in 1 second...")
10+
time.sleep(1)
11+
12+
print(f"{filename} found! Proceeding with processing.")
13+
with open(filename, mode="r") as file:
14+
print("File contents:")
15+
print(file.read())

python-while-loop/connection.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import random
2+
import time
3+
4+
MAX_RETRIES = 5
5+
attempts = 0
6+
7+
while attempts < MAX_RETRIES:
8+
attempts += 1
9+
print(f"Attempt {attempts}: Connecting to the server...")
10+
# Simulating a connection scenario
11+
time.sleep(0.5)
12+
if random.choice([False, False, False, True]):
13+
print("Connection successful!")
14+
break
15+
16+
print("Connection failed. Retrying...")
17+
else:
18+
print("All attempts failed. Unable to connect.")

python-while-loop/infinite.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# number = 5
2+
# while number != 0:
3+
# print(number)
4+
# number -= 2
5+
6+
7+
number = 5
8+
while number > 0:
9+
print(number)
10+
number -= 2
11+
12+
13+
number = 5
14+
while number != 0:
15+
if number <= 0:
16+
break
17+
print(number)
18+
number -= 2

python-while-loop/logfile.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import time
2+
3+
with open("file.log", mode="r") as file:
4+
file.seek(0, 2)
5+
6+
while True:
7+
line = file.readline()
8+
if line:
9+
line_content = line.strip()
10+
if line_content == "END":
11+
print("File processing done.")
12+
break
13+
print(f"Processing line content: {line_content}")
14+
else:
15+
time.sleep(1)
16+
print("No new content. Retrying in 1 second...")

python-while-loop/password.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
MAX_ATTEMPTS = 3
2+
3+
correct_password = "secret123"
4+
attempts = 0
5+
6+
7+
while True:
8+
password = input("Password: ").strip()
9+
10+
attempts += 1
11+
if attempts >= MAX_ATTEMPTS:
12+
print("Too many failed attempts.")
13+
break
14+
15+
if password == correct_password:
16+
print("Login successful! Welcome!")
17+
break
18+
else:
19+
print(f"Incorrect password. {MAX_ATTEMPTS - attempts} attempts left.")

python-while-loop/remove.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
colors = ["red", "blue", "yellow", "green"]
2+
3+
while colors:
4+
color = colors.pop(-1)
5+
print(f"Processing color: {color}")

python-while-loop/temperature.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import random
2+
import time
3+
4+
5+
def read_temperature():
6+
time.sleep(1)
7+
return random.uniform(20.0, 30.0)
8+
9+
10+
while True:
11+
temperature = read_temperature()
12+
print(f"Temperature: {temperature:.2f}°C")
13+
14+
if temperature >= 25:
15+
print("Required temperature reached! Stopping monitoring.")
16+
break

python-while-loop/user_input.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
line = input("Type some text: ")
2+
3+
while line != "stop":
4+
print(line)
5+
line = input("Type some text: ")
6+
7+
8+
while (line := input("Type some text: ")) != "stop":
9+
print(line)

0 commit comments

Comments
 (0)