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

2024-06-23 19:01:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我只是在学习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.

Tags: ifthatwithnot语句elsefavoriteboot
3条回答

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

n = 'Nike'
p = 'Puma'
a = 'Adidas'
print('What is your favorite boot?')
boot = input()

现在else只与最后一个if语句相关 尝试使用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')

输出:

What is your favorite boot?

Nike
Nike, great choice

如果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')

您在这里创建了三个独立的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”:

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

相关问题 更多 >

    热门问题