For some background I'm pretty much a beginner and attempting to learn Python currently. So I decided after a few days of lessons I'd look for some beginner projects to test my knowledge. A website suggested I do a 'Guess the Number' game and basically suggested I follow this guideline.
- Random function
- Variables
- Integers
- Input/Output
- While loops
- If/Else statements
In short I read the documentation on random and decided to give it a shot. Now for the actual question. Is this a good way of doing this or can I simplify it?
I've pretty much been working at this for longer than I would like to admit (approximately 90 minutes), because I'd get stumped and then rewrite what I was thinking.
# guess the number game
import random
print "Welcome to guess the number!"
print "You have 10 tries to guess the correct number!"
print "The range of numbers will be from 0-25"
# variables to store winning number, user guess and number of tries
number = random.randint(0, 25)
guess = raw_input("Please enter a number (0-25): ")
tries = 0
# check to see if the user guessed the right number
if int(guess) == number:
print "Congratulations you\'ve won!"
# noticed that you could input invalid numbers and it counted as a guess so this is how i solved that
while int(guess) > 25 or int(guess) < 0:
guess = raw_input("Please enter a VALID guess: ")
else:
# my attempt at making the game loop
while tries < 10 and int(guess) != number:
guess = raw_input("Please guess again: ")
tries = tries + 1
# i noticed if i guessed the right answer out of the loop it would just exit so i duplicated here to prevent it
if int(guess) == number:
print "Congratulations you\'ve won!"
# implemented the lose mechanic
elif tries == 10:
print "You've Lost!"
# same with the correct answer issue i had so i put it in the loop as well
elif int(guess) > 25 or int(guess) < 0:
while int(guess) > 25 or int(guess) < 0:
guess = raw_input("Please enter a VALID guess: ")
# this is here because I didn't want to take tries away for invalid guesses
tries = tries
So the game for me works as expected. You can win, lose, guess invalid numbers (I haven't tried letters but I won't get into that yet). Just not sure if this is the most efficient I can get. But if it's good enough for a beginner, I'll take it.
print
is a function and not a statement, andraw_input
is nowinput
). As Python 2 is now depreciated, I would definitely move up to it right now. \$\endgroup\$