7 Basic Input Output In Python
8 Python의 기본 입출력
이 폴더에는 Real Python 튜토리얼 Python의 기본 입출력에 대한 코드 예제가 포함되어 있습니다.
파일 이름을 지정하여 모든 스크립트를 직접 실행할 수 있습니다.
$ python <filename>.py8.1 파일: adventure_game.py
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")8.2 파일: greeter.py
name = input("Please enter your name: ")
print("Hello", name, "and welcome!")8.3 파일: guess_the_number.py
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)8.4 파일: improved_input.py
import readline # noqa F401
while (user_input := input("> ")).lower() != "exit":
print("You entered:", user_input)