尝试代码中的功能

时间:2015-12-02 13:22:36

标签: python

嗯,我对编程很陌生,我需要一些关于此代码的帮助。

roundvalue = True
rounds = 0
while roundvalue == True:
 rounds= input("Pick a number of rounds (3 or 5)")
try:
    int(rounds)
except ValueError:
    try:
        float(rounds)
    except ValueError:
        print ("This is not a number")

    if rounds  ==  3:
       print("You chose three rounds!")
       roundvalue = False
    elif rounds == 5:
        print ("You chose 5 rounds")
        roundvalue = False
    else:
        print ("Input again!")

代码的要点是选择一些轮次,如果用户输入任何其他内容(字母或数字不是3或5),它应该重复这个问题。 *(我的代码目前正在重复'选择一些轮次(3或5)'

2 个答案:

答案 0 :(得分:0)

这将以更简洁的方式达到预期的效果。

while True:
    rounds = input("Pick a number of rounds (3 or 5)")
    try:
        rounds = int(rounds)
        if rounds in [3,5]:
            break
    except ValueError:
        print("This is not a number")
    print("Input again!")
print ("You chose %d rounds" % rounds)

答案 1 :(得分:-2)

首次尝试时,您应该将rounds = int(rounds)放在rounds = float(round).

下面的试试中

使用适当的缩进检查:

roundvalue = True
rounds = 0 
while roundvalue == True:
    rounds= input("Pick a number of rounds (3 or 5)")
    try:
        rounds = int(rounds)
    except ValueError:
        print ("This is not a number")

    if rounds  ==  3:
        print("You chose three rounds!")
        roundvalue = False
    elif rounds == 5:
        print ("You chose 5 rounds")
        roundvalue = False
    else:
        print ("Input again!")