好的,所以我有下面顯示的代碼,我在其中向用戶詢問溫度。他們顯然必須回答數字,但如果他們不這樣做,我想開個玩笑。僅當變數屬于某種型別時,如何才能轉換它?
base_temp = input("What is the temperature outside?:" )
if base_temp == str:
print("ok that is not a real temperature.")
print("you stupid liar i HATE you.")
else: temp = int(base_temp)
if temp >= 0 and temp <= 30 :
print("that's nice. Go outside. NOW!")
if temp >= 31 or temp < -10 :
print("okay you can stay inside.")
print("you still need to go outside though, stinky.")
uj5u.com熱心網友回復:
如果給定的字串僅包含數字,則可以使用內置isdigit()函式回傳 true,因此對于 ex:
if base_temp.isdigit():
print("valid temp")
else:
print("invalid temp")
uj5u.com熱心網友回復:
使用例外處理來做到這一點。稍微修改了一下代碼,希望對你有幫助。
它還可以處理負數。
base_temp = input("What is the temperature outside?:" )
try:
temp = int(base_temp)
if temp >= 0 and temp <= 30 :
print("that's nice. Go outside. NOW!")
if temp >= 31 or temp < -10 :
print("okay you can stay inside.")
print("you still need to go outside though, stinky.")
except ValueError:
print("ok that is not a real temperature.")
print("you stupid liar i HATE you.")
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/478356.html
上一篇:如果變數存在,如何保留它
