- Characters can be checked and compared in much the same way as numbers, using the same symbols
- Less than (<) and greater than (>) work if you think about the alphabet as going from low (a) to high (z)
- Remember that lowercase and uppercase letters are recognised as different characters by the computer
Symbol | Example | Operation |
---|---|---|
== | if name == “John”: | equal to |
< | if char < “z”: | lower in the alphabet |
<= | if char <= “z”: | less than or equal to in alphabet |
> | if char > “a”: | higher in the alphabet |
>= | if char >= “a”: | greater than or equal to in alphabet |
!= | if char != “a”: | not equal to |
in | if char in string: | is character in string? |
ASCII
Less than (<) and greater than (>) works because the computer assigns all letters a preset numerical value, documented in the ASCII character set
#Use ord() to find the ASCII value of a character
print(ord("A"))
#Use chr() to find the character associated with an ASCII number
print(chr(65))
Tasks
- Type in the code above and check it works
- Modify the program to accept user input
- Save and label your code
Extension Task
You can combine these techniques with an IF statement to check for any allowed alphanumeric character (look at the table and find the lowest, and highest numbers that identify the range of characters you want to accept)