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(...).
Related
Why does this code make me type yes or no twice to get the result I want instead of just once?
This is for the python dice roll text game, btw...
import random
min = 1
max = 20
# <!--TWO D-20's, A-LA DUNGEONS AND DRAGAONS--!>
roll_again = "yes"
while roll_again == "yes" or roll_again == "y":
print("Rolling the dice")
print("The values are --- ")
print(random.randint(min, max))
print(random.randint(min, max))
roll_again = input("Would you like to play again?")
answer = input()
if answer == ('yes'):print("OK, here we go!")
elif answer == ("no"):print("Sorry about that, please try again another time.")
I am entering into a python class on Monday, this is one of the more common types of beginners code (granted I spiced it up by changing the dice from 6 sided to 20 sided, but it's more fun that way...lol) that I have read in some of the python books and sites I have visited, so I wanted to kind of get my feet wet a bit before I start my class.
So, any idea why I have to type yes or no twice, hitting enter after each time, to get it to run properly?
For the record, I am on Win10 right now but I also mostly use Parrot Security OS (Linux)...
Thanks for any and all feedback which anyone can provide...I know it's probably a stupid noob mistake or oversight, since I don't really know or understand the basics, but the quicker I can grasp them the better...
Python's function input() asks for users to input and waits the answer. As it can be seen in your code, you're doing it two times:
roll_again = input("Would you like to play again?")
answer = input()
The variable roll_again is being redeclarated to the first user's input, then the variable answer is getting the second user's input. You maybe meant to do something like:
roll_again = input("Would you like to play again?")
answer = roll_again
But first of all, there is no need to create an answer variable, you could simply use the roll_again on the if. Also the if statement is out of the while so your code might not work as you're trying to anyways~ (it will re-roll if user inputs yes but it will not print the message you're trying to; that will only happen when the user inputs no as that will go out of the while and blah blah blah)
This should be alright:
import random
min = 1
max = 20
# <!--TWO D-20's, A-LA DUNGEONS AND DRAGAONS--!>
roll_again = "yes"
while roll_again == "yes" or roll_again == "y":
print("Rolling the dice")
print("The values are --- ")
print(random.randint(min, max))
print(random.randint(min, max))
roll_again = input("Would you like to play again?")
if roll_again == 'yes' or roll_again == 'y': print("OK, here we go!")
else: print("Sorry about that, please try again another time.")
Every time you call the input() function, it prompts for input. Since you call it twice for each iteration of your while loop, the user is prompted twice per iteration. You should instead only call the input() function once in your while loop.
You can also avoid using the answer variable if you just use the roll_again variable for your conditions for your if and elif.
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 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!")
I need help, my program is simulating the actions of a dice. I want to an error check to occur checking if the input string is a number and if it isn't I want to ask the question again again until he enters an integer
# This progam will simulate a dice with 4, 6 or 12 sides.
import random
def RollTheDice():
print("Roll The Dice")
print()
NumberOfSides = int(input("Please select a dice with 4, 6 or 12 sides: "))
Repeat = True
while Repeat == True:
if not NumberOfSides.isdigit() or NumberOfSides not in ValidNumbers:
print("You have entered an incorrect value")
NumberOfSides = int(input("Please select a dice with 4, 6 or 12 sides")
print()
UserScore = random.randint(1,NumberOfSides)
print("{0} sided dice thrown, score {1}".format (NumberOfSides,UserScore))
RollAgain = input("Do you want to roll the dice again? ")
if RollAgain == "No" or RollAgain == "no":
print("Have a nice day")
Repeat = False
else:
NumberOfSides = int(input("Please select a dice with 4, 6 or 12 sides: "))
As a commenter disliked my first answer with try: except ValueError and the OP asked about how to use isdigit, that's how you can do it:
valid_numbers = [4, 6, 12]
while repeat:
number_of_sides = 0
while number_of_sides not in valid_numbers:
number_of_sides_string = input("Please select a dice with 4, 6 or 12 sides: ")
if (not number_of_sides_string.strip().isdigit()
or int(number_of_sides_string) not in valid_numbers):
print ("please enter one of", valid_numbers)
else:
number_of_sides = int(number_of_sides_string)
# do things with number_of_sides
the interesting line is not number_of_sides_string.strip().isdigit(). Whitespace at both ends of the input string is removed by strip, as a convenience. Then, isdigit() checks if the full string consists of numbers.
In your case, you could simply check
if not number_of_sides_string not in ['4', '6', '12']:
print('wrong')
but the other solution is more general if you want to accept any number.
As an aside, the Python coding style guidelines recommend lowercase underscore-separated variable names.
Capture the string in a variable, say text. Then do if text.isdigit().
Make a function out of:
while NumberOfSides != 4 and NumberOfSides != 6 and NumberOfSides != 12:
print("You have selected the wrong sided dice")
NumberOfSides = int(input("Please select a dice with 4, 6 or 12 sides: "))
And call it when you want to get input. You should also give an option to quit e.g. by pressing 0. Also you should try catch for invalid number. There is an exact example in Python doc. Note that input always try to parse as a number and will rise an exception of it's own.
You can use type method.
my_number = 4
if type(my_number) == int:
# do something, my_number is int
else:
# my_number isn't a int. may be str or dict or something else, but not int
Or more «pythonic» isinstance method:
my_number = 'Four'
if isinstance(my_number, int):
# do something
raise Exception("Please, enter valid number: %d" % my_number)