I'm new to Python and just starting to make a guessing game.
I finally managed to figure out a way to make the game work by allowing the user to try again if they run out of 3 guesses with this code (hopefully this is ok for you people)
from random import randint
random_number = randint(1, 10)
guesses_left = 3
guess = None
while True:
print(f"You have {guesses_left} guseses left")
guess = input("Pick a number between 1 and 10\n")
guess = int(guess)
if guess > random_number:
print("Too high")
guesses_left -= 1
elif guess < random_number:
print("Too low")
guesses_left -= 1
else:
guesses_left = 3
print("Good Job! You got it!")
if input("Would you like to play again (y/n)\n") == "y":
random_number = randint(1, 10)
else:
print("Thanks for Playing!")
break
if guesses_left == 0:
guesses_left = 3
print("You ran out of guesss :(")
if input("Would you like another try?\n") != "y":
print("Thanks for playing!")
break
However before I got to that conclusion, I had the final if statement placed above the 2nd to last else statement (I probably didn't say that well but hopefully the code explains it) and the code didn't work in the end (It said I got the number right even if the number was wrong) Could someone help me explain why I need to put that block of code at the bottom instead of the final else statement?
from random import randint
random_number = randint(1, 10)
guesses_left = 3
guess = None
while True:
print(f"You have {guesses_left} guseses left")
guess = input("Pick a number between 1 and 10\n")
guess = int(guess)
if guess > random_number:
print("Too high")
guesses_left -= 1
elif guess < random_number:
print("Too low")
guesses_left -= 1
**if guesses_left == 0:
guesses_left = 3
print("You ran out of guesss :(")
if input("Would you like another try?\n") != "y":
print("Thanks for playing!")
break**
else:
guesses_left = 3
print("Good Job! You got it!")
if input("Would you like to play again (y/n)\n") == "y":
random_number = randint(1, 10)
else:
print("Thanks for Playing!")
break
In the second code snippet, you are checking whether guesses_left is equals to 0. After the first guess, it isn't, and so it goes to the 'else', where Good job, you got it! is printed.
if guesses_left == 0:
guesses_left = 3
print("You ran out of guesss :(")
if input("Would you like another try?\n") != "y":
print("Thanks for playing!")
break
else:
guesses_left = 3
print("Good Job! You got it!")
```
Hi The reason is when you inserted the if after your elif you had reinitated another condition. thus, the else follows the condition on the second if statement and not the first condition. see the below example
a = 3
b = 'a dsistraction'
if a ==3:
print('yes 3')
elif a ==1:
print('yes 1')
if b == 2:
print('reseting the condition')
else:
print('broken out of the first if')
#yes 3
#a followin
What you will realise is there are two different conditions. thus rather than use if, you are better off using an elif statement
The if at the same indent level after an elif starts a new set of branches; its evaluation is largely independent of the previous branches (the exception being any state change, such as the alteration of guesses_left in the sample). Consider what you have going into the block (in particular, the value of guesses_left:
if guesses_left == 0:
guesses_left = 3
print("You ran out of guesss :(")
if input("Would you like another try?\n") != "y":
print("Thanks for playing!")
break
else:
guesses_left = 3
print("Good Job! You got it!")
if input("Would you like to play again (y/n)\n") == "y":
random_number = randint(1, 10)
else:
print("Thanks for Playing!")
break
This connects to general design principles that can help avoid this sort of mistake: decompose a task into discrete subtasks and reduce coupling. In this case, "check the guess" and "check for game end" are separate subtasks, which should reflect in the code (as was done in the final, working program). You can separate the tasks out into distinct functions, classes, modules or frameworks (as appropriate), but even if you don't, you can write your code in such a way as it can later be refactored into separate pieces.
Related
SUPER new to programming so bear with me, please. I am taking my first ever programming class and for a project, I was given a list of requirements I need to fulfill, creating a simple number guessing game has been the only thing I've not had a lot of trouble with so I decided to give it a go.
(i need 1 class, function, dictionary or list, for loop, and while loop) What I, well at least have tried to make is a guessing game that gives a limit of 2 guesss for a # between 0 and 10, any help would be greatly appreciated. :)
import random
class Player:
player = ""
playerscore = 0
def gamestart(self):
self.number = random.randint(0,7)
self.guesss = 0
self.list = []
self.limit = 3
print()
print("Guess what number I'm thinking off")
print()
print("Might even give you a hit if you do well enough")
print()
while self.limit > 0:
self.player_guess = int(input("Well? What are you waiting for? Start guessing:"))
print()
if self.player_guess > 7 or self.player_guess < 0:
print("Wow that was a terrible guess, think harder or we might be here all week long")
print("also,", self.player_guess , "is not in the range...")
print("Becareful though, you only have", self.limit, "guesss left")
elif self.player_guess > self.number:
self.guesss += 1
self.limit-= 1
print("WRONG")
print(self.player, "You only have", self.limit, "guesss left")
self.list.append(self.player_guess)
elif self.player_guess < self.number:
self.guesss += 1
self.limit -= 1
print("oh oh... wrong again!")
print()
print(self.player, "You only have", self.limit, "guesss left.")
self.list.append(self.player_guess)
else:
self.limit -= 1
self.playerscore += 1
self.list.append(self.player_guess)
print()
print("wow, you actually got it right")
print()
print(self.player_guess, "IS THE CORRECT ANSWER!")
print()
print("you only had",self.limit,"left too...")
print("Lets see all the numbers you guessed")
print()
for i in self.list:
print(i)
self.list.clear()
I found the question confusing, however the following code should work as a number guessing game, hope I answered your question.
import random
game = "true"
guesses = 2
while game == "true":
comp_number = int(random.uniform(1,8))
print("I have randomly selected a number between 1 and 7 (inclusive), you have 2 attempts to guess the number.")
while guesses > 0:
if guesses == 2:
turn = "first"
else:
turn = "final"
guess = int(input("Please submit your "+turn+" guess:"))
while guess < 1 or guess > 7:
print("Invalid guess, remember my number is between 1 and 7 (inclusive)")
guess = int(input("Resubmit a valid guess:"))
if guess == comp_number:
print("Congratulations you guessed my number, you win!")
if str(input("Would you like to play again? Please enter Y or N.")) == "Y":
guesses = 2
game = "true"
else:
game = "false"
break
else:
print("Incorrect number, try again.")
guesses -= 1
print("You where unable to guess my number, I win!")
if str(input("Would you like to play again? Please enter Y or N.")) == "Y":
guesses = 2
game = "true"
else:
game = "false"
break
I'm making a guess the number game. My code is almost complete but I need to make it so that the program asks the player if they want to play again and then restarts. Could someone help me with how I should go about that? I tried making a new function ex. def game_play_again and then call the game_play() function but it's not reseting the attempts which leads to it not looping correctly.
This is my code right now
import random
MIN = 1
MAX = 100
attempts = 5
win = False
number = random.randint(MIN,MAX)
last_hint = f"{'EVEN' if number%2 == 0 else 'ODD'}"
#print game instructions
def game_start():
print(f"Im thinking of a number between {MIN} and {MAX}. Can you guess it within
{attempts} attempts? ")
input("Press enter to start the game ")
#process user input
def game_play():
global number, attempts, last_hint, win
while attempts > 0:
print()
print(f"You have {attempts} {'attempts' if attempts > 1 else 'attempt'} left.")
if attempts == 1:
print(f"This is your last chance. So i'll give you one more hint. Its's an {last_hint} number.")
while True:
try:
guess = int(input("Try a lucky number: "))
if guess in range(MIN, MAX+1):
break
else:
print(f"Please enter numbers between {MIN} and {MAX} only!")
except ValueError:
print("Plese enter numbers only!")
if guess == number:
win = True
break
if attempts == 1:
break
if guess > number:
if guess-number > 5:
print("Your guess is too high. Try something lower.")
else:
print("Come on you are very close. Just a bit lower.")
else:
if number-guess > 5:
print("Your guess is too low. Try something higher.")
else:
print("Come on you are very close. Just a bit higher.")
attempts -= 1
#print game results
def game_finish(win):
if win:
print("Congratulations you guessed it!")
else:
print(f"The number I was thinking of is {number}. Sorry you lost. Better luck next time!")
game_start()
game_play()
game_finish(win)
You can simply reset your variables to initial values and then call game_play()
def game_finish(win):
if win:
print("Congratulations you guessed it!")
else:
print(f"The number I was thinking of is {number}. Sorry you lost. Better luck next time!")
want_play_again = int(input("Want play again? [1-Yes / 2-No]"))
if want_play_again == 1:
game_play_again()
else:
print("Bye")
/
def game_play_again():
attempts = 0
win = False
game_play()
Within a while(True) loop, write a menu driven statement asking the user if they want to repeat. If they do, initialise values and call game methods. If they do not, break the loop.
pseudocode:
while(True):
choice = input('play again? y/n)
if choice=='y':
attempts, win = 5, False
number = random.randint(MIN,MAX)
last_hint = f"{'EVEN' if number%2 == 0 else 'ODD'}"
game_start()
game_play()
game_finish()
elif choice=='n':
break
else:
print('invalid input')
The above code should be in main, with all methods within its scope.
Better yet, in place of all the initializations, add an init() method declaring them and call them when necessary.
The indentation in the code you have submitted is faulty, so I'm not sure if a related error is involved.
import random
print("Welcome to the Number Guessing Game!")
number=random.randint(1,100)
print("I'm thinking of a number between 1 and 100.")
print(number)
def guess(lives):
guess_number=int(input("Make a guess: "))
while guess_number!=number and lives>0:
if guess_number>number:
print("Too High")
elif guess_number<number:
print("Too Low")
else:
print(f"You got it! The answer was {number}")
if lives==0:
print("You are out of moves.YOu loose")
else:
print(f"You have {lives-1} attempts remaining to guess the number")
print("Guess Again:")
guess(lives-1)
def set_lives():
level=input("Choose a difficulty.Type 'easy' or 'hard': ")
if level=="easy":
lives=10
else:
lives=5
return lives
guess(set_lives())
After the number of lives ==0 the while statement is false and it must come out of the loop.
but in this case the loop is executed even when its false.
I can see that we can solve this problem by make the solution simpler, we need just to change guess function, here you are the code and I'll explain it:
def guess(lives):
while lives > 0:
guess_number = int(input("Make a guess: "))
if guess_number == number:
print(f"You got it! The answer was {number}")
return
if guess_number > number:
print("Too High")
elif guess_number < number:
print("Too Low")
lives -= 1
print(f"You have {lives} attempts remaining to guess the number")
print("You are out of moves. You loose")
now what this code says is:
1- we need to loop at least the {number of alives} times
2- if what the user guess {guess_number} is == to the number, then print "You got it! The answer was... " then return statement will get out of the function, so we have just one success story and this is it/
3- the other 2 if conditions will still loop becouse the user didn't get the the requird guess.
4- if the loop has been finished and we still in the functions, that means that the user finished his {lives} with no correct answer, so it will print "You are out of moves. You loose"
I have a few days of Python knowledge. I've been going to courses like Codecademy and I wanted to dive into a project. I followed a YouTube video at the start of this project to get the hang of it.
My game will ask if it wants to be played, if "yes" it will keep playing. If "no" the program will stop. I don't know how to change this to make it keep playing.
The program also will not show that the number is greater than or less than after the while loop shows up. Originally I had that section of code after the while loop, but it made no difference.
I'm just a total beginner who wanted to learn Python better with an actual project, so I really am not sure which steps to take here:
import random
number = random.randint(1,10)
tries = 1
name = input("Hello, What is your name?")
print("Hello there,", name)
question = input("Time to guess, ready? [Y/N]")
if question == "n":
print("sorry, lets go!")
if question == "y":
print("Im thinking of a number between 1 and 10.")
guess = int(input("Have a guess"))
if guess < number:
print("That is too low!")
if guess == number:
print("Congrats! You win!!")
if guess > number:
print("That is too high!")
while guess != number:
tries += 1
guess = int(input("Try again: "))
.
Hello, What is your name?name
Hello there, name
Time to guess, ready? [Y/N]y
Im thinking of a number between 1 and 10.
Have a guess1
That is too low!
Try again: 10
Try again: 10
Try again: 10
Try again:
The message "too high" is never displayed.
The if statements can go inside the while loop.
And you can use the break statement to terminate the while loop.
You can find more details here: https://docs.python.org/2.0/ref/break.html
Use elif not consecutive if statements. Change your while loop to allow breaking out, so you can display the correct win message.
import random
number = random.randint(1,10)
tries = 1
name = input("Hello, What is your name?")
print("Hello there,", name)
question = input("Time to guess, ready? [Y/N]")
if question == "n":
print("sorry, lets go!")
if question == "y":
print("Im thinking of a number between 1 and 10.")
guess = int(input("Have a guess"))
while True:
if guess < number:
print("That is too low!")
elif guess == number:
print("Congrats! You win!!")
break
elif guess > number:
print("That is too high!")
tries += 1
guess = int(input("Try again: "))
I'm with #furas in that this really should be a pair of nested while loops with a structure something like:
import random
name = input("Hello, What is your name? ")
print("Hello there,", name)
answer = "y"
while answer.lower().startswith("y"):
number = random.randint(1, 10)
print("I'm thinking of a number between 1 and 10.")
guess = int(input("Have a guess: "))
while True:
if guess < number:
print("That is too low!")
elif guess > number:
print("That is too high!")
else:
print("Congrats! You win!")
break
guess = int(input("Try again: "))
answer = input("Play again? [Y/N]: ")
print("Goodbye!")
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
I wanted to create a guessing game to get more comfortable programming, The user has up to 100 guesses(yes more than enough). If the number is too high or too low it have them type in a new input, if its correct it will print correct.Now I simply want to have it setup to where I ask them would they like to play again. I think I have an idea of to set it up, by separating them into two functions?
I am aware that is not currently a function but should put this as a fucntion and then put my question as an if statement in its own function?
import random
randNum = random.randrange(1,21)
numguesses = 0
while numguesses < 100:
numguesses = numguesses + 1
userguess = int(input("What is your guess [1 through 20]?"))
if userguess < 1:
print("Too Low")
print("Please enter a valid guess [1-20]!")
elif userguess > 20:
print("Too High")
elif userguess == randNum:
print("Correct")
print("you used",numguesses,"number of guesses")
Here's a simple way to do as you asked.I made a function and when you get the thing correct it asks if you want to play again and if you enter "yes" then it resets the vars and runs the loop again. If you enter anything but "yes" then it breaks the loop which ends the program.
import random
def main():
randNum = random.randrange(1,21)
numguesses = 0
while numguesses < 100:
numguesses = numguesses + 1
userguess = int(input("What is your guess [1 through 20]?"))
if userguess < 1:
print("Too Low")
print("Please enter a valid guess [1-20]!")
elif userguess > 20:
print("Too High")
elif userguess == randNum:
print("Correct")
print("you used",numguesses,"number of guesses")
x = input("would you like to play again?")
if x == "yes":
main()
else:
break
main()
Here is another way to do
import random
randNum = random.randrange(1,21)
numguesses = 0
maxGuess = 100
print("Guessing number Game - max attempts: " + str(maxGuess))
while True:
numguesses +=1
userguess = int(input("What is your guess [1 through 20]? "))
if userguess < randNum:
print("Too Low")
elif userguess > randNum:
print("Too High")
else:
print("Correct. You used ",numguesses," number of guesses")
break
if maxGuess==numguesses:
print("Maximum attempts reached. Correct answer: " + str(randNum))
break
import random
randNum = random.randrange(1, 21)
guess = 0
response = ['too low', 'invalid guess', 'too hight', 'correct']
def respond(guess):
do_break = None # is assigned True if user gets correct answer
if guess < randNum:
print(response[0])
elif guess > randNum:
print(response[2])
elif guess < 1:
print(response[1])
elif guess == randNum:
print(response[3])
do_continue = input('do you want to continue? yes or no')
if do_continue == 'yes':
# if player wants to play again start loop again
Guess()
else:
# if player does'nt want to play end game
do_break = True # tells program to break the loop
# same as ''if do_break == True''
if do_break:
#returns instructions for loop to end
return True
def Guess(guess=guess):
# while loops only have accesse to variables of direct parent
# which is why i directly assigned the guess variable to the Fucntion
while guess < 100:
guess -= 1
user_guess = int(input('What is your guess [1 through 20]?'))
# here the respond function is called then checked for a return
# statement (note i don't know wheter this is good practice or not)
if respond(user_guess):
# gets instructions from respond function to end loop then ends it
break
Guess()
Yet another way with two while loops
answer = 'yes'
while answer == 'yes':
while numguesses < 100:
numguesses = numguesses + 1
userguess = int(input("What is your guess [1 through 20]?"))
if userguess < 1:
print("Too Low")
print("Please enter a valid guess [1-20]!")
elif userguess > 20:
print("Too High")
elif userguess == randNum:
print("Correct")
print("you used",numguesses,"number of guesses")
break #Stop while loop if user guest, hop to the first loop with answer var
answer = raw_input("Would you like to continue? yes or no\n>")