-1

I have an assignment to write a python program that asks the user to input a single character and then checks if it is an alphabetical digit (not special characters) or a digit or neither with neither and prints what it is.

I was testing the method below out of curiosity thinking it will return an error or print Invalid input. But lo and behold it actually works perfectly but I have no idea why.

c = input("Enter a character: ")

if 'a' <= c.lower() <= 'z' and len(c) == 1:   # .lower() in case the input is either capital or lowercase
    print('Your character', "'" + c + "'", 'is an alphabetical letter')
elif '0' <= c <= '9' and len(c) == 1:
    print('Your character', "'" + c + "'", 'is a digit')
else:
    print('Invalid input')
Mike Hanna
  • 18
  • 4
  • You're seeing chained comparison (https://stackoverflow.com/a/26502847/51685) and the fact that strings are comparable to each other. – AKX Nov 04 '20 at 09:52
  • It works because the character you put in is between 'a' and 'z' and then probably between 0 and 9, it works, can you specify what you don't understand? – Oliver Hnat Nov 04 '20 at 09:51
  • 2
    Here's the answer why strings are compared and how https://docs.python.org/3/tutorial/datastructures.html#comparing-sequences-and-other-types – Tom Wojcik Nov 04 '20 at 09:53

2 Answers2

1

According to the value comparison docs:

Strings (instances of str) compare lexicographically using the numerical Unicode code points (the result of the built-in function ord()) of their characters.

D Malan
  • 10,272
  • 3
  • 25
  • 50
0

It compares the ASCII value of your character with the ASCII value of 'a' & 'z', same thing about digits since they are in the form of characters.

Rajan
  • 625
  • 7
  • 19