2015-12-02 70 views
-3

嗯,我很新的编程,我需要一些帮助,这个代码。尝试代码中的功能

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)”

+1

这是你真正的缩进? –

+0

这可能是对你有用:[要求用户输入,直到他们给出有效响应](http://stackoverflow.com/q/23294658/953482) – Kevin

+1

缩进在Python中很重要。如图所示,while循环只围绕'rounds ='部分,它不包含'try ... except'。另外'int(rounds)'不会改变'rounds'的值,因此即使你为'rounds'输入'3','rounds == 3'总是'False',因为'rounds'仍然是一个字符串这点。另外:为什么“浮动(轮)”? – dhke

回答

-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!") 
+0

同意关于整数,但为什么漂浮?如果不是字符3或5,则根据OP将其无效。无需检查浮标。另外,我不确定你的缩进是否非常好。 –

+1

不,它不是.... – tglaria

+0

我粘贴,它损坏我的缩进...现在很好。 – PatNowak

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) 
+0

谢谢你的贡献,但我需要一个较长的代码;)。 – Lukas