for循环与字符串列表,如果condiiton不工作

时间:2022-02-13 10:59:49

I am new to programming and python.I've written a simple python program that iterates through a list of fruits and stops when it encounters the fruit 'Banana'.

我是编程和python的新手。我编写了一个简单的python程序,它遍历一个水果列表并在遇到水果'Banana'时停止。

fruits = ['Orange', 'Mango', 'Grapes', 'Guava','Blue Berry', 'Litchie', 'Banana',
          'Cherry', 'Strawberries', 'Pears', 'Apple']

for x in fruits:
    if x is "Banana"
        print('Here is %s',x)
        break
    else
        print(x)

The above script fails with invalid syntax. I tried different options such as x == 'Banana': but the same error message is displayed. What's wrong here?

上述脚本失败,语法无效。我尝试了不同的选项,例如x =='Banana':但是会显示相同的错误消息。这有什么不对?

2 个解决方案

#1


0  

Put Colon after at the end of if and else.

在if和else之后放置冒号。

fruits = ['Orange', 'Mango', 'Grapes', 'Guava','Blue Berry', 'Litchie', 'Banana',
      'Cherry', 'Strawberries', 'Pears', 'Apple']

for x in fruits:
if x is "Banana":
    print('Here is %s',x)
    break
else:
    print(x)

#2


0  

Try this

for x in fruits:
    if x == "Banana":
        print('Here is %s'%x)
        break
    print(x)

#1


0  

Put Colon after at the end of if and else.

在if和else之后放置冒号。

fruits = ['Orange', 'Mango', 'Grapes', 'Guava','Blue Berry', 'Litchie', 'Banana',
      'Cherry', 'Strawberries', 'Pears', 'Apple']

for x in fruits:
if x is "Banana":
    print('Here is %s',x)
    break
else:
    print(x)

#2


0  

Try this

for x in fruits:
    if x == "Banana":
        print('Here is %s'%x)
        break
    print(x)