[英]Python If elif else
`
is_summer = True
print("Values 1-12 correlate to the months of the year")
while is_summer == True:
_month = int(input("Enter the month of the year: "))
if _month == 4 or 5 or 6 or 7 or 8:
is_summer = int(input("It is summer, what is the temperature?: "))
if is_summer in range(60,101):
print("The squirrels are playing")
else:
print("The squirells are not playing")
elif _month == 1 or 2 or 3 or 9 or 10 or 11 or 12:
is_summer = int(input("It is winter, what is the temperature?: "))
if is_summer in range(60,91):
print("The squirrels are playing")
else:
print("The squirrels are not playing")
`
如果我輸入1,2,3,9,10,11或12,我的代碼將不會進入elif語句。如果語句執行不正確,是否嵌套了我的嵌套語句?還是其他原因?
您的條件語句的工作方式如下,這就是為什么您提供的輸入條件並不總是正確的原因。
>>> month = 4
>>> month == 4 or 5 or 6
True
>>> month = 5
>>> month == 4 or 5 or 6
5
您可以使用in
運算符來檢查_month
是否存在於您使用or
檢查的值列表中。 in
運算符的工作方式如下
month = 1
month in [1,2,3,4,5] # True
month in [2,3,4,5,6] # False
因此,您可以將程序更改為
is_summer = True
print("Values 1-12 correlate to the months of the year")
while is_summer == True:
_month = int(input("Enter the month of the year: "))
if _month in [4,5,6,7,8]:
is_summer = int(input("It is summer, what is the temperature?: "))
if is_summer in range(60,101):
print("The squirrels are playing")
else:
print("The squirells are not playing")
elif _month in [1,2,3,9,10,11,12]:
is_summer = int(input("It is winter, what is the temperature?: "))
if is_summer in range(60,91):
print("The squirrels are playing")
else:
print("The squirrels are not playing")
您的問題在於您的if語句。
if _month == 4 or 5 or 6 or 7 or 8:
這檢查_month == 4,還是5是真實,還是6是真實等。
您想做的是:
if _month == 4 or _month ==5 or _month == 6 or _month == 7 or _month == 8:
或更簡潔
if 4 <= _month <= 8:
對Elif進行相同操作。 盡管如果您知道_month是從1到12,那么實際上它可能只是別的,而不是elif
代碼未按預期執行的原因是,您實際上並未檢查_month
等於每個數字。
if _month == 1 or 2 or 3
與if _month == 1 or _month == 2 or _month == 3
。
認為第一個if (_month == 1) or (2) or (3)
。 _month == 1
為False
,但是2
或3
是非零值,其結果為True
,因此始終采用第一個if
。
您的第一個if
語句基本上是說_month
是4 –很好–還是5或6或7或8將計算為True
。 在Python中的if語句中,正整數將始終取值為True
–
if 1:
print("hello!")
會一直打個hello!
。 您的if
語句應如下所示:
if _month == 4 or _month == 5 or _month == 6 or _month == 7 or _month == 8:
print("hurrah!")
但是,這變得不必要地冗長了–我們可以使用比較運算符(例如小於( >
)和大於( <
)來簡化此操作,如下所示:
if _month < 3 and _month > 9:
print("hurrah!")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.