我是學習python的新手,我喜歡嘗試一些東西,所以我在(python 3.4.3)shell中編寫了這些if
和else
語句,但我不知道在哪裏編寫導致所有4個值的最終else語句假。在哪裏寫最後的(else語句)在這個python代碼?
需要注意的是:
a=False
b=False
c=False
d=False
這是代碼的截圖,因爲代碼插入功能,在這裏總是割我的代碼的很大一部分
我是學習python的新手,我喜歡嘗試一些東西,所以我在(python 3.4.3)shell中編寫了這些if
和else
語句,但我不知道在哪裏編寫導致所有4個值的最終else語句假。在哪裏寫最後的(else語句)在這個python代碼?
需要注意的是:
a=False
b=False
c=False
d=False
這是代碼的截圖,因爲代碼插入功能,在這裏總是割我的代碼的很大一部分
你的代碼有一些邏輯錯誤。例如,即使c
和/或d
是False
,它會達到「b是假的,其餘的是真的」a
是False
和b
是真的。要做到這一點,無論您發現什麼樣的a
,b
和c
,都需要將所有變量全部測試至d
。如果你這樣做,你將在d
級別結束16個'離開',並且你將在這些葉子中寫下所有print
聲明。以下是您的代碼版本,添加了額外的分支。 「all false」部分結束於else/else/else/else分支,它應該在哪裏。
if a:
if b:
if c:
if d:
print("a,b,c,d are true")
else:
print("d is false; a,b,c are true")
else: # c false
# more detail added below
if d:
print("c is false; a,b,d are true")
else:
print("c,d are false; a,b are true")
else: # b false
# more detail added below
if c:
if d:
print("b is false; a,c,d are true")
else:
print("b,d are false; a,c are true")
else: # c false
if d:
print("b,c are false; a,d are true")
else:
print("b,c,d are false; a is true")
else: # a false
if b:
if c:
if d:
print("a is false; b,c,d are true")
else:
print("a,d are false; b,c are true")
else: # c false
# more detail added below
if d:
print("a,c are false; b,d are true")
else:
print("a,c,d are false; b is true")
else: # b false
# more detail added below
if c:
if d:
print("a,b are false; c,d are true")
else:
print("a,b,d are false; c is true")
else: # c false
if d:
print("a,b,c are false; d is true")
else:
print("a,b,c,d are false")
關於你的錯誤 - 你必須像下面這樣,這是無效代碼:
if a:
# something
else:
# something else
else:
print("a,b,c,d are false")
這真的很有用。在你的代碼中,你檢查了這些值的每一種可能性,現在我將嘗試自己編寫它,謝謝親。 – peter
你可以更簡單地做到這一點,而不海量if-else
塊code
。
如果你有4
boolean
variables
:a
,b
,c
和d
那麼你就可以做到以下幾點:
print("a is", a, "b is", b, "c is", c, "and d is", d)
這將print
東西的順序:
a is False b is False c is False and d is False
這裏有一些examples
顯示出一定的情況:
>>> a, b, c, d = True, True, True, True
>>> print("a is", a, "b is", b, "c is", c, "and d is", d)
a is True b is True c is True and d is True
>>> a, b, c, d = True, False, True, False
>>> print("a is", a, "b is", b, "c is", c, "and d is", d)
a is True b is False c is True and d is False
>>> a, b, c, d = False, False, True, True
>>> print("a is", a, "b is", b, "c is", c, "and d is", d)
a is False b is False c is True and d is True
啊,我現在看到。你想知道爲什麼shell
給你一個error
。那麼這只是因爲你正試圖從一個if
做2
else``statements
。
格式用於if
statement
是:
if <condition>:
code...
elif <condition>:
code...
else:
code...
其中elif
和else
是可選。
,你在截圖中使用的syntax
是:
if a:
code...
else:
code...
else:
ERROR
你就不能有2
else
條款從一個if
statement
!也許你的意思是indent
這更進一步匹配不同的statement
,但希望你明白爲什麼Python在這裏拋出error
。
臨提示:請勿在大量的代碼輸入直接進入Python的外殼。將代碼存儲在文件中並在該文件上運行Python。 –