Skip to content Skip to sidebar Skip to footer

Checking Input Is A Number In Python

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 a

Solution 1:

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 = 0while number_of_sides notin 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() 
              orint(number_of_sides_string) notin 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.

Solution 2:

Capture the string in a variable, say text. Then do if text.isdigit().

Solution 3:

Make a function out of:

while NumberOfSides != 4and NumberOfSides != 6and 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.

Solution 4:

You can use type method.

my_number = 4iftype(my_number) == int:
    # do something, my_number is intelse:
    # my_number isn't a int. may be str or dict or something else, but notint

Or more «pythonic» isinstance method:

my_number = 'Four'ifisinstance(my_number, int):
    # do somethingraise Exception("Please, enter valid number: %d" % my_number)

Post a Comment for "Checking Input Is A Number In Python"