Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add code examples for Basic I/O Update #608

Merged
merged 4 commits into from
Nov 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
Loading