1

I was hoping to create a code to output if a next number entered is Up, Down or Same as the first one. I wanted it to exit when '0' is entered. I also wanted it to print the 'Up', 'Down', or 'Same' result at the end when exited with '0' instead of each time a number is entered.(if user enters: 4, 6, 1, 1, then 0 to exit, the final output will be Up, Down, Same printed.) Please tell me what I am missing, here is what i have so far:

firstNumber = input('Please enter your first number:')

nextNumber=input('Enter the next number(0 to finish)')

while nextNumber !=0:

    if firstNumber<nextNumber:
        print ('Up')

    elif firstNumber>nextNumber:
        print ('Down')

    elif firstNumber==nextNumber:
        print ('Same')

    firstNumber = nextNumber

    nextNumber=input('Enter the next number(0 to finish)')
Kaka Pin
  • 81
  • 1
  • 9

2 Answers2

2

You are comparing string, not numbers.

You should cast your input to integers with int().

here:

try:
    firstNumber = int(input('Please enter your first number:'))
    nextNumber = int(input('Enter the next number(0 to finish)'))
except ValueError:
    # Handle cast error here
    pass
while nextNumber !=0:
    ...

Note

As blubberdiblub explained:

  • < > compare pointer code of strings, that means "8" < "10" returns False while 8 < 10 returns True
Morreski
  • 302
  • 1
  • 5
  • 1
    Actually, `<` and `>` will compare strings in code point order (i.e. `'a' < 'b'` -> `True`). But otherwise a nice answer. – blubberdiblub May 04 '17 at 10:31
  • You are right, just tested it. I always thought otherwise. – Morreski May 04 '17 at 10:33
  • You can still point out that for numbers in strings `"8" < "10"` would result in `False` while `8 < 10` (i. e. numbers) will result in `True`. So in essence it was a fair point to make. – blubberdiblub May 04 '17 at 10:34
0

input

The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.

So use

int(input(...))
itzMEonTV
  • 19,851
  • 4
  • 39
  • 49