My program asks the user to input how many tries/attempts they would like for answering each question. When the user runs out of tries, my program prints "0 tries left." How can I prevent this so that my program only prints "You are out of tries"?
Here is the specific function of my code:
def test_student(max_attempts, prob_spec, prob_sol):
counter = 0
print("The problem is:", prob_spec)
while counter < max_attempts:
user_answer = int(input("\t Your answer:"))
if user_answer != int(prob_sol):
counter = counter + 1
print("Try again. You have", (max_attempts - counter), "tries left.")
elif user_answer == int(prob_sol):
print("Correct!")
return True
break
if counter == max_attempts:
print("You are out of tries. The answer was:", prob_sol)
return False
Change this:
print("Try again. You have", (max_attempts - counter), "tries left.")
to this:
if max_attempts - counter != 0:
print("Try again. You have", (max_attempts - counter), "tries left.")
else:
break
Redesigned your code a little:
def test_student(max_attempts, prob_spec, prob_sol):
counter = 0
print("The problem is:", prob_spec)
while True:
user_answer = int(input("\t Your answer:"))
if user_answer == int(prob_sol):
print("Correct!")
return True
counter += 1
if counter == max_attempts:
print("You are out of tries. The answer was:", prob_sol)
return False
print("Try again. You have", (max_attempts - counter), "tries left.")
No need for break after a return.
No need to check equality and then immediately inequality, it's superfluous.
Try exiting a while loop as soon as possible if you're correct, it leads to more readable code.
As you can see, instead of checking the counter as the while condition, I check it later on. This allows you to take care of the last attempt differently.
Keep in mind you can use the max_attempts as a counter by running max_attempts -= 1 and comparing the result to 0. I chose to go with your way as it's completely reasonable.
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'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.
I attempted to make a simple word guessing game, where the user has 3 attempts to guess a word. If the user guesses the word within 3 attempt, the program returns "Yay, you win!" If they do not guess within the 3 attempts, the program is supposed to return "Out of attempts! You lost!", however I am not getting any output when the user fails the game.
The program also tells the user how many guesses he has remaining after each incorrect guess, (except the last guess, where the output should be "Out of attempts! You lost!".
secret_word = "giraffe"
guess = ""
guesses_remaining = 3
out_of_guesses = False
while secret_word != guess:
if guesses_remaining != 0:
guess = input("Enter guess: ")
guesses_remaining -= 1
if guesses_remaining != 0:
if secret_word != guess:
print("You have " + str(guesses_remaining) + " guesses remaining!")
else:
out_of_guesses = True
if out_of_guesses == False:
print("Yay, you win!")
else:
print("Out of attempts! You lost!")
I can't figure out why I get no output when the user fails to guess within the three attempts.
Since you said that you're brand new to Python, I started out by changing your code as little as possible so you can see how you could fix what you've written to make it work.
Your problem can be fixed by adding and not out_of_guesses to your while statement condition. You could also have added a line with the keyword break after the line out_of_guesses = True. Using breakends whatever loop you are in right away.
secret_word = "giraffe"
guess = ""
guesses_remaining = 3
out_of_guesses = False
#Changing the condition of the while loop makes sure the loop doesn't continue
#after the player is out of guesses
while secret_word != guess and not out_of_guesses:
if guesses_remaining != 0:
guess = input("Enter guess: ")
guesses_remaining -= 1
if guesses_remaining != 0:
if secret_word != guess:
print("You have " + str(guesses_remaining) + " guesses remaining!")
else:
out_of_guesses = True
if out_of_guesses == False:
print("Yay, you win!")
else:
print("Out of attempts! You lost!")
Example output:
Enter guess: fox
You have 2 guesses remaining!
Enter guess: bear
You have 1 guesses remaining!
Enter guess: mouse
Out of attempts! You lost!
I would like to add that your code can be simplified considerably whilst maintaining its behavior:
secret_word = "giraffe"
guesses_remaining = 3
while guesses_remaining > 0:
guess = input("Enter guess: ")
guesses_remaining -= 1
if guess == secret_word:
print("Yay, you win!")
break
else:
print("Out of attempts! You lost!")
You need to break the loop after three unsuccessful attempts.
Try putting break in else after you turn out_of_guesses True.