Error: not all Arguments converted During string formatting

Asked

Viewed 423 times

2

I’m taking the Python 3 course on video and I’m in exercise n° 82. Even though my code and the teacher’s code are almost identical, mine is making the mistake not all Arguments converted During string formatting. My code is this:

a = list()
b = list()
c = list()
while True:
    a.append(input('Digite um número:'))
    r = str(input('Deseja continuar: [S/N]:')).upper().strip()
    if r == 'N':
        break
for i, v in enumerate(a):
    print(v)
    print(i)
    if v % 2 == 0:
        b.append(v)
    elif v % 2 != 0:
        c.append(v)
print(f'A lista de números digitados é: {a}')
print(f'Desses números, {len(b)} deles são pares. Estes são {b}')
print(f'Desses números, {len(c)} deles são impares. Estes são {c}')

Pycharm makes no mistake. Where did I go wrong? By the way, my version of Python is 3.6 And the error is happening on line 12:if v % 2 == 0:

  • Just one detail: the result of numero % 2, for any number, it will always be 0 or 1. Then the elif is unnecessary and can be exchanged for a else: if v % 2 == 0: b.append(v) else: c.append(v)

1 answer

0


This error occurs because you are trying to use the operator % in a string:

if v % 2 == 0:

When using the function input to take the data, this function returns a string, even the user typing a number.

You can fix this by converting the value the user types to an integer using the function int in the following part of the code:

a.append(int(input('Digite um número:')))

As the function input already returns a string, you can remove the function str at the time when it requests the S/N to the user:

r = input('Deseja continuar: [S/N]:').upper().strip()

Your code will then look like this:

a = list()
b = list()
c = list()

while True:
    a.append(int(input('Digite um número:')))
    r = input('Deseja continuar: [S/N]:').upper().strip()
    if r == 'N':
        break

for i, v in enumerate(a):
    print(v)
    print(i)
    if v % 2 == 0:
        b.append(v)
    elif v % 2 != 0:
        c.append(v)

print(f'A lista de números digitados é: {a}')
print(f'Desses números, {len(b)} deles são pares. Estes são {b}')
print(f'Desses números, {len(c)} deles são impares. Estes são {c}')

See online: https://repl.it/repls/JumpyDishonestLifecycle


Documentations:

https://docs.python.org/3/library/functions.html#input

https://docs.python.org/3/library/functions.html#int

Browser other questions tagged

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