How do I ask the user if they want to play again and repeat the while loop?
15,288
Points for your code:
- Code you have pasted don't have
':'
afterif,elif
andelse.
- 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 asint(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
Author by
Lizzie
Updated on June 05, 2022Comments
-
Lizzie almost 2 years
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?
-
Dinesh Pundkar over 7 years@Lizzie - Please check the updated code and comments