简体   繁体   中英

Python printing issue in For loop

I am trying to print a specific message for each item in my list using a for-loop. I am really not sure how to go about it. Thank you!

pizzas = ['cheese', 'veggie', 'marherita']

for pizza in pizzas:

    print(f'{pizza(0)} is was my favorite as a child, \n {pizza(1)} is my favorite as an adult, but \n {pizza(2)} is also great!') # broken line of code

Error Message:

  File "c:/Users/logan/Untitled-2.py", line 5, in <module>
    print(f'{pizza(0)} is was my favorite as a child, \n {pizza(1)} is my favorite as an adult, but \n {pizza(2)} is also great!') # 
broken line of code
TypeError: 'str' object is not callable

What I want to print:

cheese was my favorite as a child,

veggie is my favorite as an adult, but

margherita is also great!

I see that you're new to Python. A print statement in a for loop does not have something in it that makes it print something depending on the text selected. You will need to use if statements.

pizzas = ['cheese', 'veggie', 'margherita']

for pizza in pizzas:
    if pizza == "cheese":
        print(pizza + " was my favorite as a child,")
    elif pizza == "veggie":
        print(pizza + " is my favorite as an adult, but")
    elif pizza == "margherita":
        print(pizza + " is also great!")

By the way, in your print statement, there is no need of a for loop. You are trying to print it by referring to the pizza flavour in the list itself, not referring it in the actual for loop variable.

Another way to stop the loop from printing for each item in the list, while using a for-loop, is by using a break: I need to do this is a for-loop per the book I'm learning from, Python Crash Course.

pizzas = ['cheese', 'veggie', 'margherita']


for pizza in pizzas:

    print(f'my favorite pizzas are: {pizzas}')
    break

This will print:

my favorite pizzas are: ['cheese', 'veggie', 'margherita']

or by removing the print for my favorite pizzas from the for-loop, as follows:

pizzas = ['cheese', 'veggie', 'margherita']


print(f'my favorite pizzas are:')


for pizza in pizzas:

    print(pizza)

This will print:

my favorite pizzas are:

cheese
veggie
margherita

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