2017-02-15 28 views
0

我完全是编程的新手,我一直在试图获得一段简单的代码。不过,我不断收到多个不同的错误,所以我认为我做的东西沿线某处非常错误...这里是我的代码的时刻:如果语句条件不符合,返回到一段代码的开头

userName = input('Please enter your name: ') 
age = input('Please enter your age: ') 

if int(age) <= 5: 
    print(userName, 'you are too young to play') break 
else: 
    print (userName, 'Your old enough') 

factor = 2 
finalAge = int(age) + int(factor) 
multAge = int(age) * int(factor) 
divAge = float(age)/int(factor) 

print('In', factor, 'years you will be', finalAge, 'years old', userName) 
print('Your age multiplied by', factor, 'is', multAge) 
print('Your age divided by', factor, 'is', divAge) 

我想要做的是,如果用户的年龄不会高于5,那么他们会收到这样的信息,即他们太年轻了,无法播放,并返回到代码片段的开头 - 再次请求该名称。

有没有人有任何建议如何做到这一点?

回答

0

您需要使用循环。语法取决于您尚未指定的语言。作为伪代码,你可以做

loop indefinitely 
    prompt for name and age 
    if age is less than 5 
     print error 
    otherwise 
     print that age is ok 
     break loop 
0

看看while循环。为此,您可以设置某种条件(例如“old_enough”变量,如果该变量成立,则循环停止运行。

您可以在if语句中设置此值。可无论会使循环运行

有教程的负荷网上对于这一点,但这里是在Python的例子(您的代码示例看起来像Python3):

old_enough = False 
while not old_enough: 
    # do something 
    if age > 5: 
     print("You're old enough") 
     old_enough = True 
    else: 
     print("you're not old enough") 

这应该明智的,如果不是,请请查阅文件,长期来看对你更好