简体   繁体   中英

Why is my program not taking the first item in the list?

I'm following Crash Course Python Volume 3, and I am doing Chapter 8-12, which is on functions. Here is my code so far:

def sandwich_builder(bread,*items):    
    print(f"What type of bread do you want?")
    bread=input("Type of Bread:")
    print(f"Making your sandwich on {bread} bread with the following items:")
    for item in items:
            print(f"-{item}")

sandwich_builder('turkey','bacon','avocado','cheddar','mayonnaise','tomato','lettuce')

However, my output looks like this:

Making your sandwich on sourdough bread with the following items:
-bacon

-avocado

-cheddar

-mayonnaise

-tomato

-lettuce

Is there a reason why my function won't output the first item in the list? Thanks.

Removing the function "bread", which then set the first item in the list equal to that parameter.

I expected the function to print the first item in the list, but it didn't.

The following line of code sets bread='turkey' and items = ['bacon', 'avocado', 'cheddar','mayonnaise','tomato','lettuce'] .

sandwich_builder('turkey','bacon','avocado','cheddar','mayonnaise','tomato','lettuce')

You then override the value of bread by using bread=input("Type of Bread:") .

To fix it, remove bread as an argument from your function.

def sandwich_builder(*items):    
    print(f"What type of bread do you want?")
    bread=input("Type of Bread:")
    print(f"Making your sandwich on {bread} bread with the following items:")
    for item in items:
            print(f"-{item}")

sandwich_builder('turkey','bacon','avocado','cheddar','mayonnaise','tomato','lettuce')

just remove one unnecessary argument from the function. or you have to pass None to bread.

def sandwich_builder(bread,*items):    
    print(f"What type of bread do you want?")
    bread=input("Type of Bread:")
    print(f"Making your sandwich on {bread} bread with the following items:")
    for item in items:
            print(f"-{item}")

sandwich_builder(None,'turkey','bacon','avocado','cheddar','mayonnaise','tomato','lettuce')

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