-1

I've got the following code:

fn = input("Choose a function(1, 2, 3, 4, 5, other(quit)): ");
while (not(fn > '5' or fn < '1')):
    print("hello world");

This works, most of the time. For example, if I input 54 or some crazy number, it will never print "hello world".
However, when I enter 45, it does enter the loop.
Why is this?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Human Cyborg Relations
  • 1,202
  • 5
  • 27
  • 52
  • Because they are compared lexicographically... `'4'` is lexicographically smaller than `'5'` and greater than `'1'`, thus the expression evaluates to `False`. `not False` is `True` thus it goes into the loop. – Andrew Li Oct 29 '16 at 23:24
  • In other words - when using the `>` or `<` operators on string (text) it compares their order relative to each other, alphabetically. Well not quite alphabetically, but by the place of the symbols from that string in the encoding table. – Alex Oct 29 '16 at 23:25

3 Answers3

0

Python doesn't end statements with semi-colons

Neither while or not do not require parenthesis.

And you need to compare numbers, not strings. But wait, input returns a string in Python3, so you need to int() that as well.

fn = input("Choose a function(1, 2, 3, 4, 5, other(quit)): ")
if fn == 'quit':
    # break out of this choose a function prompt
else: 
    while int(fn) in range(1, 5 + 1): # +1 because non-inclusive ranges
       print("hello world")

And, this will be an infinite while loop for a valid input, so just be prepared for that

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
-1

You're using strings instead of numbers ('5', '1'). String comparison is done by the single character, and the character '4' in '45' counts as less than the character '5'.

>>> ord('4')
52
>>> ord('5')
53
Roberto
  • 2,696
  • 18
  • 31
-1

You could fix it by writing:

fn = input("Choose a function(1, 2, 3, 4, 5, other(quit)): ");
while str(fn) + ',' in '1,2,3,4,5,':
    print("hello world");
Progg
  • 85
  • 8