[英]My program gives wrong answers between 3-10 C
我在 3 天前開始編程。 這顯示了 3-10 C 之間的錯誤結果,我該如何解決?
x = input("what C is it today: ")
if x < str(20):
print("Its cold")
print("Wear a jacket")
if str(20) <= x < str(30):
print("Its a nice day")
print("don't forget to have fun")
if x >= str(30):
print("Its hot")
print("open the air conditioner")
而不是使用str(20), ...
使用int(x)
。
發生這種情況是因為比較字符串與字符串有點不同。
嘗試如下:
x = input("what C is it today: ")
x = int(x) # here we cast x to an Integer
if x < 20:
print("Its cold", "Wear a jacket") # you can pass multiple value
if 20 <= x < 30:
print("Its a nice day", "don't forget to have fun")
if x >= 30:
print("Its hot", "open the air conditioner")
正如 Mehrdad 所說, input() 假定您輸入的內容是一個字符串。 所以你應該將輸入轉換為 int 類型。
而且我可以發現您可以對代碼進行的其他改進。 例如:對相互關聯/在排除過程中的條件使用elif
和else
語句(比如如果不是1,就是2)
x = int( input("what C is it today: ") ) # input (string to integer)
if x < 20:
print("Its cold", "Wear a jacket") # you can pass multiple value
elif 20 <= x < 30:
print("Its a nice day", "don't forget to have fun")
else: # this condition is not needed, because we eliminated the possibilities that x is less than 30, so everything else that passes the two above statements are 30 or above.
print("Its hot", "open the air conditioner")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.