What is the difference between these forms of command execution?

Asked

Viewed 145 times

1

These commands in Python:

lista = eval('[' + input("Digite sua lista: ") + ']')

And this:

lista = input("Digite sua lista: ")

And this:

lista = [int(x) for x in input().strip()]

Why the latter gives the error below?

Valueerror: invalid literal for int() with base 10: ','

1 answer

1


lista = eval('[' + input("Digite sua lista: ") + ']')

Do not use eval() if you do not deeply master language and computing. In essence you do not need it.

lista = input("Digite sua lista: ")

Are you asking to type something and store in the variable as a string, not a list.

lista = [int(x) for x in input().strip()]

Is creating a list (a array dynamically sized). This is called expression comprehension, so this loop is executed and the result of every loop execution, i.e., all steps, are saved in the list.

In this case is catching the string generated in data typing (input()) and separating the words (strip()) and in each data is transformed into an integer (int()), expecting the text typed separated by spaces to be numbers.

Valueerror: invalid literal for int() with base 10: ','

A text has been typed that cannot be converted to a number. I don’t like this strategy, but in Python it is customary to capture exception when this occurs to correct.

Browser other questions tagged

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