user6882757
user6882757

Reputation:

Why do I get "ValueError: invalid literal for int() with base 10:" from user input?

n = int(input())
markesheet = [[ int(input()).split()] for _ in range(n)]
print (markesheet)

The user has to enter n = 2, then for markesheet, the user has to enter 2 numbers 22 33.

The desired output is [22,33].

I am getting error:

ValueError: invalid literal for int() with base 10:

Upvotes: 0

Views: 481

Answers (2)

T.A.
T.A.

Reputation: 118

Let's think about the order in which things are happening here:

  • input() gets the string that the user types in
  • int() tries to take that string type object and turn it into an int type object. (gives ValueError because '22 33' doesn't make sense as a integer, it's two separate numbers)
  • .split() doesn't make sense and isn't defined for an int type

Instead, you probably want this:

  • get a string from input()
  • split() that string into a list of smaller strings
  • turn each string into an int

The code for that looks like the following:

markesheet = [ int(_) for _ in input().split() ]

Upvotes: 2

Luke Zhong
Luke Zhong

Reputation: 11

The problem is that when the user enters 22 23, the function input() will try to interpret the entire string 22 23 as an integer. But apparently, 22 23 is not a valid integer, so you get that error.

Therefore, you need to modify how markesheet is constructed:

n = int(input())
markesheet = [int(s) for s in input().split()[:n]]
print(markesheet)

Upvotes: 1

Related Questions