[英]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.