Number Guessing Game
Basically one of the classics, whether it’s a programmable calculator, 8-bit home computer, or as shown here with Python; you have to implement this on every platform at least once.
Perfect for first attempts with conditionals (if-statements).
flowchart TD A[Start] --> B[Generate random number] B --> C[User is informed about number of digits] C --> D[User input: Guess the number] D --> E{Input == Random number?} E -- Yes --> F[Correctly guessed! Display attempts] E -- No --> G{Input < Random number?} G -- Yes --> H[Hint: My number is larger] G -- No --> I[Hint: My number is smaller] H --> D I --> D F --> J[End]
from random import randint
eingabe = 0
versuche = 0
zahl = randint(1, 9999)
print(
f"\nLass uns Zahlenraten spielen, ich denke mir eine Zahl; meine Zahl hat {len(str(zahl))} Stellen."
)
while eingabe != zahl:
versuche += 1
while True:
try:
eingabe = int(input("\nRate meine Zahl: "))
break
except ValueError:
print("Bitte nur Zahlen eingeben.")
if eingabe == zahl:
print(f"\nDas ist richtig, du hast {versuche} Versuche gebraucht!")
elif eingabe < zahl:
print("\nMeine Zahl ist größer.")
elif eingabe > zahl:
print("\nMeine Zahl ist kleiner.")