繁体   English   中英

如何在 IF 语句中要求输入?

[英]How do I ask for an input within an IF statement?

我是初学者,如果我的代码看起来很乱,我很抱歉。 我正在尝试编写一个代码,询问您是否要计算周长或三角形的面积或正方形,只是想不出连接 q1 和 q2 的最佳方法。

代码最好打印所选的计算方式,如果您选择了正方形的面积,也会将“x”变量更改为 1,如果您选择了正方形的周长等,则将其更改为 2。

随意提供任何编码技巧。

q1 = input("Type 1 for Square, type 2 for Triangle."))

if q1 == "1":
    q2 = input("Type 1 for Area, Type 2 for Perimeter."))
      if q2 == "1":
        print("Calculating the Area of a Square.")
        x = 1
      else:
        print("Calculating the Perimeter of a Square.")
        x = 2

else:
    q2 = input("Type 1 for Area, Type 2 for Perimeter."))
      if q2 == "1":
        print("Calculating the Area of a Triangle.")
        x = 3
      else:
        print("Calculating the Perimeter of a Triangle.")
        x = 4

有更多干净的方法可以做你想做的事情,但我发现这种方法初学者友好,只需要求用户在程序开始时输入两个问题,因为只有 4 个选项 - 选中所有选项。

q1 = input("Type 1 for Square, type 2 for Triangle.")
q2 = input("Type 1 for Area, Type 2 for Perimeter.")


if q1 == "1" and q2 == "1":
    #do something
    
if q1 == "1" and q2 == "2":
    #do something
    
if q1 == "2" and q2 == "1":
    #do something
    
if q1 == "2" and q2 == "2":
    #do something

如果条件语句的所有分支都问两个问题,我会先问两个问题,然后同时测试两个结果:

q1 = input("Type 1 for Square, type 2 for Triangle.")
q2 = input("Type 1 for Area, Type 2 for Perimeter.")

if q1 == "1" and q2 == "1":
    # Area of a Square
    print(...)
    x = 1
elif q1 == "1" and q2 == "2":
    # Perimeter of a Square
    print(...)
    x = 2
elif q1 == "2" and q2 == "1":
    # Area of a Triangle
    print(...)
    x = 3
elif q1 == "2" and q2 == "2":
    # Perimeter of a Triangle
    print(...)
    x = 4
else:
    # The not valid input cases (never forget about non nominal cases)
    raise ValueError('Not valid input q1 {} q2 {}'.format(q1, q2))

使这段代码更高效的几件事!

q1 = input("Type 1 for Square, type 2 for Triangle."))

您可能还想在此处添加此行: q2 = input("Type 1 for Area, Type 2 for Perimeter."))现在您应该在此处分配此变量

x = q2

然后进行适当的调整。 最终代码:

q1 = input("Square or triangle? type 1 for square type 2 for triangle")
q2 = input("Type 1 for Area, Type 2 for Perimeter."))
x = q2
if q1 == "1":
   if x == "1":
        print("Calculating the Area of a Square.")
      else:
        print("Calculating the Perimeter of a Square.")
else:
   if x == "1":
      print("Calculating the Area of a Triangle.")
      
   else:
      print("Calculating the Perimeter of a Triangle.")
        

如果它不起作用让我知道,我会尝试修复它!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM