【问题标题】:Creating two and one condition in a program在程序中创建两个和一个条件
【发布时间】:2019-10-07 01:42:38
【问题描述】:

我有一个代码允许用户在 3 个选项之间进行选择 0- 初学者 1- 中级 2:高级

我的代码是:

if inp == 0:
    out = "Beginner"

elif inp == 1:
    out = "Intermediate"

elif inp == 2:
    out = "Advanced"

else:
    print("Invalid")

但是,我想要它,所以如果输入大于 3 的数字,它就不会进入第二部分。

我拥有的代码的第二部分是:

x=float(input("Choose a number between [0,90]"))
if x > 0 and x < 90:
    print("Is Latitude in the North or South Hemisphere?")
else:
    print ("Invalid")

有人可以提供一些关于条件应该如何的见解吗? 谢谢!

【问题讨论】:

    标签: python input output conditional-statements


    【解决方案1】:

    如果您在第二部分之前测试out 的存在,您可以使用您的代码来执行此操作。 你只需要在 if 之前初始化out

    out = ""
    if inp == 0:
        out = "Beginner"
    elif inp == 1:
        out = "Intermediate"
    elif inp == 2:
        out = "Advanced"
    else:
        print("Invalid")
    

    现在,因为out已经变成了一个全局变量,你可以测试一下out是否被设置了。如果未设置out,则跳过下一部分。

    if out:
        x=float(input("Choose a number between [0,90]"))
        if x > 0 and x < 90:
        print("Is Latitude in the North or South Hemisphere?")
        else:
            print ("Invalid")
    

    实际上,您可以通过多种不同的方式来做到这一点。就个人而言,我可能会使用一个函数,然后使用一个 return 语句来停止执行,但你也可以以这种方式中断和停止事情,或者使用某种形式的循环来等待你想要的变量。

    编程的好处和令人沮丧的地方在于,通常有不止一种方法可以让它正确。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-04
      • 2023-03-17
      • 1970-01-01
      相关资源
      最近更新 更多