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

2024-05-13 07:10:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我是初学者,如果我的代码看起来很混乱,我很抱歉。我试着做一个代码,询问你是否想要计算三角形或正方形的周长或面积,只是想不出连接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


Tags: ofthe代码forinputtypeareaprint
3条回答

有几件事可以让这段代码更高效

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

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

有更多干净的方法来做你想做的事情,但我发现这种方法对初学者很友好,只需在程序开始时让用户输入这两个问题,因为只有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))

相关问题 更多 >