2

I'm working though a course on Python. The following code is meant to count the vowels in a string. I typed it out as I thought it should be and did not work. I then cut n paste from lecture notes and it did work.

But I cannot see what the difference is! I've commented out my non working expressions. The working expression is below it.

Why does mine not work?

    ## count the number of vowels in string s
s = 'azcbobobegghakl'
vowelcount = 0
for char in s:
    ## if char == 'a' or char = 'e' or char == 'i' or char == 'o' \
       ## or char == 'u':

    if char == 'a' or char == 'e' or char == 'i' \
       or char == 'o' or char == 'u':

         vowelcount += 1
print "Number of vowels: " + str(vowelcount)

Here is the error message:

%run "/var/folders/cs/31zvz_q925v_z3tmvj09dpyc0000gn/T/tmpCEB9ME.py"
File "/var/folders/cs/31zvz_q925v_z3tmvj09dpyc0000gn/T/tmpCEB9ME.py", line 4
if char == 'a' or char = 'e' or char == 'i' or char == 'o' \
                       ^
SyntaxError: invalid syntax
4
  • 3
    Could you please post your error message? Commented Nov 7, 2013 at 15:03
  • @AnkurAnkan I have added this now Commented Nov 7, 2013 at 15:05
  • 1
    You can see that you are using a single = that means you are doing assignment operation rather than comparision. Commented Nov 7, 2013 at 15:07
  • I got such a big response to this question. Clearly many folk follow the Python tag and it has a strong community behind it. Thanks for the help on my syntax error I'm really glad to be picking this up Commented Nov 7, 2013 at 15:19

3 Answers 3

3

You need to use == for comparison tests:

if char == 'a' or char == 'e' or char == 'i' \
   or char == 'o' or char == 'u':

= is only used for variable assignment.


Or, even better here would be to use in:

if char.lower() in "aeiou":

This code tests whether a lowercase version of char can be found in the string "aeiou". I added .lower() so that your code can handle uppercase vowels.

Sign up to request clarification or add additional context in comments.

Comments

2

You want == instead of =.

I suggest using the following equivalent instead, as it’s more pythonic and more readable:

if char in 'aeiou':
    ...

Comments

1

The ^ is pointing you to the exact error.

or char = 'e' 

must be

or char == 'e' 

1 Comment

Doh! Thank you Lutz Horn. And thanks for the tip on ^. Accepting shortly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.