如何阻止Python if语句与else语句一起打印?

如何阻止Python if语句与else语句一起打印?,python,if-statement,Python,If Statement,我刚刚学习python,很难理解为什么if输入会触发else语句。我肯定我遗漏了一些基本的东西,但我希望有人能看看!本质上,当我输入一个变量时,它将else语句拖入其中。我附上代码,谢谢你看 n = 'Nike' p = 'Puma' a = 'Adidas' boot = input('What is your favorite boot?') if boot == n: print('Nike, great choice') if boot == a: print('Adidas

我刚刚学习python,很难理解为什么if输入会触发else语句。我肯定我遗漏了一些基本的东西,但我希望有人能看看!本质上,当我输入一个变量时,它将else语句拖入其中。我附上代码,谢谢你看

n = 'Nike'
p = 'Puma'
a = 'Adidas'

boot = input('What is your favorite boot?')

if boot == n:
  print('Nike, great choice')
if boot == a:
  print('Adidas, not my favorite')
if boot == p:
  print('Not sure about Puma')
else:
  print('I am not familiar with that brand')
在输入打印上键入
Nike

Nike, great choice.
I'm not familiar with that brand.

那么,发生了什么。G如果
boot
等于
n
?执行从上到下,并执行所有测试:

if boot == n:
  print('Nike, great choice')
boot==n
。印刷品

if boot == a:
  print('Adidas, not my favorite')
boot!=a
,未打印任何内容

if boot == p:
  print('Not sure about Puma')
else:
  print('I am not familiar with that brand')
boot!=p
,否则执行部分

为了在匹配时抑制进一步的测试,请使用
elif

if boot == n:
  print('Nike, great choice')
elif boot == a:
  print('Adidas, not my favorite')
elif boot == p:
  print('Not sure about Puma')
else:
  print('I am not familiar with that brand')

当前您的输入是“您最喜欢的靴子是什么?” 我会在输入之前打印提示,就像下面的代码一样

n = 'Nike'
p = 'Puma'
a = 'Adidas'
print('What is your favorite boot?')
boot = input()
现在else只与最后一个if语句绑定 尝试使用Elif语句将它们联系在一起(如下)

输出:

What is your favorite boot?

Nike
Nike, great choice
这里创建了三个独立的if语句。看一下附带的带括号的伪代码

if(boot == n){
   print('Nike, great choice')
}

if (boot == a){
   print('Adidas, not my favorite')
}

if (boot == p){
  print('Not sure about Puma')
}
else{
  print('I am not familiar with that brand')
}
您需要使用“elif”:


请尝试eif,除了第一个If,尝试将剩余的If或else更改为elif并重试。

当您在第一个输入中输入Nike时,它会检查
boot==n
,该选项变为真,并打印“Nike,很棒的选择”。 一切都还不错。
之后,它检查
boot==a
,该值变为false,因此不打印任何内容 之后,它检查
boot==p
,这也是false,因此它进入else块或第三个
if
并打印“我不熟悉该品牌”。 您需要了解的是
elif
语句,因此,如果if语句中的任何一条为真,它将跳过其余语句,而不转到elif或else块的其余部分。 这是正确的代码

n = 'Nike'
p = 'Puma'
a = 'Adidas'

boot = input('What is your favorite boot?')

if boot == n:
  print('Nike, great choice')
elif boot == a:
  print('Adidas, not my favorite')
elif boot == p:
  print('Not sure about Puma')
else:
  print('I am not familiar with that brand')

对中间的两个分支使用
elif
。你一定和我一样发布了。很好的描述。我投了赞成票
if boot == n:
    print('Nike, great choice')
elif boot == a:
   print('Adidas, not my favorite')
else:
   print('I am not familiar with that brand')
n = 'Nike'
p = 'Puma'
a = 'Adidas'

boot = input('What is your favorite boot?')

if boot == n:
  print('Nike, great choice')
elif boot == a:
  print('Adidas, not my favorite')
elif boot == p:
  print('Not sure about Puma')
else:
  print('I am not familiar with that brand')