Checking input is a number in python -


i need help, program simulating actions of dice. want error check occur checking if input string number , if isn't want ask question again again until enters integer

# progam simulate dice 4, 6 or 12 sides.  import random   def rollthedice():      print("roll dice")     print()       numberofsides = int(input("please select dice 4, 6 or 12 sides: "))      repeat = true       while repeat == true:           if not numberofsides.isdigit() or numberofsides not in validnumbers:             print("you have entered incorrect value")             numberofsides = int(input("please select dice 4, 6 or 12 sides")          print()         userscore = random.randint(1,numberofsides)         print("{0} sided dice thrown, score {1}".format (numberofsides,userscore))          rollagain = input("do want roll dice again? ")           if rollagain == "no" or rollagain == "no":             print("have nice day")             repeat = false          else:             numberofsides = int(input("please select dice 4, 6 or 12 sides: ")) 

as commenter disliked first answer try: except valueerror , op asked how use isdigit, that's how can 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 dice 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 1 of", valid_numbers)           else:               number_of_sides = int(number_of_sides_string)     # things number_of_sides 

the interesting line not number_of_sides_string.strip().isdigit(). whitespace @ both ends of input string removed strip, convenience. then, isdigit() checks if full string consists of numbers.

in case, check

 if not number_of_sides_string not in ['4', '6', '12']:      print('wrong') 

but other solution more general if want accept number.

as aside, python coding style guidelines recommend lowercase underscore-separated variable names.


Comments

Popular posts from this blog

php - Why I am getting the Error "Commands out of sync; you can't run this command now" -

linux - Does gcc have any options to add version info in ELF binary file? -

java - Are there any classes that implement javax.persistence.Parameter<T>? -