Home python ValueError: "invalid literal for int () with base 10: '-'

ValueError: “invalid literal for int () with base 10: ‘-‘




Good afternoon!
When trying to enter this piece of code:

for i in input ():
  s = int (i)
  print (s)

found that it only works when you enter positive integers, but an error occurs when you enter a negative number (like -3). The for loop is necessary because in the program, the task is to enter numbers until certain times (these conditions are indicated in the while loop above the piece of code that I have given here).

Then I specifically checked to see if anything had happened to my keyboard and the minus sign. No, everything is fine, this code works:

a = -3
print (int (a))

and outputs -3. Help, please, I am a noob, and I absolutely do not understand why this is so.

Answer 1, authority 100%

See, for example, you enter -3 and input () will have "-3" , then you iterate over "-3" in the loop and the first character in the i variable is "-" , do you understand?

I assume that you enter one or more numbers separated by a space, then the code will be something like this:

for i in input (). split ():
  n = int (i)
  print (n)

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions