While Loop Stopping - python

The Code is working, but after 2 trys of the code it will just stop, this is in the section of playagain() when im asking the yes or no question it will display the error but will stop after the trys am i doing it wrong?
import random
import time
import getpass
import sys
def game1():
number = (input("Please Enter Your 3 Digit Code e.g.(0 0 1): "))
if number.isnumeric(): #if its a number
counter = 0
x = True
L = 1
H = 100
while x == True:
time.sleep(0.5)
randomguess = random.randint(L,H)
print("%03d"%randomguess)
if randomguess > int(number):
print("The Passcode is lower")
H = randomguess
elif randomguess < int(number):
print("The Passcode is higher")
L = randomguess
else:
print("The Passcode is Equal")
x = False
counter = counter + 1
if randomguess == int(number):
print("Well Done the Prisoner has Escaped, he did it in",counter,"trys")
return playagain()
if counter > 9:
print("The Prisoner get it wrong",counter,"times he is locked in, Well Done Jailer")
return playagain()
else:
print("This is Invalid, Please Provide a 3 Digit Code")
#This is the Section just for Reference
def playagain():
playagain = input("Do you wish to play again (yes/no): ")
if playagain == "yes":
print("You chose to play again")
return game1()
elif playagain == "no":
print("So you let the prisoner escape, thats it your fired")
time.sleep(2)
print("Thanks for Playing")
time.sleep(2)
#quit("Thanks for Playing") #quit game at this point
sys.exit()
else:
print("Please choose a valid option")
return

Here's a cleaned-up version:
from random import randint
from time import sleep
DELAY = 0.5
def get_int(prompt, lo=None, hi=None):
while True:
try:
val = int(input(prompt))
if (lo is None or lo <= val) and (hi is None or val <= hi):
return val
except ValueError:
# not an int, try again
pass
def get_yn(prompt):
while True:
yn = input(prompt).strip().lower()
if yn in {"y", "yes"}:
return True
elif yn in {"n", "no"}:
return False
def game(tries=100):
code = get_int("Please enter a 3-digit number (ie 091): ", 0, 999)
lo, hi = 0, 999
for attempt in range(1, tries+1):
sleep(DELAY)
guess = randint(lo, hi)
if guess < code:
print("Guessed {:03d} (too low!)".format(guess))
lo = guess + 1
elif guess > code:
print("Guessed {:03d} (too high!)".format(guess))
hi = guess - 1
else:
print("{:03d} was correct! The prisoner escaped on attempt {}.".format(guess, attempt))
return True
print("The prisoner failed to escape!")
return False
def main():
while True:
game()
if get_yn("Do you want to play again? "):
print("You chose to play again.")
else:
print("Alright, bye!")
break
if __name__=="__main__":
main()

def game1():
number = (input("Please Enter Your 3 Digit Code e.g.(0 0 1): "))
if number.isnumeric(): #if its a number
counter = 0
x = True
L = 1
H = 100
while x == True:
time.sleep(0.5)
randomguess = random.randint(L,H)
print("%03d"%randomguess)
if randomguess > int(number):
print("The Passcode is lower")
H = randomguess
elif randomguess < int(number):
print("The Passcode is higher")
L = randomguess
else:
print("The Passcode is Equal")
x = False
counter = counter + 1
if randomguess == int(number):
print("Well Done the Prisoner has Escaped, he did it in",counter,"trys")
x = False
if counter > 9:
print("The Prisoner get it wrong",counter,"times he is locked in, Well Done Jailer")
x = False
else:
print("This is Invalid, Please Provide a 3 Digit Code")
playagain()
#This is the Section just for Reference
def playagain():
playagain = ""
while (playagain != "yes" or playagain != "no"):
playagain = input("Do you wish to play again (yes/no): ")
if playagain == "yes":
print("You chose to play again")
return game1()
elif playagain == "no":
print("So you let the prisoner escape, thats it your fired")
time.sleep(2)
print("Thanks for Playing")
time.sleep(2)
#quit("Thanks for Playing") #quit game at this point
sys.exit()
else:
print("Please choose a valid option")
game1()
See https://repl.it/B7uf/3 for a working example.
Games typically run in a game loop which you have implemented using while x = True. The gameloops exits when the game is over and then user is asked to restart it. The bugs you were experiencing were due to the gameloop prematurely exiting before the user could be asked to restart.
The code below above that problem. There are other things that could be updated to improve the flow, but will leave that to you.
Use try/catch blocks instead of boolean checks
Break the game loop out into a separate method

Related

Function and keyword argument

Why is my code not working? I am following UDEMY's 100 days of code and it is essentially the same as the instructor but I wanted to have keyword named arguments. First of all it's not printing the correct turn_left after each turn and it's not stopping the game.
from random import randint
EASY_LEVEL_TURNS = 10
HARD_LEVEL_TURNS = 5
def check_answer(user_guess, correct_answer, tracking_turns):
"""
Checks answer with guess.
"""
if user_guess > correct_answer:
print("Too high")
return tracking_turns - 1
elif user_guess < correct_answer:
print("Too low")
return tracking_turns - 1
elif user_guess == correct_answer:
print(f"Right the answer is {correct_answer}")
def set_difficulty(game_level):
"""
Sets game difficulty
"""
if game_level == "easy":
return EASY_LEVEL_TURNS
elif game_level == "hard":
return HARD_LEVEL_TURNS
def game():
"""
Setting up the game
"""
guess = 0
answer = randint(1, 100)
print("Welcome to the number guessing game!")
print("I am thinking of a number between 1 to 100")
level = input("How difficult would you like the game to be? Easy or Hard ").lower()
turn_left = set_difficulty(game_level=level)
while guess != answer:
print(f"You have {turn_left} attempts to guess the answer.")
guess = int(input("What is your guess? "))
answer_checked = check_answer(user_guess=guess, correct_answer=answer,
tracking_turns=turn_left)
if turn_left == 0:
print("You have ran out of terms")
return
game()
You can modify your game function like this, mainly by updating the turn_left value and setting the end-of-function condition
def game():
"""
Setting up the game
"""
guess = 0
answer = randint(1, 100)
print("Welcome to the number guessing game!")
print("I am thinking of a number between 1 to 100")
level = input("How difficult would you like the game to be? Easy or Hard ").lower()
turn_left = set_difficulty(game_level=level)
while guess != answer:
print(f"You have {turn_left} attempts to guess the answer.")
guess = int(input("What is your guess? "))
turn_left = check_answer(user_guess=guess, correct_answer=answer,
tracking_turns=turn_left)
if turn_left == 0:
print("You have ran out of terms")
return
elif not turn_left:
return

Have couple mistakes in python with while and elif statements

from random import randint
play = "yes"
while play == "yes":
choice = int(input("Would you like to play yourself(1) or let machine(2) play? press '1' or '2': "))
if choice == 1:
print("You chose to play yourself")
num = randint(1,9999)
counter = 0
while True:
num_guess = int(input("Guess the number: "))
if num_guess == 0:
print("Player has left the game")
break
else:
if num_guess > num:
print("Your guess is too high")
elif num_guess < num:
print("Your guess is too low")
elif num_guess == num:
print("Yay,you found it")
print("It took you " + str(counter) + " tries to guess the number")
break
counter += 1
elif choice == 2:
print("You chose to let the machine play")
your_num = int(input("Enter your number: "))
lowest = 1
highest = 9999
counter = 0
machine_guess = randint(1,9999)
if your_num == 0:
you_sure = input("Are you sure you want to leave the game? yes or no: ")
if you_sure == "yes":
print("Player left the game")
break
else:
while True:
print("My guess is ",machine_guess)
is_it_right = input("Is it too small(<) or too big(>) or machine found(=) the number?: ")
if is_it_right == ">":
if machine_guess > your_num:
highest = machine_guess
counter += 1
else:
print("!!!Don't cheat!!!")
your_number = input("What was your number?: ")
print(str(machine_guess) +" < " + str(your_number) + ",so you should have written '<' instead of what you wrote.Continue ")
elif is_it_right == "<":
if machine_guess < your_num:
lowest = machine_guess + 1
counter += 1
else:
print("!!!Don't Cheat!!!")
your_number = input("What was your number?: ")
print(str(machine_guess) +" > " + str(your_number) + ",so you should have written '>' instead of what you wrote.Continue ")
elif is_it_right == "=":
if machine_guess == your_num:
if your_num == machine_guess:
counter += 1
print("Yayy,I found it")
print("It took me " + str(counter) + " tries to guess the number")
else:
print("You cheated and changed the number during the game.Please play fairly")
your_number = input("What was your number?: ")
print(str(machine_guess) +" = " + str(your_number) + ",so you should have written '=' instead of what you wrote ")
break
elif is_it_right == 0:
you_sure = input("Are you sure you want to leave the game? yes or no: ")
if you_sure == "yes":
print("Player left the game")
break
machine_guess = (lowest+highest)//2
elif choice == 0:
you_sure = input("Are you sure you want to leave the game? yes or no: ")
if you_sure == "yes":
print("Player has left the game")
break
request = input("Do you want to play again? Answer with 'yes' or 'no': ")
if request == "no":
print("You quitted the game")
break
elif request == 0:
you_sure = input("Are you sure you want to leave the game? yes or no: ")
if you_sure == "yes":
print("Player left the game")
break
This is my code for game "guess my number",here the complicated ones is me trying to make the program prevent user from cheating (It is a university task,due in 3 hours)
So choice 1 is when user decides to play game "guess my number" and 2nd choice when computer plays the game.The problem that I have is :
I can't make the code make the user input the number in range of(1,9999) and THEN continue the process
As you see I have a lot of "if ... == 0" --> .In task it is said that whenever(any of inputs) user types 0 the game has to stop.The others work well but the one in choice 2 the first if is not working
If somebody has solution for this,please help.I would be grateful
Whenever you want to ask a question repeatedly until the correct input is given, use a while loop
print("You chose to let the machine play")
your_num = -1
while your_num < 0 or your_num > 9999:
your_num = int(input("Enter your number [0..9999]: "))
1- To force the user to input a number in the range of (1,9999), you must have an a condition like:
while True:
try:
num_guess= int(input("Enter your number in range 1-9999: "))
except ValueError:
print("That's not a number!")
else:
if 1 <= num_guess <= 9999:
break
else:
print("Out of range. Try again")
Edit: I didn't understand which input you wanted to keep in the range of 1-9999. I gave answer with num_guess but you can use it with your_num, too.
2- Add play = "no" line to the condition when the user inputs 0:
if your_num == 0:
you_sure = input("Are you sure you want to leave the game? yes or no: ")
if you_sure == "yes":
print("Player left the game")
play = "no"
break

Asking user whether he/she wants to play again but typing yes just repeats this question again rather starting again

It is a number guessing game
Explanation
At first it asks the user to enter a number between 1 to 50
Then if the number is correct then you win else you have to try again (The winning number is random offcourse)You also have limited guesses
The problem is mentioned below the code
Here is my code:)
import random
winning_num = 23
guesses = 1
guesses_left = 9
game_over = False
end_game = False
number_enter = False
while not end_game:
while not number_enter:
try:
ask = int(input("ENTER A NUMBER BETWEEN 1 AND 50: "))
print(f"TOTAL GUESSES = {guesses_left}")
break
except ValueError:
print("INVALID INPUT!!")
continue
while not game_over:
if ask==winning_num:
print(f"YOU WON BY GUESSING THE NUMBER IN {guesses} TIME(S)!!")
print("DO YOU WANT TO PLAY AGAIN?")
while True:
ask1 = input("ENTER 'YES' OR 'NO' ONLY: ")
ask1 = ask1.lower()
if ask1=='yes':
print("YOU CHOSE TO PLAY AGAIN")
game_over = False
break
elif ask1=="no":
print("THANK YOU FOR PLAYING THIS GAME")
game_over = True
end_game = True
break
else:
print("PLEASE WRITE 'YES' OR 'NO' ONLY ")
continue
elif ask>winning_num:
print("TOO HIGH!!")
guesses+=1
guesses_left-=1
while True:
try:
ask = int(input("TRY AGAIN: "))
print(f"GUESSES LEFT = {guesses_left}")
break
except ValueError:
print("INVALID INPUT!!")
continue
if guesses_left==1:
print("ONLY ONE GUESS LEFT!!")
continue
elif guesses_left==0:
print("YOU LOSE!!")
break
elif ask<winning_num:
print("TOO LOW!!")
guesses+=1
guesses_left-=1
while True:
try:
ask = int(input("TRY AGAIN: "))
print(f"GUESSES LEFT = {guesses_left}")
break
except ValueError:
print("INVALID INPUT!!")
continue
if guesses_left==1:
print("ONLY ONE GUESS LEFT!!")
continue
elif guesses_left==0:
print("YOU LOSE!!")
break
The problem is when the game ends
It asks whether we want to play again
But if we type "Yes" it again asks the same "Do you want to play again"
However typing "No" works fine and the program ends
you have to set game_over = False in case ask1 = yes so that it can come out of the parent while loop and proceed. Also, you'll have to reset number of guesses etc so that it starts as a new game.
import random
winning_num = 23
guesses = 1
guesses_left = 9
game_over = False
end_game = False
number_enter = False
while not end_game:
while not number_enter:
try:
ask = int(input("ENTER A NUMBER BETWEEN 1 AND 50: "))
print(f"TOTAL GUESSES = {guesses_left}")
break
except ValueError:
print("INVALID INPUT!!")
continue
while not game_over:
if ask==winning_num:
print(f"YOU WON BY GUESSING THE NUMBER IN {guesses} TIME(S)!!")
print("DO YOU WANT TO PLAY AGAIN?")
while True:
ask1 = input("ENTER 'YES' OR 'NO' ONLY: ")
ask1 = ask1.lower()
if ask1=='yes':
print("YOU CHOSE TO PLAY AGAIN")
game_over = True
break
elif ask1=="no":
print("THANK YOU FOR PLAYING THIS GAME")
game_over = True
end_game = True
break
else:
print("PLEASE WRITE 'YES' OR 'NO' ONLY ")
continue
elif ask>winning_num:
print("TOO HIGH!!")
guesses+=1
guesses_left-=1
while True:
try:
ask = int(input("TRY AGAIN: "))
print(f"GUESSES LEFT = {guesses_left}")
break
except ValueError:
print("INVALID INPUT!!")
continue
if guesses_left==1:
print("ONLY ONE GUESS LEFT!!")
continue
elif guesses_left==0:
print("YOU LOSE!!")
break
elif ask<winning_num:
print("TOO LOW!!")
guesses+=1
guesses_left-=1
while True:
try:
ask = int(input("TRY AGAIN: "))
print(f"GUESSES LEFT = {guesses_left}")
break
except ValueError:
print("INVALID INPUT!!")
continue
if guesses_left==1:
print("ONLY ONE GUESS LEFT!!")
continue
elif guesses_left==0:
print("YOU LOSE!!")
break
You toggle game_over incorrectly, it should be set to True, not to False if the answer to replay is yes.
while not end_game: # End game must be false to replay
while not number_enter:
#... ask number
while not game_over: # But Game_over should be True to stop asking to replay
#... Check number good
#... Ask to replay
while True:
ask1 = input("ENTER 'YES' OR 'NO' ONLY: ")
ask1 = ask1.lower()
if ask1=='yes':
print("YOU CHOSE TO PLAY AGAIN")
game_over = True # <<<< Thats the problematic part, it must be True
# in your code it is False, So it result in
# an "infinite" loop, if yes.
break

Restart my Python script

So I've created this number guessing game. And it works fine up until the play_again function is needed. I have looked around trying to figure out how I can restart the program. I have tested this in my PyCharm IDE and it just exits with exit code 0. What is the best way to actually restart the program so it generates a new number in my rand variable?
import os
from random import random
import sys
class Game:
"""
rand is declared by grabbing a number between 0 and 1, multiplying it by 100, and rounding to the nearest integer
guessed is declared as false in order to keep the while loop running until the number is guessed
"""
rand = round(random() * 100, 0)
guessed = False
print("Guess the number [0 - 100]")
# This function handles the number guessing and number formatting
def run_game(self):
# Assigns the 'answer' variable by grabbing user input from console
answer = input()
# Checks if the input from the console is a number, and if not, asks the user to enter a valid number
if answer.isdigit():
n = int(answer)
# Checks the input given against the random number generated
while not self.guessed:
if n > int(self.rand):
print("Number is less than " + str(n))
self.run_game()
elif n < int(self.rand):
print("Number is greater than " + str(n))
self.run_game()
else:
print("You have guessed the correct number!")
self.guessed = True
self.play_again()
else:
print("Please enter a number")
self.run_game()
return
def play_again(self):
reply = input("Play again? (y/n)")
if reply.lower() == "y":
python = sys.executable
os.execl(python, python, *sys.argv)
elif reply.lower() == "n":
print("Thanks for playing!")
else:
self.play_again()
if __name__ == "__main__":
game = Game()
game.run_game()
Solution
There are several errors in your code. The most common being is that you are using recursion as a looping construct. Don't do this. It's a great way to introduce bugs, not to mention if your "loop" runs to many times, you'll hit the recursion limit. Just use a while loop:
def run_game(self):
while True:
answer = input()
if answer.isdigit():
n = int(answer)
if n > int(self.rand):
print("Number is less than " + str(n))
elif n < int(self.rand):
print("Number is greater than " + str(n))
else:
print("You have guessed the correct number!")
reply = self.play_again()
if reply is False:
break
else:
print("Please enter a number")
Note a modified player to return a boolean indicating whether the user wants to play again. As I said above, you made the same mistake in player. Don't use a recursion as a loop, use an explicit while loop:
def play_again(self):
while True:
reply = input("Play again? (y/n)")
if reply.lower() == "y":
return True
elif reply.lower() == "n":
return False
else:
print("Enter 'y' or 'n'")
Improvements
On an unrelated side note, I see no reason to use a class here. There's no global state you need to keep track of or any data you're trying to encapsulate. This can be implemented much cleaner using just functions:
def run_game():
rand = randint(1, 100)
while True:
answer = input()
if answer.isdigit():
n = int(answer)
if n > rand:
print("Number is less than " + str(n))
elif n < rand:
print("Number is greater than " + str(n))
else:
print("You have guessed the correct number!")
if not play_again():
break
else:
print("Please enter a number")
def play_again():
while True:
reply = input("Play again? (y/n)")
if reply.lower() == "y":
return True
elif reply.lower() == "n":
return False
else:
print("Enter 'y' or 'n'")
if __name__ == "__main__":
print("Guess the number [0 - 100]")
run_game()
Here are some other improvements I made:
I used ranint() instead of randomm(). Since you have a specific range, just use randint().
I removed the calls to int() as those are no longer needed.
That's a pretty bad way to restart the game, you should avoid running exec when possible.
One other way to do it would be to return False or True based on user input, and keep running the game while the function returns True:
import os
from random import random
import sys
class Game:
"""
rand is declared by grabbing a number between 0 and 1, multiplying it by 100, and rounding to the nearest integer
guessed is declared as false in order to keep the while loop running until the number is guessed
"""
rand = round(random() * 100, 0)
guessed = False
print("Guess the number [0 - 100]")
# This function handles the number guessing and number formatting
def run_game(self):
# Assigns the 'answer' variable by grabbing user input from console
answer = input()
# Checks if the input from the console is a number, and if not, asks the user to enter a valid number
if answer.isdigit():
n = int(answer)
# Checks the input given against the random number generated
while not self.guessed:
if n > int(self.rand):
print("Number is less than " + str(n))
self.run_game()
elif n < int(self.rand):
print("Number is greater than " + str(n))
self.run_game()
else:
print("You have guessed the correct number!")
self.guessed = True
return self.play_again() # Here we run play_again and return its result
else:
print("Please enter a number")
self.run_game()
return
def play_again(self):
reply = input("Play again? (y/n)")
if reply.lower() == "y":
return False # Game isn't finished
elif reply.lower() == "n":
print("Thanks for playing!")
return False # Game is finished
else:
return self.play_again()
if __name__ == "__main__":
game = Game()
game_is_finished = False
while not game_is_finished:
game_is_finished = game.run_game()

How to go about repeating or ending a function by a simple yes or no answer? [duplicate]

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>")

Categories

Resources