0

I'm trying to recreate a piece of code that I've found on Non-Programmer's Tutorial for Python 2.6-(Page 29):

n = input("Number?")
if n < 0:
    print "The absolute value of", n, "is", -n
else:
    print "The absolute value of", n, "is", n

But the output is different than I spected. If I put as input "-5" I received as output "-5", not "5".I don't know exactly what is the problem with that. This is my piece of code: http://www.codeskulptor.org/#user40_ULW5rdd4VSQXxss.py

Morgan Thrapp
  • 9,748
  • 3
  • 46
  • 67
Jino Michel Aque
  • 513
  • 1
  • 4
  • 16
  • Not sure this should have been marked as a duplicate. A beginner wouldn't be aware that comparing a string and an integer in 2.x would result in odd behavior, not an error. Joac wasn't aware that input() was returning a string, which would be a pre-requisite for checking how to have input() return an integer. /me shrugs. Doesn't matter at this point, I guess. – Kal Zekdor Oct 07 '15 at 16:52

1 Answers1

2

input() returns a string. What you're checking is "-5" < 0, which is False.

Change your input statement to:

n = int(input("Number?"))

And it will work fine.

Kal Zekdor
  • 1,172
  • 2
  • 13
  • 23