Skip to content

Commit

Permalink
Merge branch 'master' into python-set-comprehension
Browse files Browse the repository at this point in the history
  • Loading branch information
brendaweles authored Nov 21, 2024
2 parents 27b8475 + c328778 commit 4107fd0
Show file tree
Hide file tree
Showing 20 changed files with 363 additions and 138 deletions.
9 changes: 9 additions & 0 deletions basic-input-output-in-python/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Basic Input and Output in Python

This folder contains the code examples for the Real Python tutorial [Basic Input and Output in Python](https://realpython.com/python-input-output/).

You can run all of the scripts directly by specifying their name:

```sh
$ python <filename>.py
```
26 changes: 26 additions & 0 deletions basic-input-output-in-python/adventure_game.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import random

health = 5
enemy_health = 3

while health > 0 and enemy_health > 0:
# Normalize input to handle extra spaces and case variations.
action = input("Attack or Run? ").strip().lower()
if action not in {"attack", "run"}:
print("Invalid choice. Please type 'Attack' or 'Run'.")
continue

if action == "attack":
enemy_health -= 1
print("You hit the enemy!")
# Implement a 50% chance that the enemy strikes back.
enemy_attacks = random.choice([True, False])
if enemy_attacks:
health -= 2
print("The enemy strikes back!")
else:
print("You ran away!")
break
print(f"Your health: {health}, Enemy health: {enemy_health}")

print("Victory!" if enemy_health <= 0 else "Game Over")
2 changes: 2 additions & 0 deletions basic-input-output-in-python/greeter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
name = input("Please enter your name: ")
print("Hello", name, "and welcome!")
9 changes: 9 additions & 0 deletions basic-input-output-in-python/guess_the_number.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import random

number = random.randint(1, 10)
guess = int(input("Guess a number between 1 and 10: "))

if guess == number:
print("You got it!")
else:
print("Sorry, the number was", number)
4 changes: 4 additions & 0 deletions basic-input-output-in-python/improved_input.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import readline # noqa F401

while (user_input := input("> ")).lower() != "exit":
print("You entered:", user_input)
66 changes: 66 additions & 0 deletions expressions-vs-statements/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# Expression vs Statement in Python: What's the Difference?

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/)

## Code Inspector

Identify whether a piece of Python code is an expression or a statement:

```shell
$ python code_inspector.py
Type a Python code snippet or leave empty to exit.
>>> yield
statement
>>> (yield)
expression
>>> 2 +
invalid
```

## GUI App

Register a lambda expression as a callback, which delegates to a function with statements:

```shell
$ python gui_app.py
```

## Echo Program

Compile with a C compiler and pipe stdin to the echo program:

```shell
$ gcc echo.c -o echo.x
$ echo "Hello, World!" | ./echo.x
Hello, World!
```

## HEX Reader

Read a binary file and display its bytes in hexadecimal format:

```shell
$ python hex_reader.py /path/to/HelloJava.class --columns 8
ca fe ba be 00 00 00 41
00 0f 0a 00 02 00 03 07
00 04 0c 00 05 00 06 01
(...)
```

## Generators

Generate a random signal and use a low-pass filter to make it smooth:

```shell
$ python generators.py
-0.96: -0.96
-0.81: -0.89
-0.52: -0.67
0.22: -0.15
0.51: 0.37
0.40: 0.46
-0.08: 0.16
-0.24: -0.16
0.80: 0.28
0.47: 0.64
```
31 changes: 31 additions & 0 deletions expressions-vs-statements/code_inspector.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import ast


def main():
print("Type a Python code snippet or leave empty to exit.")
while code := input(">>> "):
print(describe(code))


def describe(code):
if valid(code, mode="eval"):
return "expression"
elif valid(code, mode="exec"):
return "statement"
else:
return "invalid"


def valid(code, mode):
try:
ast.parse(code, mode=mode)
return True
except SyntaxError:
return False


if __name__ == "__main__":
try:
main()
except EOFError:
pass
11 changes: 11 additions & 0 deletions expressions-vs-statements/echo.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#include <stdio.h>

int main() {
int x;
while (x = fgetc(stdin)) {
if (x == EOF)
break;
putchar(x);
}
return 0;
}
24 changes: 24 additions & 0 deletions expressions-vs-statements/generators.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import random


def main():
lf = lowpass_filter()
lf.send(None)
for value in generate_noise(10):
print(f"{value:>5.2f}: {lf.send(value):>5.2f}")


def generate_noise(size):
for _ in range(size):
yield 2 * random.random() - 1


def lowpass_filter():
a = yield
b = yield a
while True:
a, b = b, (yield (a + b) / 2)


if __name__ == "__main__":
main()
19 changes: 19 additions & 0 deletions expressions-vs-statements/gui_app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import tkinter as tk


def main():
window = tk.Tk()
button = tk.Button(window, text="Click", command=lambda: on_click(42))
button.pack(padx=10, pady=10)
window.mainloop()


def on_click(age):
if age > 18:
print("You're an adult.")
else:
print("You're a minor.")


if __name__ == "__main__":
main()
24 changes: 24 additions & 0 deletions expressions-vs-statements/hex_reader.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import argparse
import itertools

MAX_BYTES = 1024


def main(args):
buffer = bytearray()
with open(args.path, mode="rb") as file:
while chunk := file.read(MAX_BYTES):
buffer.extend(chunk)
for row in itertools.batched(buffer, args.columns):
print(" ".join(f"{byte:02x}" for byte in row))


def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("path")
parser.add_argument("-c", "--columns", type=int, default=16)
return parser.parse_args()


if __name__ == "__main__":
main(parse_args())
7 changes: 7 additions & 0 deletions numpy-examples/full_portfolio.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Company,Sector,Mon,Tue,Wed,Thu,Fri
Company_A,technology,100.5,101.2,102,101.8,112.5
Company_B,finance,200.1,199.8,200.5,201.0,200.8
Company_C,healthcare,50.3,50.5,51.0,50.8,51.2
Company_D,technology,110.5,101.2,102,111.8,97.5
Company_E,finance,200.1,200.8,200.5,211.0,200.8
Company_F,healthcare,55.3,50.5,53.0,50.8,52.2
4 changes: 2 additions & 2 deletions numpy-examples/issued_checks.csv
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
Check_ID,Payee,Amount,Date_Issued
1341,K.Starmer,150.00,2024-03-29
1341,K Starmer,150.00,2024-03-29
1342,R Sunak,175.00,2024-03-29
1343,L Truss,30.00,2024-03-29
1344,B Johnson,45.00,2024-03-22
Expand All @@ -8,4 +8,4 @@ Check_ID,Payee,Amount,Date_Issued
1347,G Brown,100.00,2024-03-15
1348,T Blair,250.00,2024-03-15
1349,J Major,500.00,2024-03-15
1350,M Thatcher,220.00,2024-03-15
1350,M Thatcher,220.00,2024-03-15
4 changes: 2 additions & 2 deletions numpy-examples/passports.csv
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ passport_no,passenger_no,nationality
493456399,3,American
375456228,4,American
457345975,5,Austrian
345957363,6,Norewegian
345957363,6,Norwegian
567546577,7,French
453667456,8,German
456785778,9,Danish
Expand All @@ -19,4 +19,4 @@ passport_no,passenger_no,nationality
654672278,18,Spanish
683637288,19,Norwegian
768357788,20,British
768357788,21,American
768357788,21,American
Loading

0 comments on commit 4107fd0

Please sign in to comment.