Program that uses input().split(" ") and doesn't run on Python 3.5.1

Question:

I have to do several exercises in Python where the input values ​​must be on the same line and they indicated the input().split(" ") , but the program doesn't run, it gives an error. Ex.:

C, Q = input().split(" ")
C = int(C)
Q = int(Q)

if(C==1):
    T=4.00
elif(C==2):
    T=4.50
elif(C==3):
    T=5.00
elif(C==4):
    T=2.00
elif(C==5):
     T=1.50
print("Total: R$ %.2f"%(T*Q))
print

The error that gives:

Traceback (most recent call last):
File "C:/Users/ILDA/Desktop/lanche.py", line 1, in
C, Q = input().split(" ")
ValueError: not enough values ​​to unpack (expected 2, got 1)

Answer:

This is happening because you are trying to unpacking a list (in code C, Q = input().split(' ') ) but in your unpacking you are expecting 2 values ​​or more ("C, Q"), but I believe you should only be passing one word on the command line (example "foo"), so it will raise this exception. See how unpacking works:

>>> x, y = [1, 2]

>>> x, y
(1, 2)

>>> x, y = [1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 1 value to unpack
need more than 1 value to unpack

The relationship with the number of words is because the split(" ") code will return a list of strings from a given string, for example:

>>> "foo bar".split(" ")
['foo', 'bar']

>>> "foo".split(" ")
['foo']

In short, the code works but is unsure of how it was made.

Scroll to Top