Skip to content
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

Sample code for the article on for loops #620

Open
wants to merge 5 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-for-loop/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Python "for" Loops: The Pythonic Way

This folder provides the code examples for the Real Python tutorial [Python "for" Loops: The Pythonic Way](https://realpython.com/python-for-loop-update/).
19 changes: 19 additions & 0 deletions python-for-loop/async_range.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import asyncio


class AsyncRange:
def __init__(self, start, end):
self.data = range(start, end)

async def __aiter__(self):
for index in self.data:
await asyncio.sleep(0.5)
yield index


async def main():
async for index in AsyncRange(0, 5):
print(index)


asyncio.run(main())
14 changes: 14 additions & 0 deletions python-for-loop/break_continue.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
numbers = [1, 3, 5, 7, 9]
target = 5
for number in numbers:
print(f"Processing {number}...")
if number == target:
print(f"Target found {target}!")
break

numbers = [1, 2, 3, 4, 5, 6]
for number in numbers:
print(f"{number = }")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

flake8 compains and I was also wondering about it, I've generally only seen this used without whitespace:

Suggested change
print(f"{number = }")
print(f"{number=}")

pycodestyle, which implements the check, seems to be stubborn about keeping it this way: PyCQA/pycodestyle#1201

$ flake8 break_continue.py 
break_continue.py:11:20: E251 unexpected spaces around keyword / parameter equals
break_continue.py:11:22: E202 whitespace before '}'
break_continue.py:11:22: E251 unexpected spaces around keyword / parameter equals

But I know you're using space around the equals sign also in the f-string tutorial.

So IDK, I guess the linters don't fail on it?

If you decide to change it, you'd also have to change it in the written tutorial.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If I remember correctly, in one of my previous articles I used this feature without spaces and I guess it was Geir Arne who suggested adding the spaces for readability. However, I don't think this is a written rule.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, yeah I'm fine with leaving it considering it passes our linter checks. @gahjelle should we note this somewhere, that we'll ignore E251 and E202 for these cases?

if number % 2 != 0:
continue
print(f"{number} is even!")
14 changes: 14 additions & 0 deletions python-for-loop/built_in_types.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
numbers = [1, 2, 3, 4]
for number in numbers:
print(number)

person = ("Jane", 25, "Python Dev", "Canada")
for field in person:
print(field)

text = "abcde"
for character in text:
print(character)

for index in range(5):
print(index)
4 changes: 4 additions & 0 deletions python-for-loop/colors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
colors = ["red", "green", "blue", "yellow"]

for color in colors:
print(color)
7 changes: 7 additions & 0 deletions python-for-loop/cubes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
cubes = []
for number in range(10):
cubes.append(number**3)
print(cubes)

cubes = [number**3 for number in range(10)]
print(cubes)
29 changes: 29 additions & 0 deletions python-for-loop/dictionaries.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
students = {
"Alice": 89.5,
"Bob": 76.0,
"Charlie": 92.3,
"Diana": 84.7,
"Ethan": 88.9,
}
for student in students:
print(student)

for student in students:
print(student, "->", students[student])

for student in students.keys():
print(student)

teams = {
"Colorado": "Rockies",
"Chicago": "White Sox",
"Boston": "Red Sox",
"Minnesota": "Twins",
"Milwaukee": "Brewers",
"Seattle": "Mariners",
}
for team in teams.values():
print(team)

for city, team in teams.items():
print(city, "->", team)
10 changes: 10 additions & 0 deletions python-for-loop/else_clause.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
numbers = [1, 3, 5, 7, 9]
target = 42

for number in numbers:
print(f"Processing {number}...")
if number == target:
print(f"Target found {target}!")
break
else:
print(f"Target no found {target}")
14 changes: 14 additions & 0 deletions python-for-loop/exceptions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
files = ["file1.txt", "file2.txt", "file3.txt"]

for file in files:
with open(file, "r") as f:
print(f"Contents of {file}:")
print(f.read())

for file in files:
try:
with open(file, "r") as f:
print(f"Contents of {file}:")
print(f.read())
except FileNotFoundError:
print(f"Error: {file} not found. Skipping.")
8 changes: 8 additions & 0 deletions python-for-loop/indices.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
fruits = ["orange", "apple", "mango", "lemon"]

for index in range(len(fruits)):
fruit = fruits[index]
print(index, fruit)

for index, fruit in enumerate(fruits):
print(index, fruit)
10 changes: 10 additions & 0 deletions python-for-loop/matrix.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from itertools import chain

matrix = [
[9, 3, 8],
[4, 5, 2],
[6, 4, 3],
]

for value in chain(*matrix):
print(value**2)
7 changes: 7 additions & 0 deletions python-for-loop/menu.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
def display_menu(options):
print("Main Menu:")
for pos, option in enumerate(options, start=1):
print(f"{pos}. {option}")


display_menu(["Open", "Save", "Settings", "Quit"])
4 changes: 4 additions & 0 deletions python-for-loop/nested.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
for number in range(1, 11):
for product in range(number, number * 11, number):
print(f"{product:>4d}", end="")
print()
5 changes: 5 additions & 0 deletions python-for-loop/parallel_iteration.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
numbers = [1, 2, 3]
letters = ["a", "b", "c"]

for number, letter in zip(numbers, letters):
print(number, "->", letter)
3 changes: 3 additions & 0 deletions python-for-loop/repeat.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
for _ in range(3):
print("Knock, knock, knock")
print("Penny!")
4 changes: 4 additions & 0 deletions python-for-loop/reversing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
actions = ["Type text", "Select text", "Cut text", "Paste text"]

for action in reversed(actions):
print(f"Undo: {action}")
4 changes: 4 additions & 0 deletions python-for-loop/sets.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
tools = {"Django", "Flask", "pandas", "NumPy"}

for tool in tools:
print(tool)
17 changes: 17 additions & 0 deletions python-for-loop/sorting.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
students = {
"Alice": 89.5,
"Bob": 76.0,
"Charlie": 92.3,
"Diana": 84.7,
"Ethan": 88.9,
"Fiona": 95.6,
"George": 73.4,
"Hannah": 81.2,
}

sorted_students = sorted(
students.items(), key=lambda item: item[1], reverse=True
)

for name, grade in sorted_students:
print(f"{name}'s average grade: {grade:->{20-len(name)}.1f}")
4 changes: 4 additions & 0 deletions python-for-loop/unpacking.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
points = [(1, 4), (3, 6), (7, 3)]

for x, y in points:
print(f"{x = } and {y = }")
Loading