-2

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'.

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?

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
Abhi
  • 7
  • 2
  • Why do you write it in one line? – fahadh4ilyas May 23 '18 at 06:07
  • 1
    you are missing the `:`. it should be `if x == 'Banana':` (the same goes for `else:`). and do not compare strings with `is`. as a beginner you will get surprising results ([string interning](https://stackoverflow.com/questions/15541404/python-string-interning)). – hiro protagonist May 23 '18 at 06:11

2 Answers2

0

Try this

for x in fruits:
    if x == "Banana":
        print('Here is %s'%x)
        break
    print(x)
fahadh4ilyas
  • 450
  • 2
  • 13
0

Put Colon after at the end of if and 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)
Drizzy
  • 138
  • 8
  • ...as i mentioned: comparing strings with `is` is usually not a good idea! and please fix the string formatting in the `print` statement. – hiro protagonist May 23 '18 at 08:13