【问题标题】:'if' and 'elif' and 'else' in python question [closed]python问题中的'if'和'elif'和'else'[关闭]
【发布时间】:2020-09-20 05:44:49
【问题描述】:

我当前的代码:

age = int(input("Your Age is:"))
if (age <11 or age >60 ):
    print("You are not eligible")
    break

elif (age >=11 and age<=60):
    print("You are eligible")
    continue

elif (age >15 and age<60):
    print('Ticket is $20')

elif (age >=11 and age<=15):
    print("Ticket is $10")

输出:

File "<ipython-input-12-47ead3cda82a>", line 7
    print("You are eligible to watch a football match")
           ^
SyntaxError: 'break' outside loop

我想做什么:

如果年龄小于 11 岁或大于 60 岁,则应显示您不符合条件并在此处中断循环。

但是如果年龄在 11 到 60 岁之间,那么它应该显示 You are compliant 然后下一个循环开始,即如果 age 大于 15 且小于 60 则它应该显示 Ticket is $20 否则年龄在大于或等于 11 和小于或等于 15 之间显示 Ticket is $15 em>

【问题讨论】:

  • 此代码不在循环内。循环使用for 或while 创建。
  • 我认为你不明白什么是“循环”。 if 不是循环,循环是重复的东西。
  • 谢谢..????我刚开始写这些条件,请原谅我的无知。????
  • 这能回答你的问题吗? Python: 'break' outside loop

标签: python if-statement


【解决方案1】:

这不是循环,您不能使用break 和continue。循环是用for 或while 语句创建的——它是对反复出现的事物的隐喻,例如字符串循环。

如果您想优化标准,您应该使用嵌套的if 语句。

另外,当条件与if 条件完全相反时,不要使用elif。只需使用else: 并省略条件即可。

if (age <11 or age >60 ):
    print("You are not eligible")
else:
    print("You are eligible")

    if (15 < age <60):
        print('Ticket is $20')
    else:
        print("Ticket is $10")

【讨论】:

  • 但是当年龄小于11岁大于60岁时,其他if else条件仍然继续。它应该只显示您不符合条件...
  • 不应该。你确定你的缩进正确吗?
【解决方案2】:

你可以把它放在一个循环中。 这是一个替代解决方案。范围是一种更酷的做事方式。

记住range(a,b)从a开始一直到b-1

这是一种不同风格的解决方案。我刚刚展示了一个方法。

我知道这不满足您问题中的所有标准。

我相信你足够聪明,可以调整它以使其成为你的。


while(True):
    # starting an infinite while loop

    age = int(input("Your Age is: "))

    if age in range(15, 60):

        print("Ticket is $20")
        continue

    if age in range(11, 15):

        print("Ticket is $10")
        continue

    print("You are not eligible")
    break

break 语句终止包含它的循环。程序的控制流向紧跟在循环体之后的语句。

如果break 语句在嵌套循环内(在另一个循环内循环),break 语句将终止最内层循环。

continue 语句仅用于跳过当前迭代循环内的其余代码。循环不会终止,而是继续下一次迭代。

在您的示例中,您在循环外使用了break。

【讨论】:

  • Wbat 是循环的重点?问题的答案在重复时不会改变。
  • 作者可能需要一个循环。可能只是一个有趣的项目
【解决方案3】:

我相信你是故意的:

age = int(input("Your Age is: "))
IsEligible = True
while age!=-1:  # input age as -1 will break the loop
    if age <11 or age >60:
        print("You are not eligible")
        IsEligible = False
    # now for this itteration we know that the age is eligible
    if IsEligible:
        print "you are eligible"
        if age<=15 and age>=11:
            print("Ticket is $15")
        else:
            print "Ticket is $20 "
    age = int(input("Your Age is: "))
    IsEligible = True

【讨论】:

  • 循环的意义何在?这个人的年龄不会改变。
  • 我认为这是一个可以为他想要的任意数量的人输入年龄和接收价格或/和状态的系统
  • 他发布的代码只是为了回答一个人。如何将它用作更大应用程序的一部分是一个单独的问题。它可能在一个函数中,而循环在调用者中。
猜你喜欢
  • 2017-05-03
  • 1970-01-01
  • 2017-11-27
  • 1970-01-01
  • 2012-09-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-11
  • 2022-11-03
相关资源
最近更新 更多