Skip to content

Commit 4107fd0

Browse files
authored
Merge branch 'master' into python-set-comprehension
2 parents 27b8475 + c328778 commit 4107fd0

File tree

20 files changed

+363
-138
lines changed

20 files changed

+363
-138
lines changed
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# Basic Input and Output in Python
2+
3+
This folder contains the code examples for the Real Python tutorial [Basic Input and Output in Python](https://realpython.com/python-input-output/).
4+
5+
You can run all of the scripts directly by specifying their name:
6+
7+
```sh
8+
$ python <filename>.py
9+
```
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import random
2+
3+
health = 5
4+
enemy_health = 3
5+
6+
while health > 0 and enemy_health > 0:
7+
# Normalize input to handle extra spaces and case variations.
8+
action = input("Attack or Run? ").strip().lower()
9+
if action not in {"attack", "run"}:
10+
print("Invalid choice. Please type 'Attack' or 'Run'.")
11+
continue
12+
13+
if action == "attack":
14+
enemy_health -= 1
15+
print("You hit the enemy!")
16+
# Implement a 50% chance that the enemy strikes back.
17+
enemy_attacks = random.choice([True, False])
18+
if enemy_attacks:
19+
health -= 2
20+
print("The enemy strikes back!")
21+
else:
22+
print("You ran away!")
23+
break
24+
print(f"Your health: {health}, Enemy health: {enemy_health}")
25+
26+
print("Victory!" if enemy_health <= 0 else "Game Over")
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
name = input("Please enter your name: ")
2+
print("Hello", name, "and welcome!")
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import random
2+
3+
number = random.randint(1, 10)
4+
guess = int(input("Guess a number between 1 and 10: "))
5+
6+
if guess == number:
7+
print("You got it!")
8+
else:
9+
print("Sorry, the number was", number)
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
import readline # noqa F401
2+
3+
while (user_input := input("> ")).lower() != "exit":
4+
print("You entered:", user_input)
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
# Expression vs Statement in Python: What's the Difference?
2+
3+
This folder contains sample code from the Real Python tutorial [Expression vs Statement in Python: What's the Difference?](https://realpython.com/python-expression-vs-statement/)
4+
5+
## Code Inspector
6+
7+
Identify whether a piece of Python code is an expression or a statement:
8+
9+
```shell
10+
$ python code_inspector.py
11+
Type a Python code snippet or leave empty to exit.
12+
>>> yield
13+
statement
14+
>>> (yield)
15+
expression
16+
>>> 2 +
17+
invalid
18+
```
19+
20+
## GUI App
21+
22+
Register a lambda expression as a callback, which delegates to a function with statements:
23+
24+
```shell
25+
$ python gui_app.py
26+
```
27+
28+
## Echo Program
29+
30+
Compile with a C compiler and pipe stdin to the echo program:
31+
32+
```shell
33+
$ gcc echo.c -o echo.x
34+
$ echo "Hello, World!" | ./echo.x
35+
Hello, World!
36+
```
37+
38+
## HEX Reader
39+
40+
Read a binary file and display its bytes in hexadecimal format:
41+
42+
```shell
43+
$ python hex_reader.py /path/to/HelloJava.class --columns 8
44+
ca fe ba be 00 00 00 41
45+
00 0f 0a 00 02 00 03 07
46+
00 04 0c 00 05 00 06 01
47+
(...)
48+
```
49+
50+
## Generators
51+
52+
Generate a random signal and use a low-pass filter to make it smooth:
53+
54+
```shell
55+
$ python generators.py
56+
-0.96: -0.96
57+
-0.81: -0.89
58+
-0.52: -0.67
59+
0.22: -0.15
60+
0.51: 0.37
61+
0.40: 0.46
62+
-0.08: 0.16
63+
-0.24: -0.16
64+
0.80: 0.28
65+
0.47: 0.64
66+
```
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import ast
2+
3+
4+
def main():
5+
print("Type a Python code snippet or leave empty to exit.")
6+
while code := input(">>> "):
7+
print(describe(code))
8+
9+
10+
def describe(code):
11+
if valid(code, mode="eval"):
12+
return "expression"
13+
elif valid(code, mode="exec"):
14+
return "statement"
15+
else:
16+
return "invalid"
17+
18+
19+
def valid(code, mode):
20+
try:
21+
ast.parse(code, mode=mode)
22+
return True
23+
except SyntaxError:
24+
return False
25+
26+
27+
if __name__ == "__main__":
28+
try:
29+
main()
30+
except EOFError:
31+
pass

expressions-vs-statements/echo.c

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
#include <stdio.h>
2+
3+
int main() {
4+
int x;
5+
while (x = fgetc(stdin)) {
6+
if (x == EOF)
7+
break;
8+
putchar(x);
9+
}
10+
return 0;
11+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import random
2+
3+
4+
def main():
5+
lf = lowpass_filter()
6+
lf.send(None)
7+
for value in generate_noise(10):
8+
print(f"{value:>5.2f}: {lf.send(value):>5.2f}")
9+
10+
11+
def generate_noise(size):
12+
for _ in range(size):
13+
yield 2 * random.random() - 1
14+
15+
16+
def lowpass_filter():
17+
a = yield
18+
b = yield a
19+
while True:
20+
a, b = b, (yield (a + b) / 2)
21+
22+
23+
if __name__ == "__main__":
24+
main()
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import tkinter as tk
2+
3+
4+
def main():
5+
window = tk.Tk()
6+
button = tk.Button(window, text="Click", command=lambda: on_click(42))
7+
button.pack(padx=10, pady=10)
8+
window.mainloop()
9+
10+
11+
def on_click(age):
12+
if age > 18:
13+
print("You're an adult.")
14+
else:
15+
print("You're a minor.")
16+
17+
18+
if __name__ == "__main__":
19+
main()

0 commit comments

Comments
 (0)