Skip to content
Merged
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-print/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Your Guide to the Python print() Function

This folder contains sample code for the Real Python tutorial [Your Guide to the Python print() Function](https://realpython.com/python-print/).
5 changes: 5 additions & 0 deletions python-print/ansi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
def esc(*codes):
return f"\033[{';'.join(str(code) for code in codes)}m"


print(esc(31, 1, 4) + "really" + esc(0) + " important")
14 changes: 14 additions & 0 deletions python-print/calculator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import readline # noqa

print('Type "help", "exit", "add a [b [c ...]]"')
while True:
command, *arguments = input("~ ").split(" ")
if len(command) > 0:
if command.lower() == "exit":
break
elif command.lower() == "help":
print("This is help.")
elif command.lower() == "add":
print(sum(map(int, arguments)))
else:
print("Unknown command")
9 changes: 9 additions & 0 deletions python-print/countdown.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import time

num_seconds = 3
for countdown in reversed(range(num_seconds + 1)):
if countdown > 0:
print(countdown, end="...", flush=True)
time.sleep(1)
else:
print("Go!")
12 changes: 12 additions & 0 deletions python-print/custom_class.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def __str__(self):
class_name = type(self).__name__
return f"{class_name}(name={self.name!r}, age={self.age!r})"


jdoe = Person("John Doe", 42)
print(jdoe)
39 changes: 39 additions & 0 deletions python-print/morse_code.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# flake8: noqa

from time import sleep

speed = 0.1


def signal(duration, symbol):
sleep(duration)
print(symbol, end="", flush=True)


dot = lambda: signal(speed, "·\a")
dash = lambda: signal(3 * speed, "−\a")
symbol_space = lambda: signal(speed, "")
letter_space = lambda: signal(3 * speed, "")
word_space = lambda: signal(7 * speed, " ")

while True:
dot()
symbol_space()
dot()
symbol_space()
dot()
letter_space()

dash()
symbol_space()
dash()
symbol_space()
dash()
letter_space()

dot()
symbol_space()
dot()
symbol_space()
dot()
word_space()
21 changes: 21 additions & 0 deletions python-print/progress.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from time import sleep


def progress(percent=0, width=30):
left = width * percent // 100
right = width - left
print(
"\r[",
"#" * left,
" " * right,
"]",
f" {percent:.0f}%",
sep="",
end="",
flush=True,
)


for i in range(101):
progress(i)
sleep(0.1)
39 changes: 39 additions & 0 deletions python-print/snake.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import curses
import time


def main(screen):
curses.curs_set(0) # Hide the cursor
screen.nodelay(True) # Don't block I/O calls

directions = {
curses.KEY_UP: (-1, 0),
curses.KEY_DOWN: (1, 0),
curses.KEY_LEFT: (0, -1),
curses.KEY_RIGHT: (0, 1),
}

direction = directions[curses.KEY_RIGHT]
snake = [(0, i) for i in reversed(range(20))]

while True:
screen.erase()

# Draw the snake
screen.addstr(*snake[0], "@")
for segment in snake[1:]:
screen.addstr(*segment, "*")

# Move the snake
snake.pop()
snake.insert(0, tuple(map(sum, zip(snake[0], direction))))

# Change direction on arrow keystroke
direction = directions.get(screen.getch(), direction)

screen.refresh()
time.sleep(0.1)


if __name__ == "__main__":
curses.wrapper(main)
6 changes: 6 additions & 0 deletions python-print/spinning_wheel.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from itertools import cycle
from time import sleep

for frame in cycle(r"-\|/-\|/"):
print("\r", frame, sep="", end="", flush=True)
sleep(0.2)
18 changes: 18 additions & 0 deletions python-print/test_print.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from unittest import TestCase
from unittest.mock import patch


class TestPrint(TestCase):
@patch("builtins.print")
def test_print(self, mock_print):
print("Not a real print()")
mock_print.assert_called_with("Not a real print()")

@patch("builtins.print")
def test_greet(self, mock_print):
greet("John")
mock_print.assert_called_with("Hello, John!")


def greet(name):
print(f"Hello, {name}!")
8 changes: 8 additions & 0 deletions python-print/thread_safe_print.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import threading

lock = threading.Lock()


def thread_safe_print(*args, **kwargs):
with lock:
print(*args, **kwargs)
25 changes: 25 additions & 0 deletions python-print/threads_simulation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import sys
from random import random
from threading import Thread, current_thread
from time import sleep
from unittest.mock import patch

write = sys.stdout.write


def slow_write(text):
sleep(random())
write(text)


def task():
thread_name = current_thread().name
for letter in "ABC":
# print(f"[{thread_name} {letter}]")
print(f"[{thread_name} {letter}]\n", end="")


with patch("sys.stdout") as mock_stdout:
mock_stdout.write = slow_write
for i in range(1, 4):
Thread(target=task, name=f"Thread-{i}").start()