Ahmed Abukar
Ahmed Abukar

Reputation: 23

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 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: "))

Upvotes: 0

Views: 334

Answers (4)

Thomas Fenzl
Thomas Fenzl

Reputation: 4392

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.

Upvotes: 2

Sofia Velmer
Sofia Velmer

Reputation: 69

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)

Upvotes: 0

Nux
Nux

Reputation: 10032

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.

Upvotes: 0

John Zwinck
John Zwinck

Reputation: 249552

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

Upvotes: 1

Related Questions