Skip to content

Commit d70d127

Browse files
authored
Merge pull request #609 from realpython/expressions-vs-statements
Materials for Python Expressions vs Statements
2 parents a046f4e + a68d9d7 commit d70d127

File tree

6 files changed

+175
-0
lines changed

6 files changed

+175
-0
lines changed
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()
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import argparse
2+
import itertools
3+
4+
MAX_BYTES = 1024
5+
6+
7+
def main(args):
8+
buffer = bytearray()
9+
with open(args.path, mode="rb") as file:
10+
while chunk := file.read(MAX_BYTES):
11+
buffer.extend(chunk)
12+
for row in itertools.batched(buffer, args.columns):
13+
print(" ".join(f"{byte:02x}" for byte in row))
14+
15+
16+
def parse_args():
17+
parser = argparse.ArgumentParser()
18+
parser.add_argument("path")
19+
parser.add_argument("-c", "--columns", type=int, default=16)
20+
return parser.parse_args()
21+
22+
23+
if __name__ == "__main__":
24+
main(parse_args())

0 commit comments

Comments
 (0)