我是学习python的新手,我喜欢尝试所以我在(python 3.4.3)shell中编写了这些if
和else
语句,但我不知道在哪里写导致所有4个值的最终else语句都是错误的。
请注意:
a=False
b=False
c=False
d=False
答案 0 :(得分:1)
如果没有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
的原因。好吧,这仅仅是因为你试图从一个2
开始else``statements
if
。
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
。
答案 1 :(得分:0)
您的代码中存在一些逻辑错误。例如,即使a
和/或{{1},任何时候False
b
且c
都为真,它将达到“b为假,其余为真”是d
。要做到这一点,无论您为False
,d
和a
找到什么,都需要将所有变量一直测试到b
。如果你这样做,你最终会得到c
级别的16个'叶子',你将在这些叶子中写下所有d
个语句。下面是您添加了额外分支的代码版本。 “all false”部分最终出现在else / else / else / else分支处,应该是。
print
关于您的错误 - 您的代码如下,无效:
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")