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)
Related
This question already has answers here:
How can I check if string input is a number?
(30 answers)
Closed 3 years ago.
I'm starting out with Python after taking a class that taught us pseudocode. How could I make a validation loop to continue the function if a user inputted a decimal rather than a whole number? At its current state, I've gotten it to recognize when a user enters a number outside of the acceptable range, but if the user enters a decimal number, it crashes. Is there another validation loop that can recognize a decimal?
def main():
again = 'Y'
while again == 'y' or again == 'Y':
strength_score = int(input('Please enter a strength score between 1 and 30: '))
# validation loop
while strength_score < 1 or strength_score > 30 :
print ()
print ('Error, invalid selection!')
strength_score = int(input('Please enter a whole (non-decmial) number between 1 and 30: '))
# calculations
capacity = (strength_score * 15)
push = (capacity * 2)
encumbered = (strength_score * 5)
encumbered_heavily = (strength_score * 10)
# show results
print ()
print ('Your carrying capacity is' , capacity, 'pounds.')
print ('Your push/drag/lift limit is' , push, 'pounds.')
print ('You are encumbered when holding' , encumbered, 'pounds.')
print ('You are heavyily encumbered when holding' , encumbered_heavily, 'pounds.')
print ()
# technically, any response other than Y or y would result in an exit.
again = input('Would you like to try another number? Y or N: ')
print ()
else:
exit()
main()
Depending on what you want the behavior to be:
If you want to accept non-integer numbers, just use float(input()). If you want to accept them but turn them into integers, use int(float(input())) to truncate or round(float(input())) to round to the nearest integer.
If you want to print an error message and prompt for a new number, use a try-catch block:
try:
strength_score = int(input('Please enter a strength score between 1 and 30: '))
except ValueError:
again = input("Invalid input, try again? Y / N")
continue # skip the rest of the loop
That is because you have strength_score as an int, and not a float.
Try changing
strength_score = int(input('Please enter a strength score between 1 and 30: '))
to
strength_score = float(input('Please enter a strength score between 1 and 30: '))
Tested with 0.1 and 0.0001 and both are working properly.
I would like to be able to check weather the user has inputed a 8-digit number, not for example, a 7 digit number, and tell them that the number they inputted is too long or not long enough.
For reference here is the input:
cardNumber = input("What is your 8 digit card number: ")
I guess you can use len() function.
Something like if len(cardnumber) != 8: print("Please, input 8 digit number.").
You can use the usual len:
Python 3:
cardNumber = input("What is your 8 digit card number?")
s = len(cardNumber)
if s < 8: print("Too short")
elif s > 8: print("Too long")
else: print("Right Length")
Python 2:
cardNumber = raw_input("What is your 8 digit card number?")
s = len(cardNumber)
if s < 8: print("Too short")
elif s > 8: print("Too long")
else: print("Right Length")
Generally, you can get the number of digits of an integer by using len(str(number))
In case you want to loop until the user has entered the correct number:
try:
input = raw_input # make this Python 2.6+ and 3.5+ compatible
except NameError:
pass
while True:
cardNumber = input("What is your 8 digit card number: ")
if len(cardNumber) == 8:
break
if len(cardNumber) < 8:
print("Your number is not long enough, please try again...")
elif len(cardNumber) > 8:
print("Your number is too long, please try again...")
print("Thank you, your number is: {}".format(cardNumber)
If your are using Python 2, use raw_input instead of input, which will always return a string:
>>> cardNumber = raw_input("What is your 8 digit card number: ")
What is your 8 digit card number: 00000001
>>> len(cardNumber)
8
In Python 2, raw_input will return the entered value as string, while input will evaluate the entered value as code, et is equivalent to eval(raw_input(prompt)).
You can check that with the following code:
>>> cardNumber = input("What is your 8 digit card number: ")
What is your 8 digit card number: 2 + 4
>>> cardNumber
6
With Python 3, however, the old raw_input was renamed to input, and the old input does not exists, although you can still achieve the same with eval(input()).
Once you have the string representation of the card number, you can use len to get the number of characters.
However, I would rather use Regex to validate the input instead of just checking the length, as you may have letters or other symbols as well. You can wrap the whole thing in a loop to keep asking until a valid value is entered. Assuming you are using Python 3, it will look like this:
import re
from termcolor import colored
while True:
cardNumber = input("What is your 8 digit card number: ")
if not re.match('[0-9]{8}', cardNumber):
print(colored("\nThe entered value is not valid. Please, try again.\n", "red"))
else:
break
As part of a larger menu-driven program, I'd like to test user input to see if that input:
is an integer AND
if it is an integer, if it is within the range 1 to 12, inclusive.
number = 0
while True:
try:
number = int(input("Enter a whole number between 1 and 12 >>> "))
except ValueError:
print("Invlaid input, please try again >>> ")
continue
else:
if not (1<= number <=12):
print("Need a whole number in range 1-12 >>> ")
continue
else:
print("You selected:",number)
break
I'm using Python 3.4.3, and wanted to know if there's a more succinct (fewer lines, better performance, more "Pythonic", e.g.) way to achieve this? Thanks in advance.
You don't need anything bar one if in the try:
while True:
try:
number = int(input("Enter a whole number between 1 and 12 >>> "))
if 1 <= number <= 12:
print("You selected:", number)
break
print("Need a whole number in range 1-12 >>> ")
except ValueError:
print("Invlaid input, please try again >>> ")
Bad input will mean you go straight to the except, if the input is good and is in your accepted range, the print("You selected:", number) and will be executed then we break or else print("Need a whole number in range 1-12 >>> ") will be executed if is outside the range.
Your code looks pretty good to me. Minor fix-ups (spelling, indentation, unnecessary continues):
while True:
try:
number = int(input("Enter a whole number between 1 and 12 >>> "))
except ValueError:
print("Invalid input, please try again >>> ")
else:
if 1 <= number <= 12:
print("You selected: {}".format(number))
break
else:
print("Need a whole number in range 1-12 >>> ")
Use isdigit() to check for non-digit characters. Then you shouldn't need to catch the exception. There's only one if and it uses operator short-circuiting to avoid doing int(blah) if blah contains non-digits.
while True:
num_str = raw_input("Enter a whole number between 1 and 12 >>> ")
if num_str.isdigit() and int(num_str) in range(1,13):
print("You selected:",int(num_str))
break
else:
print("Need a whole number in range 1-12 >>> ")
I don't think you need a whole try/except block. Everything can be fit into a single condition:
number = raw_input("Enter a whole number between 1 and 12 >>> ")
while not (number.isdigit() and type(eval(number)) == int and 1<= eval(number) <=12):
number = raw_input("Enter a whole number between 1 and 12 >>> ")
print("You selected:",number)
I'd like to challenge myself and develop my programming skills. I would like to create a program that asks for the user to enter a range of numbers where odd and even numbers should be separated (preferably through search) and also separated by a specified jump factor.
Also the user should be allowed to choose whether or not they would like to continue. And if so they can repeat the process of entering a new range.
for example when the program is run a sample input would be:
"Please enter the first number in the range": 11
"Please enter the last number in the range": 20
"Please enter the amount you want to jump by": 3
and the program would output:
"Your odd Numbers are": 11,17
"Your even Numbers are": 14,20
"Would you like to enter more numbers(Y/N)":
So far what I have for code is this but am having trouble putting it together and would appreciate some help.
import sys
print("Hello. Please Proceed to Enter a Range of Numbers")
first = int(input("please enter the first number in the range: "))
last = int(input("please enter the last number in the range: "))
jump = int(input("please enter the amount you want to jump by: "))
def mylist(first,last):
print("your first number is: ",first,"your last number is: ",last,"your jump factor is: ",jump)
def binarySearch (target, mylist):
startIndex = 0
endIndex = len(mylist) – 1
found = False
targetIndex = -1
while (not found and startIndex <= endIndex):
midpoint = (startIndex + endIndex) // 2
if (mylist[midpoint] == target):
found = True
targetIndex = midpoint
else:
if(target<mylist[midpoint]):
endIndex=midpoint-1
else:
startIndex=midpoint+1
return targetIndex
print("your odd Numbers are: ")
print("your even Numbers are: ")
input("Would you like to enter more numbers (Y/N)?")
N = sys.exit()
Y = first = int(input("please enter the first number in the range"))
last = int(input("please enter the last number in the range"))
jump = int(input("please enter the amount you want to jump by: "))
question - "So far what I have for code is this but am having trouble putting it together and would appreciate some help."
answer -
As a start, it seems like a good idea to group your inputs and outputs into functions! Then putting it together is a snap!
def get_inputs():
bar = input('foo')
def process_inputs():
bar = bar + 1
def print_outputs():
print(bar)
if '__name__' == '__main__':
get_inputs()
process_inputs()
print_outputs()
You could even toss in something like if input('more? (Y/N):') == 'Y': in a while loop.
Maybe I'm missing something but couldn't you replace your binary search with the following?
>>> list(filter(lambda x: x%2 == 1, range(11, 20 + 1, 3)))
[11, 17]
>>> list(filter(lambda x: x%2 == 0, range(11, 20 + 1, 3)))
[14, 20]
This question already has answers here:
Accepting only numbers as input in Python
(2 answers)
Closed 7 years ago.
Hi i am trying to make the program only accept the numbers 0, 4, 6, and 12, and not allow anything else to be inputted. So far i have been successful in only allowing certain integers to be entered, however i am having trouble with not allowing any letters to be entered. When a letter is entered, the entire program crashes. Please could you help me only allow integers to be entered? Thank you.
My code is below:
from random import randint
def simul():
dice = int(input("What sided dice would you like to roll? 4, 6 or 12? 0 to not roll:"))
if dice != 4 and dice!=6 and dice!=12 and dice!=0:
print('You must either enter 4, 6, or 12')
simul()
elif dice==0:
exit()
else:
while dice !=0 and dice==4 or dice==6 or dice ==12 :
print (randint(1,dice))
dice = int(input("What sided dice would you like to roll? 4, 6 or 12? press 0 to stop."))
simul()
A couple of things you could look for in your code:
using try/catch is the recommended way to test input for many reasons including knowing the exact cause of the error
you can reduce some of your ifs and elses by thinking a little more about how they are nested
having the function call itself and using a while loop isn't the best way, use one or the other
in your case, you don't really need to allow only integer input, what you're looking for is to only allow a 0, 4, 6, or 12, which you do with the if statement
from random import randint
def simul():
while True:
try:
dice = int(input("What sided dice would you like to" \
" roll? 4, 6 or 12? 0 to not roll: "))
if dice not in (4, 6, 12, 0):
raise ValueError()
break # valid value, exit the fail loop
except ValueError:
print("You must enter either 4, 6, 12, or 0")
if dice == 0:
return 0
print(randint(1, dice))
return dice
if __name__ == '__main__':
while simul() != 0:
pass
I would encapsulate the "constrained input" functionality into a separate, reusable function:
def constrained_int_input(prompt, accepted, toexit=0):
msg = '%s? Choose %s (or %s to exit)' % (
prompt, ', '.join(str(x) for x in sorted(accepted)), toexit)
while True:
raw = raw_input(msg)
try:
entered = int(raw)
except ValueError:
print('Enter a number, not %r' % raw)
continued
if entered == toexit or entered in accepted:
return entered
print('Invalid number: %r -- please enter a valid one' % entered)
Now you can call e.g
dice = constrained_int_input('What sided dice would you like to roll', (4,6,12))
whenever required and be sure that dice will end up with one of the accepted integers, including possibly the to-exit value of 0.
put it in a try catch block like so:
try:
choice = int(raw_input("Enter choice 1, 2 or 3:"))
if not (1 <= choice <= 3):
raise ValueError()
except ValueError:
print "Invalid Option, you needed to type a 1, 2 or 3...."
else:
print "Your choice is", choice
copied from: limit input to integer only (text crashes PYTHON program)
while True:
x=input("4,6 or 12? 0 to not roll: ")
if x.isalpha():
print ("only numbers.")
continue
elif int(x)==0:
print ("quiting..")
break
elif int(x)!=4 and int(x)!=6 and int(x)!=12:
print ("Not allowed.")
else:
print (random.randint(1,int(x)))
Here is another method, use isalpha().