My Basic Code Not Executing Correctly?

This is the place for queries that don't fit in any of the other categories.

My Basic Code Not Executing Correctly?

Postby learnpython » Sat Oct 12, 2013 2:17 pm

Folks,

I am a new bee and trying to learn python. Below is basic code which I am working on, The problem is that when I enter any word starting with a consonant the code is only returns 'Vowel'. Can someone guide me where I am going wrong - Thanks in advance.

Code: Select all
original = raw_input('Enter a word:')

if len(original) > 0 and original.isalpha():
    word = original.lower()
    first = (word [0])
    if first == "a" or "e" or "i" or "o" or "u":
        print 'vowel'
    else:
        print 'consonant'
else:
    print 'empty'
Last edited by stranac on Sat Oct 12, 2013 3:14 pm, edited 1 time in total.
Reason: Locked. Added code tags.
learnpython
 
Posts: 1
Joined: Sat Oct 12, 2013 2:07 pm

Re: My Basic Code Not Executing Correctly?

Postby stranac » Sat Oct 12, 2013 3:20 pm

Code: Select all
if first == "a" or "e" or "i" or "o" or "u":

This will be True if any of these evaluates as True:
  • first == "a"
  • "e"
  • "i"
  • "o"
  • "u"
As all of 'e', 'i', 'o', and 'u' are non-empty strings, they all evaluate to True, so the condition is always fulfilled.

What you wanted is:
Code: Select all
if first == "a" or first == "e" or first == "i" or first == "o" or first == "u":

Or, better and simpler:
Code: Select all
if first in 'aeiou':
Friendship is magic!

R.I.P. Tracy M. You will be missed.
User avatar
stranac
 
Posts: 888
Joined: Thu Feb 07, 2013 3:42 pm

Re: My Basic Code Not Executing Correctly?

Postby Kebap » Mon Oct 14, 2013 10:09 am

stranac wrote:Or, better and simpler:
Code: Select all
if first in 'aeiou':

This only works for single characters, so here is another good solution which works with other objects as well:
Code: Select all
if mystring in ["a", "e", "iou"]:

By the way, welcome to the forums, and welcome to python! Just maybe think of another username? :mrgreen:
Learn: How To Ask Questions The Smart Way
Join the #python-forum IRC channel on irc.freenode.net and chat with uns directly!
Kebap
 
Posts: 282
Joined: Thu Apr 04, 2013 1:17 pm
Location: Germany, Europe


Return to General Coding Help

Who is online

Users browsing this forum: Google [Bot], mckryall and 5 guests

cron