how do I execute without taking the int from the code?

Asked

Viewed 60 times

-2

codigo = input('Digite um numero: ')

for i in codigo:
    print(f'{i} |', end='')

generates this result, ok

> Digite um numero: 21853
> 2 |1 |8 |5 |3 |
> Process finished with exit code 0

below add int it generates error, as it would solve without taking the int from the code

codigo = int(input('Digite um numero: '))

for i in codigo:
    print(f'{i} |', end='')

generates this result, error!

for i in codigo:
TypeError: 'int' object is not iterable
  • You can edit the question to make the corrections.

  • 1

    If one of the answers below solved your problem and there was no doubt left, choose the one you liked the most and mark it as correct/accepted by clicking on the " " that is next to it, which also marks your question as solved. If you still have any questions or would like further clarification, feel free to comment.

  • 1

    What would be the reason to use int()? From your code it simply looks like the int there is not needed, you could convert it to int() after for(), but instead it turns out that it converts a string to int and then has to convert it back to str. Can you explain the problem better Ricardo? cc @Lucas

1 answer

1


Ever tried to make a conversão (cast) for str?

Here is an example of how it can be implemented:

codigo = int(input('Digite um numero: '))

for i in str(codigo):
    print(f'{i} |', end='')

Note that it is now necessary to treat if the user type a non-numeric value (for example the letter to) then it will be necessary to treat this case. In order to avoid error:

Traceback (Most recent call last): File "", line 1, in Valueerror: invalid literal for int() with base 10: 'a'

Python command is used try/except to do this operation.

Here is an example of how to treat this flow:

while True:
    try:
        codigo = int(input("Digite um numero: "))
        for i in str(codigo):
            print(f'{i} |', end='')
        break
    except ValueError:
        print("Pff! Não foi possível representar o valor lido como número. Tente novamente...")

Browser other questions tagged

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