Skip to content
Advertisement

I don’t understand why my loop is missing numbers

Output shows that the numbers 13 is misplaced and 19 is completely missing, I apologize in advance for the inadequateness of the post, my first question here.

 fav_num = {
       'john': [18, 23, 30],
       'serena': [12, 7],
       'bryan': [13],
       'james': [19],
       'ashley': [10, 13],
    }

for name, numbers in fav_num.items():


        if len(numbers) >= 2:
            print(f"{name.title()} favorite numbers are:")

        else:
            print(f"{name.title()} favorite number is {number}.n")

        for number in numbers:

    
            if len(numbers) >= 2:
                print(f"t{number}")

output

Advertisement

Answer

The problem is: you use print(f"{name.title()} favorite number is {number}.n") and number use the number in the previous one.

change to : print(f"{name.title()} favorite number is {numbers[0]}.n")

see below full code

fav_num = {
           'john': [18, 23, 30],
           'serena': [12, 7],
           'bryan': [13],
           'james': [19],
           'ashley': [10, 13],
        }
    
    for name, numbers in fav_num.items():
            if len(numbers) >= 2:
                print(f"{name.title()} favorite numbers are:")
            else:
                print(f"{name.title()} favorite number is {numbers[0]}.n")
            for number in numbers:  
                if len(numbers) >= 2:
                    print(f"t{number}")
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement