Python Forum

Full Version: Functions and program question
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I don't know how to combine the function and the program I've already done the codes just not combining it. If I can help on this it will be great :)

Question as follows:

Write a program that uses a for-loop to ask a user to enter 5 words. The program will then display all the words entered that starts with a vowel only. Your program must use the function start_vowel defined in Question 5. Below is a sample output of the program in Python shell:

Enter a word : Apple
Enter a word : eagle
Enter a word : horse
Enter a word : Hamster
Enter a word : Ostrich
Word that begins with vowels are ['Apple', 'eagle', 'Ostrich']

#The function
def start_vowel(word):
if word[0] == 'A' or 'a' or 'E' or 'e' or 'I' or 'i' or 'O' or 'U' or 'u':
return True
else:
return False

#The program

wordList = []

for word in range(5):

wordList.append(input("Enter a word : "))


print("Word that begins with vowels are " + str(wordList))
Please use python tags when posting so that we can see the indentation in your code. See the BBCode link in my signature below.

Even without indentation I can see you will have a problem with your function. You are using the 'or' operator incorrectly. Please see: https://python-forum.io/Thread-Multiple-...or-keyword
Try this.

[redacted]
Since the function returns True or False you can use if function(argument): like statement looping over the words
I have solved it thanks everyone and heres my code :)

#Function
def start_vowel(word):
    if word[0] == "A" or word[0] == "a" or word[0] == "E" or word[0] == "e" or word[0] == "I"or word[0] == "i" or word[0] == "O" or word[0] == "o" or word[0] == "O" or word[0] == "U" or word[0] == "u":
        return True
    else:
        return False

#Main program
wordList = []
for word in range(5):  
    word = input("Enter a word : ")
    
    if start_vowel(word) == True:
        wordList.append(word)
    else:
        pass
      
print("Word that begins with vowels are " + str(wordList)) 
Improvements line 3 is a little long Wink
#Function
def start_vowel(word):
    if word.startswith(('a','e','i','o','u')):
        return True
    return False

#Main program
wordList = []
for word in range(5):
    word = input("Enter a word : ").lower()
    if start_vowel(word):
        wordList.append(word)
    else:
        pass

print("Word that begins with vowels are {} ".format(wordList))
Oh.. I have learned the startswith method but I didn't know and forgotten how to use it  :(     but what's the .format for in line 16?
(Aug-31-2017, 12:29 PM)Zei Wrote: [ -> ]but what's the .format for in line 16?
It's string formatting PyFormat.
With Python 3.6 did come the newest one f-string.
>>> word_list = ['all', 'act', 'eau']
>>> print(f"Word that begins with vowels are {word_list}")
Word that begins with vowels are ['all', 'act', 'eau']