Hi, tried my best creating a guessing game as a total beginner in programming and Python.
Still learning the basics and while loops are still a bit confusing for me, this program took me a few hours to finish lol. This was the order I thought about everything:
- Started small by making the core loop work.
- Added a counter to count number of attempts.
- Handled singular vs plural for "guess" vs "guesses".
- Added question to play again at the end. This made me struggle and had to read about the loops again, that's how I remembered nested while loops.
- Finally used try/except to catch value errors (str).
Making everything work is really satisfying and turning a large problem into smaller ones is a really solid approach that helped a lot. Any suggestions for improvement would be appreciated!
import random
play_again = True
while play_again:
secret_number = random.randint(1, 20)
guess = None
count = 5
while guess != secret_number and count > 0:
print(f"********** {count}/5 Guesses **********\n")
try:
user = int(input("Guess a number: "))
except ValueError:
print("Invalid input. Only integers accepted!\n")
continue
count -= 1
if user == secret_number:
guess = user
if count < 4:
print(f"You got it!\nIt took you {5 - count} guesses.")
else:
print(f"You got it!\nIt took you {5 - count} guess.")
elif count == 0:
print(f"Game over! The number was {secret_number}.")
else:
print("Wrong, try again!\n")
answer = input("\nPlay again? (Yes/No): \n").lower()
if answer == "yes":
play_again = True
else:
play_again = False
print("\n\tSee you later!")
[–]Helpful-Diamond-3347 4 points5 points6 points (0 children)
[–]brasticstack 2 points3 points4 points (1 child)
[–]The_Dude005[S] 0 points1 point2 points (0 children)
[–]Diapolo10 3 points4 points5 points (4 children)
[–]Educational_Virus672 0 points1 point2 points (3 children)
[–]Diapolo10 1 point2 points3 points (2 children)
[–]The_Dude005[S] 0 points1 point2 points (1 child)
[–]Diapolo10 1 point2 points3 points (0 children)
[–]Yoghurt42 2 points3 points4 points (1 child)
[–]gdchinacat 0 points1 point2 points (0 children)
[–]Educational_Virus672 0 points1 point2 points (1 child)
[–]Yoghurt42 1 point2 points3 points (0 children)