关于python:检查用户输入?

Checking user input?

本问题已经有最佳答案,请猛点这里访问。

我想检查用户输入是否是一个数字,如果它继续代码,如果它不重新询问,直到他们输入一个数字

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# This progam will simulate a dice with 4, 6 or 12 sides.

import random

def RollTheDice():

    print("Roll The Dice")
    print()




    ValidNumbers = [4,6,12]

    Repeat = True

    while Repeat == True:
        Counter = 0
        NumberOfSides = input("Please select a dice with 4, 6 or 12 sides")

        if not type(NumberOfSides) == int or not int(NumberOfSides) == ValidNumbers:
            print("You have entered an incorrect value")
            NumberOfSides = int(input("Please select a dice with 4, 6 or 12 sides"))


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


首先,一般编程实践:使用camelCase或under_scores作为变量名。

这是你想要的(我认为):

1
2
3
4
5
6
7
8
9
10
11
validNumbers = [4, 6, 12]
repeat = True
while repeat:
    userNum = input("Enter a number") # input returns a string
    try: # try to convert it to an integer
        userNum = int(userNum)
    except ValueError:
        pass
    if userNum in validNumbers:
        repeat = False
# do everything else