Skip to content

Commit 5acbc24

Browse files
committed
Add code examples for Basic I/O Update
1 parent ff6d3a0 commit 5acbc24

File tree

5 files changed

+47
-0
lines changed

5 files changed

+47
-0
lines changed
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
# Basic Input and Output in Python
2+
3+
This folder contains the code examples from the Real Python tutorial on [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+
```
10+
11+
If you're on a Windows sytem, then you'll need to install `pyreadline3` before you can see the benefits of importing `readline`, like done in `improved_input.py`.
12+
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import random
2+
3+
health = 5
4+
enemy_health = 3
5+
6+
while health > 0 and enemy_health > 0:
7+
if input("Attack or Run? ").lower() == "attack":
8+
enemy_health -= 1
9+
print("You hit the enemy!")
10+
# Implement a 50% chance that the enemy strikes back.
11+
enemy_attacks = random.choice([True, False])
12+
if enemy_attacks:
13+
health -= 2
14+
print("The enemy strikes back!")
15+
else:
16+
print("You ran away!")
17+
break
18+
print(f"Your health: {health}, Enemy health: {enemy_health}")
19+
20+
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(f"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)

0 commit comments

Comments
 (0)