Skip to content

Commit

Permalink
Merge pull request #608 from realpython/input-output-update
Browse files Browse the repository at this point in the history
Add code examples for Basic I/O Update
  • Loading branch information
brendaweles authored Nov 15, 2024
2 parents 9e6a15e + 56ad978 commit a046f4e
Show file tree
Hide file tree
Showing 5 changed files with 44 additions and 0 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
```
20 changes: 20 additions & 0 deletions basic-input-output-in-python/adventure_game.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import random

health = 5
enemy_health = 3

while health > 0 and enemy_health > 0:
if input("Attack or Run? ").lower() == "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(f"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)

0 comments on commit a046f4e

Please sign in to comment.