简体   繁体   中英

How do I print individual sentences from a Python list of sentences?

The code below prints the individual characters within the list instead of printing the sentences themselves. How can I rectify this error?

# Modify this function to return a list of strings as defined above
def list_benefits():
    things = ["More organized code", "More readable code", "Easier code reuse", "Allowing programmers to share and connect code together"]
    for k in things:
        return k
# Modify this function to concatenate to each benefit - " is a benefit of functions!"
def build_sentence(benefit):
    return "%s is a benefit of functions!" % benefit

def name_the_benefits_of_functions():
    list_of_benefits = list_benefits()
    for benefit in list_of_benefits:
        print(build_sentence(benefit))

name_the_benefits_of_functions()

This is my output:

M is a benefit of functions!
o is a benefit of functions!
r is a benefit of functions!
e is a benefit of functions!
  is a benefit of functions!
o is a benefit of functions!
r is a benefit of functions!
g is a benefit of functions!
a is a benefit of functions!
n is a benefit of functions!
i is a benefit of functions!
z is a benefit of functions!
e is a benefit of functions!
d is a benefit of functions!
  is a benefit of functions!
c is a benefit of functions!
o is a benefit of functions!
d is a benefit of functions!
e is a benefit of functions!
>>> 

Here your function list_benefits() will return all individual sentences instead of the whole list, and later you even apply list on the individual sentences. Then modify list_benefits() to return the whole list

# Modify this function to return a list of strings as defined above
def list_benefits():
    things = ["More organized code", "More readable code", "Easier code reuse", "Allowing programmers to share and connect code together"]
    return things
# Modify this function to concatenate to each benefit - " is a benefit of functions!"
def build_sentence(benefit):
    return "%s is a benefit of functions!" % benefit

def name_the_benefits_of_functions():
    list_of_benefits = list_benefits()
    for benefit in list_of_benefits:
        print(build_sentence(benefit))

name_the_benefits_of_functions()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM