while True:
x = (input("Enter character or ASCII value for conversion or q to quit: "))
if x == "q":
break
if len(x) > 1 and not x.isdigit():
print("not applicable: fail")
break
elif x.isdigit():
print(chr(int(x)))
else:
print(ord(x))
So you are relatively new to programming, like me, and you have got a few concepts under your belt. Probably you are bored of print(“Hello world!”). You are looking for a basic program to write. Something that is actually relevant to IT.
While I was going over notes from the Programming Expert course, I was messing around with a while loop and ASCII conversion functions ord and chr. If you are not familiar with ASCII then just know that it is a numerical value given to each symbol/character we use in computing. So a = 97, A = 65, # = 35 and so on.
The Crux of the Matter
print(ord(x))
will print the ASCII value of the variable x
print(chr(x))
will print the character of the variable x
These are the active ingredients of this little program. Let’s look at the rest of it:
Line 1: Creates an infinite loop. In which we will put our block of code.
Line 2: Asks the user to input a number or character and puts this in the variable x. It also gives the user the option to quit the infinite loop.
Line 3+4: Enables the quit feature.
Line 5+6+7: Input validation. The ord and char functions are a bit fussy and will only take an integer or a single character respectively. So this if statement effectively says that if the length of the input is greater than one character and is not a digit then it’s no good and the user is told as much. (Note that even if a float is entered then this will be more than one character and will fail too.)
Line 8/9: The next part of the if statement is an elif which asks if x is a digit then print the character associated with the value. It has been converted from the string the user entered, to an integer which the function can read.
Line 10/11: Anything else must be a single character and is then converted to a value.
And there you have it. Admittedly this is a simple converter which only accepts one input at a time and can’t deal with [DELETE] for example but it’s still pretty neat. I am finding it’s important to gain confidence at coding by experimenting with small programs.
Leave a Reply