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

问题描述

我是一个初学者,如果我的代码看起来凌乱,请对不起。我正在尝试编写一个代码,询问您是否要计算周长,三角形面积或正方形面积,只是无法找出附加q1和q2的最佳方法

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

随时提供任何编码提示

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 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.")
        

如果它不起作用,请告诉我,我会尝试修复它!