while loop could not break - python

there is NameError: name 'user' is not defined
why while loop is not ending please help to find the problem
this program is for dice roll in pyhton
I want to roll the dice with no exception but there are exception accured
rand_num=random.randint(1, 6)
game_is_on=True
while True:
try:
user=int(input("What's your choice : "))
continue
except:
print("Please Enter 1-6")
if user == rand_num:
print("\t congrats ! \n You guessed it right 🎊")
elif user != rand_num:
print("Sorry! your guess is incorrect🥺")
replay=input("Do you want to play again (Yes/No)")
if replay =='yes'.lower():
game_is_on=True
else:
print("Thanks for playing this game")
game_is_on=False```
hlep to find the problem please

For your loop to exit:
Your while loop will forever be true, but you switched a variable game_is_on that was meant to regulated the loop. Instead of the forever loop , game_is_on should be next to while,
You need to remove continue statement as that line will just go to the next iteration as long as the condition is true,
When asked about replaying, the lower part should be on the variable, instead of lowering the string itself.
Below is the code you need:
rand_num=random.randint(1, 6)
game_is_on=True
# while True:
while game_is_on:
try:
user=int(input("What's your choice : "))
# continue
except:
print("Please Enter 1-6")
if user == rand_num:
print("\t congrats ! \n You guessed it right 🎊")
elif user != rand_num:
print("Sorry! your guess is incorrect🥺")
replay=input("Do you want to play again (Yes/No)")
if replay.lower() =='yes':
game_is_on=True
else:
print("Thanks for playing this game")
game_is_on=False
Happy coding!

import random
rand_num=random.randint(1, 6)
game_is_on=True
while game_is_on:
try:
user=int(input("What's your choice : "))
except:
print("Please Enter 1-6")
if user == rand_num:
print("\t congrats ! \n You guessed it right 🎊")
elif user != rand_num:
print("Sorry! your guess is incorrect🥺")
replay=input("Do you want to play again (Yes/No)")
if replay =='yes'.lower():
game_is_on=True
else:
print("Thanks for playing this game")
game_is_on=False
Note:
In while loop you have to write 'game_is_on' as for that variable it is telling whether true or false instead you have written True therefore your loop will never end as nothing is breaking the loop
corrected code is pasted above, hope this might help you.

You can use operator break to end while loop. lower() should be used with variable.
if replay.lower() != 'yes':
print("Thanks for playing this game")
break

Related

Guess the number, play again

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.

Is there anyway to use 'return' outside a function block to go back to my variable from 'else'?

I've been facing this problem for a bit now. I know that the 'return' command can't work outside a function, but is there an alternative to this or is there a need to define a new function?:
print("Are you", userage(), "years old?")
userinput = input()
if userinput == "yes":
print("Ok, lets get on with the program")
elif userinput =="no":
print("Oh, let's try that again then")
userage()
else:
print("please answer yes or no")
return userinput
Btw, sorry for all the mistakes I make. I'm still a beginner.
You need to use a while loop here:
while (True):
userinput = input("Are you xxx years old?\n")
if userinput == "yes":
print("Ok, lets get on with the program")
break
elif userinput == "no":
print("Oh, let's try that again then")
else:
print("please answer yes or no")
The loop will ever only break when someone types in yes.

Why wont this program stop after I press 'n'?

Why wont this stop when 'n' is entered?
I've tried using break on the bottom else but I get errors doing that. That's a common problem I have with break. I have no idea why I'm thrown off with break.
import random
def game():
secret_num = random.randint(1, 10)
guesses = []
while len(guesses) < 5:
try:
guess = int(input("Guess a number between 1 and 10: "))
except ValueError:
print("{} isn't a number".format(guess))
else:
if guess == secret_num:
print("You got it! The number was {}.".format(secret_num))
break
elif guess < secret_num:
print("My number is higher than {}".format(guess))
else:
print("My number is lower than {}".format(guess))
guesses.append(guess)
else:
print("You didn't get it! My number was {}".format(secret_num))
play_again = input("Do you want to play again? Y/n ")
if play_again.lower() != 'Y':
game()
else:
print("Bye!")
game()
You convert play_again to a lower-case letter but compare it to an upper-case letter.
You could simply change it to:
if play_again.lower() != 'n': # 'y' was wrong, right?
game()
else:
print("Bye!")
return # works also without the explicit return but it makes the intention clearer.

How do I ask the user if they want to play again and repeat the while loop?

Running on Python, this is an example of my code:
import random
comp = random.choice([1,2,3])
while True:
user = input("Please enter 1, 2, or 3: ")
if user == comp
print("Tie game!")
elif (user == "1") and (comp == "2")
print("You lose!")
break
else:
print("Your choice is not valid.")
So this part works. However, how do I exit out of this loop because after entering a correct input it keeps asking "Please input 1,2,3".
I also want to ask if the player wants to play again:
Psuedocode:
play_again = input("If you'd like to play again, please type 'yes'")
if play_again == "yes"
start loop again
else:
exit program
Is this related to a nested loop somehow?
Points for your code:
Code you have pasted don't have ':' after if,elif and else.
Whatever you want can be achived using Control Flow Statements like continue and break. Please check here for more detail.
You need to remove break from "YOU LOSE" since you want to ask user whether he wants to play.
Code you have written will never hit "Tie Game" since you are comparing string with integer. User input which is saved in variable will be string and comp which is output of random will be integer. You have convert user input to integer as int(user).
Checking user input is valid or not can be simply check using in operator.
Code:
import random
while True:
comp = random.choice([1,2,3])
user = raw_input("Please enter 1, 2, or 3: ")
if int(user) in [1,2,3]:
if int(user) == comp:
print("Tie game!")
else:
print("You lose!")
else:
print("Your choice is not valid.")
play_again = raw_input("If you'd like to play again, please type 'yes'")
if play_again == "yes":
continue
else:
break

How to stop the beginning of my function's loop from repeating

I have created a code in which the user will input their choice which will continue in a loop if the variable 'contin' equals "yes". When the user enters the choice "no" or any other input it will print their overall answers or the error message and end the loop. Instead it then repeats the beginning of the function (in this case it's whether the user wanted to continue or not). Is there a way for me to prevent this from happening?
This is the code:
def userinput():
while True:
contin = input("Do you wish to continue the game? If so enter 'yes'. If not enter 'no'.")
if contin == 'yes':
print(symbol_dictionary["#"]+symbol_dictionary["+"]+symbol_dictionary["/"]+symbol_dictionary["0"]+symbol_dictionary["8"]+symbol_dictionary["4"]+symbol_dictionary["&"]+symbol_dictionary['"']
guess = input("What symbol do you wish to change? ")
symbol_dictionary[guess] = input("Input what letter you wish to change the symbol to.(Make sure the letter is in capitals.) ")
print(symbol_dictionary["#"]+symbol_dictionary["+"]+symbol_dictionary["/"]+symbol_dictionary["0"]+symbol_dictionary["8"]+symbol_dictionary["4"]+symbol_dictionary["&"]+symbol_dictionary['"'])
elif contin == ('no'):
print ("These were your overall answers:")
print(symbol_dictionary["#"]+symbol_dictionary["+"]+symbol_dictionary["/"]+symbol_dictionary["0"]+symbol_dictionary["8"]+symbol_dictionary["4"]+symbol_dictionary["&"]+symbol_dictionary['"'])
if symbol_dictionary == {"#": "A","+":"C", "/":"Q", "0":"U", "8":"I",
"4":"R", "&":"E",'"':'D', "3":"L", "*":"M",
"%":"N", "2":"S", ":":"T", "1":"O",",":"J",
"$":"K", "!":"H", "7":"Z", "-":"Y", ".":"G",
"'":"W",")":"F", "6":"B", "5":"X", "9":"V"}:
print("Well done! You have completed the game!")
else:
print("Please enter a valid input.")
All you need to do is exit the function; add a return in your no branch:
elif contin == ('no'):
print ("These were your overall answers:")
print(symbol_dictionary["#"]+symbol_dictionary["+"]+symbol_dictionary["/"]+symbol_dictionary["0"]+symbol_dictionary["8"]+symbol_dictionary["4"]+symbol_dictionary["&"]+symbol_dictionary['"'])
if symbol_dictionary == {"#": "A","+":"C", "/":"Q", "0":"U", "8":"I",
"4":"R", "&":"E",'"':'D', "3":"L", "*":"M",
"%":"N", "2":"S", ":":"T", "1":"O",",":"J",
"$":"K", "!":"H", "7":"Z", "-":"Y", ".":"G",
"'":"W",")":"F", "6":"B", "5":"X", "9":"V"}:
print("Well done! You have completed the game!")
# exit the function
return
Just add a break or a return at the end of the elif statement:
print("Well done! You have completed the game!")
break # or return
This will exit the loop. Break makes more sense in this context.

Categories

Resources