Home > Back-end >  PyCharm says there is no errors here, but when i run the code i get ValueError: too many values to u
PyCharm says there is no errors here, but when i run the code i get ValueError: too many values to u

Time:05-02

enter code here

pizzas = ("4 seasons", "Neapolitan", "Pepperoni")

def display_pizzas(types):
    types = list(types)
    print(f"---PIZZAS({len(types)})---")
    for p, x in types, range(0,len(types)):
        print(f"{x}. Pizza {p}")

display_pizzas(pizzas)

im trying this weird syntax, PyCharm sees no errors here, but i get Traceback (most recent call last): File "...\main.py", line 9, in display_pizzas(pizzas) File "...\main.py", line 6, in display_pizzas for p, x in rodzaje, range(0,len(rodzaje)): ValueError: too many values to unpack (expected 2)

CodePudding user response:

Nvm, i already found the solution whitch is:

enter code here

pizzas = ("4 seasons", "Neapolitan", "Pepperoni")

def display_pizzas(types):
    types = list(types)
    print(f"---PIZZAS({len(types)})---")
    for p, x in zip(types, range(0,len(types))):
        print(f"{x}. Pizza {p}")

bye

CodePudding user response:

Maybe your new code works but it's not compiled in a pythonic way.
so I made a little refactor into your code.

  • you don't need to convert tuple types to the list because the tuple is already iterable you can use for loop without converting to list
  • instead of zip function you can user builtin enumerate

this is the whole code

from typing import Iterable

pizzas = ("4 seasons", "Neapolitan", "Pepperoni")
# refactoring Code
def display_pizzas(types: Iterable[str] = None):
    print(f"---PIZZAS({len(types)})---")
    for counter, pizza in enumerate(types):
        print(f"{counter}. Pizza {pizza}")
    
display_pizzas(pizzas)
  • Related