Program that uses input(). split(" ") and does not run in Python 3.5.1

Asked

Viewed 4,139 times

3

I have to do several exercises in Python that the input values should be on the same line and indicated me the input().split(" "), but the program does not run, 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 q 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)

2 answers

4

This is happening because you’re trying to make a unpacking of a list (in the code C, Q = input().split(' ')) however, in your unpacking you are expecting 2 values or more ("C, Q"), but I believe that you should be passing only one word in the command line (example "foo"), so you will climb 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 relation with the number of words is because the code split(" ") will return a list of strings from a given string, example:

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

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

In short, the code works but is insecure in the way it was made.

0

Here are four ways I know so you can put a value next to each other:

C, Q = input('Digite algo: ')
lista = [C, Q]

Q = int(Q)
C = int(C)
#Primeira forma - Utilizando a vírgula, bem simples.

print(C,Q,'- primeira forma\n')
#Segunda forma - Transformando as variáveis em str e usando o + para unir, simples também.

print(str(C)+str(Q),'- segunda forma\n')
#Terceira forma - Tirando a quebra de linha do print(), é algo bem legal também e as vezes útil.

print(C,end='')
print(Q,'- terceira forma\n')
#Quarta forma - Pegando os valores de uma lista e unindo(transformando em str, ou int no caso.)

print(''.join(lista),'- quarta forma\n')

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))

I hope I helped. And as already said, the split serves to transform a string into a list, similar to . Join I used above.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.