我是学习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。 –