When to return in function in Python?

Question:

I am creating a program that will accept user input and from that, generate a name and a backstory. What I am having trouble with is printing the indefinite articles "a" or "an," depending on the backstory string’s first letter.

# Backstory
a = "alchemist searching for a missing item"
b = "berry picker who dabbles in meteorology"
c = "camera assistant fascinated by alien civilization"
# this continues for all letters of the alphabet, with each string beginning with its corresponding variable name.

character = (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z)

def indefinite_article():
    for index in character:
        if index in (a, e, i, o, u):
            return("An ")
        else:
            return("A ")

What I would like to happen: if a letter from character is a vowel, the string "An " will print. If a letter from character is a consonant, the string "A " will print.

However, whether vowel or consonant, indefinite_article() prints "An ".

I am using a function because I would like to print the result of indefinite_article() into a string later on:

for char_index in character:
    if char_index[0] == first_name.lower()[0]:
       print("nnCHARACTER PROFILE: " + indefinite_article() + char_index)

Note: first_name is a variable with an input assigned to it.

Where should I place my return statement(s) so that the correct indefinite article is printed depending on the first letter of the backstory string?

Asked By: Lugnut

||

Answers:

I see from your update that you want to loop over the character tuple and provide the indefinite article for the first word in each backstory.

Your calling code does the loop, so the function only needs to concern itself with one item and just the first letter of the item.

So, your calling code could be modified like this:

for char_index in character:
    first_letter = char_index[0]
    if first_letter == first_name.lower()[0]:
       print("nnCHARACTER PROFILE: " + indefinite_article(first_letter) + char_index)

and the function should be modified to just test that first letter like this:

def indefinite_article(letter):
    if letter in 'aeiou':
        return 'An '
    else:
        return 'A '
Answered By: quamrana
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.