简体   繁体   中英

How can I display the results of a for loop in a user - friendly manner?

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:)

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM