I am fairly new to python and I am trying to make a code that converts any character to its binary equivalent. I so far have some code that displays the right result, but you have to read it form the bottom upwards. For example, if you input the character "F", you get the result 0 1 1 0 0 0 1 0 (which should be read 0 1 0 0 0 1 1 0).
letter = input("Please enter any character : ")
ascii_code = (ord(letter))
x = 0
for x in range(0,8):
binary = (ascii_code)%2
ascii_code = (ascii_code)//2
print(binary)
x = 1
Any ideas on how to fix this so it is displayed properly? Thank you :)
CodePudding user response:
If you're asking how to make print not add a newline, use the option end
and set it to an empty string.
print("string", end="")
Then when the loop ends you can print a newline: print()
To get the order reversed you'd want to create a string bit by bit in the loop, then reverse it (reversed()
or result[::-1]
) and print it all at once when the loop exits.
CodePudding user response:
Converting an integer to its binary form can be done within f-string formatting. Something like this:
while len(c := input('Please enter any character: ')) == 1:
print(f'{c} = {ord(c):b}')
Note:
The while loop will terminate if the input is not comprised of exactly 1 character