I am trying to create a dice game using a while loop and if's. I have done this successfully however I am trying to figure out how to program the game so that if numbers 4,6 or 12 are not input it will state invalid choice and will ask diceChoice again.
Can anybody help?
So far I have...
rollAgain = "Yes" or "yes" or "y"
while rollAgain == "Yes" or "yes" or "y":
diceChoice = input ("Which dice would you like to roll; 4 sided, 6, sided or 12 sided?")
if diceChoice == "4":
import random
print("You rolled a ", random.randint(1,4))
if diceChoice == "6":
import random
print("You rolled a ", random.randint(1,6))
if diceChoice == "12":
import random
print("You rolled a ", random.randint(1,12))
rollAgain = input ("Roll Again?")
print ("Thank you for playing")
Fixed While Loop, Tidied up all the repetition. Moved import statement to the top. Structured to allow more options for rollAgain and diceChoice.
import random
rollAgain = "Yes"
while rollAgain in ["Yes" , "yes", "y"]:
diceChoice = input ("Which dice would you like to roll; 4 sided, 6, sided or 12 sided?")
if diceChoice in ["4","6","12"]:
print("You rolled a ",random.randint(1,int(diceChoice)))
else:
print "Please input 4,6, or 12."
rollAgain = input ("Roll Again?")
print ("Thank you for playing")
Doing this sort of assignment:
rollAgain = "Yes" or "yes" or "y"
Is unnecessary - only the first value will be inputted. Pick one for this variable; you only need one for its purposes.
This sort of assignment doesn't work here either:
while rollAgain == "Yes" or "yes" or "y":
It will again only check the first value. You either have to split it up like other posters have done, or use a different data structure that will incorporate them all like a list in the code above.
You should only import random once at the top
import random #put this as the first line
Your rollAgain declaration should only set it to one value
rollAgain = "yes" # the or statements were not necessary
You forgot to do rollAgain == in your subsequent conditionals, here is a simpler way
while rollAgain.lower().startswith("y"): #makes sure it starts with y or Y
To do an invalid input statement, you could use elif: and else: statements to keep it simple
if diceChoice == "4":
print("You rolled a ", random.randint(1,4))
elif diceChoice == "6":
print("You rolled a ", random.randint(1,6))
elif diceChoice == "12":
print("You rolled a ", random.randint(1,12))
else:
print("Invalid Input, please enter either 4, 6, or 12")
Your old while loop would never have exit because you were basically saying this
while rollAgain == "Yes" or True or True #because non-empty strings are treated as True
edit since you asked about in statements, here is a brief example
>>>5 in [1,2,3,4]
False
>>>5 in [1,2,3,4,5]
True
The in statement is similar to a contains() in other languages it checks to see if the variable is inside the list
Since 5 is not in the list [1,2,3,4] it returned False
however, 5 IS in the list [1,2,3,4,5] so it returns True
You could use this several places in your code, specifically if you want to make sure a variable is within a set of options. I didn't recommend it to keep it simple for you.
diceChoice = None
while diceChoice not in ["4","12","6"]:
diceChoice = input("enter choice of dice(4,6,12)")
print "You picked %d"%diceChoice
Just my take on it:
# If you are only using one function from random
# then it seems cleaner to just import that name
from random import randint
while True:
choice = int(input("Which dice would you like to roll; 4 sided, 6, sided or 12 sided?\n:"))
# Using sets for 'in' comparisons is faster
if choice in {4, 6, 12}:
print("You rolled a", randint(1, choice))
else:
print("Please input 4, 6, or 12.")
# Make the input lowercase so that it will accept anything that can be
# interpreted as "yes".
if input("Roll Again?\n:").lower() not in {"yes", "y"}:
# End the game by breaking the loop
break
# You should use an input at the end to keep the window open to see the results
input("Thank you for playing!")
Related
I'm making a dice rolling game. The following code produces an error, saying "continue outside of loop":
import random
repeat="y" or "yes"
while repeat == "y" or "yes"
print("Rolling the dice")
print(random.randint(1,6))
repeat = input("Do you wanna roll again Y/N?").lower()
if repeat =="y" or "yes":
continue
else:
print("Thanks for rolling")
break
Why am I getting this error?
You cannot affect 2 walues as teh same time, chose "y" or "Y" in your expressions.
repeat="y"
while (repeat == "y") or (repeat == "yes"):
You have to check your indentation too,
repeat = input has to be inside the loop, so you get a new input to check each time.
The final print can be put outside the loop at the very end.
Here is a working example, and you can type anything starting with "y"/"Y" to continue rolling:
import random
repeat="y"
while (repeat[0]) == "y":
print("Rolling the dice")
print(random.randint(1,6))
repeat = input("Do you wanna roll again Y/N?").lower()
print("Thanks for rolling")
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 2 years ago.
Hello everyone so I started working on a dice rolling game that rolls the dice then displays the value and asks if the user would like to re-roll. I know how to do all that but I wanted to put in a part that would loop if the user put in a value that was not Y(Yes) or N(No). So I created another while statement to accomplish this. If you input an invalid response the program asks you to type Y or N. Then if you type an invalid response again it keeps asking until the expected value is entered. Here is the code and I'll highlight the part where I don't understand. I commented why I think it works but I'm not sure. If someone could explain why it works I appreciate it thanks a lot!
import random
value = random.randint(1, 2)
run = True
while run:
print("You roll a six sided dice \n")
print("Your dice landed on "+str(value) + "\n")
answer = input("Do you want to play again? (Y or N) \n")
if answer == "Y":
continue
if answer == "N":
print("Thanks for playing \n")
exit()
# after you type an invalid response it's stored in variable answer
# the program then goes to answer2 input which asks please enter Y or N
# if the program then detects an invalid answer it goes back to the top
# of the while statement and uses answer ones response which is still
# an invalid response???? I'm guessing since answer is always invalid and the
# decisions only two options that are yes or no it goes back to the top of the 2nd while loop
# Not sure tho.
# 2nd while loop
while answer != "Y" or "N":
answer2 = input("Please enter Y or N \n")
while answer2 == "Y":
print("You roll a six sided dice \n")
print("The dice landed on " + str(value) + "\n")
answer2 = input("Do you want to play again \n")
continue
if answer2 == "N":
print("THanks for playing")
exit()
I've commented out why I think it works but
import random
value = random.randint(1, 2)
def getans():
while True:
answer = raw_input("Do you want to play again? (Y or N) \n")
if answer == "Y":
return True
elif answer == "N":
return False
else:
print ("Please enter Y or N \n")
continue
while True:
print("You roll a six sided dice \n")
print("Your dice landed on "+str(value) + "\n")
answer = getans()
if answer == True:
continue
elif answer == False:
print("Thanks for playing \n")
exit()
else:
print ("this will never run")
I have created a program where the user can select a certain sided dice then it rolls and outputs the number generated, it then asks if the user wants to roll again and by using a while loop. i have wrote the program and for some reason it keeps on repeating the input dice side number prompt and i don't know why, here is the code
import random
roll_agn='yes'
while roll_agn=='yes':
dice=input ('Please choose a 4, 6 or 12 sided dice: ')
if dice ==4:
print(random.randint(1,4))
elif dice ==6:
print(random.randint(1,6))
elif dice ==12:
print(random.randint(1,12))
else:
roll_agn=input('that is not 4, 6 or 12, would you like to choose again, please answer yes or no')
if roll_agn !='yes':
print ('ok thanks for playing')
I suspect it is something to do with the while loop or the indentation, but I have been fiddling with it for like 3o mins and i cant get it to work properly, so if someone could help me out here it would be appreciated, Thanks !
The indentation on else: roll_agn=input is such that it only runs after you exit the while loop - but the while loop can never end until you run the else clause, therefore infinite loop.
Here is a cleaned-up, better-structured version:
# assumes Python 3.x
from random import randint
def get_int(prompt):
while True:
try:
return int(input(prompt)) # if Python 2.x use raw_input instead of input
except ValueError:
# not an int
pass
def get_yn(prompt):
while True:
value = input(prompt).strip().lower() # if Python 2.x use raw_input instead of input
if value in {'y', 'yes'}:
return True
elif value in {'n', 'no'}:
return False
def roll(sides):
return randint(1, sides)
def main():
while True:
sides = get_int("Number of sides on die (4, 6, or 12)? ")
if sides in {4, 6, 12}:
print("You rolled a {}".format(roll(sides)))
else:
print("U no reed gud?")
if not get_yn("Play again (y/n)? "):
print("Thanks for playing!")
break
if __name__=="__main__":
main()
It looks like you have indentation problems with the if statements. Try lining up elif with if.
if dice ==4:
print(random.randint(1,4))
elif dice ==6:
print(random.randint(1,6))
elif dice ==12:
print(random.randint(1,12))
I have made this code for a project and i have run into a problem with the while loop becasue it just repeat the first input function, here is the code, i would aprriecate it if someone could point out my problem and help me fix my code, thnx
import random
roll_agn='yes'
while roll_agn=='yes':
dice=input ('Please choose a 4, 6 or 12 sided dice: ')
if dice ==4:
print(random.randint(1,4))
elif dice ==6:
print(random.randint(1,6))
elif dice ==12:
print(random.randint(1,12))
else:
roll_agn=input('that is not 4, 6 or 12, would you like to choose again, please answer yes or no')
if roll_agn !='yes':
print ('ok thanks for playing')
The else block of the while would be executed only if roll_agn became non-'yes' inside the loop. You never change it inside the while loop, so it loops forever.
Your else statement is unindented (outside of the loop), so the variable within is never reset, so the condition that the while loop requires is always True, hence an infinite loop. You just need to indent this:
elif dice ==12:
...
else:
^ roll_agn = input()
Your indentation is off as others have pointed out. Here are a few suggestions on how to improve your code a little further
import random
while True:
try:
dice = int(input ('Please choose a 4, 6 or 12 sided dice: ')) # this input should be an int
if dice in (4, 6, 12): # checks to see if the value of dice is in the supplied tuple
print(random.randint(1,dice))
choice = input('Roll again? Enter yes or no: ')
if choice.lower() == 'no': # use .lower() here so a match is found if the player enters No or NO
print('Thanks for playing!')
break # exits the loop
else:
print('that is not 4, 6 or 12')
except ValueError: # catches an exception if the player enters a letter instead of a number or enters nothing
print('Please enter a number')
This will work no matter what the player enters.
I cannot get the following to function. I need validation by adding
else:
print("Type only 4, 6, or 12.")
However doing this on the code does not work:
def dicegame():
#This defines the dicegame coding so I can call it later on
number=int(input("Hello. Enter either 4,6 or 12 to determine what sided dice you want to use "))
import random
if number=="4" or "6" or "12":
print("You have rolled a", number, "sided dice with the number", random.randint(1,number))
#These if loops direct the program to the correct coding down to what the user inputs (ie. 4, 6 or 12)
print("Would you like to roll again?")
answer=input("Enter either yes or no.")
if answer == ("yes"):
dicegame()
if answer == ("no"):
print("Ok, goodbye")
#Program prints "Would you like to roll again?
#Using input, user can reply to what the program prints, labelled with the variable 'answer'
dicegame()
The loop breaks once adding the else loop for my validation.
I don't see a loop, but one thing is wrong:
instead of
if number=="4" or "6" or "12":
use
if number in (4, 6, 12):
Note that number has already been casted to int
try
if number==4 or number==6 or number==12:
or
if number in [4, 6, 12]:
'6' is always true - so you always fulfil the condition...
You also have to remove the quotation marks since you write number=int(...).