简体   繁体   中英

Python not running my program without any error

I need to create a program that will convert Base 10 numbers in Base 2.

Next is the code, it can not run as expected even if it has no error:

E = input('Please enter a number') 
Eint= int(E)
for N in range(100,0):
    while 2**N > Eint:
         N = N-1 
         print(0)  
    if B**N <= Eint:
        Eint = Eint - 2**N 
        print(1)   
    Print('finished')   

When I'm running it it will ask me the number but that's all, thank you for your help guys.

在此处输入图片说明

From a quick inspection, range(100,0) , B , and Print() are three culprits here! If you want to pass through numbers from 0 to 99, then range(100) is what you need. Now, what is B? Print should be written in lower case: print .

After we fix these syntax errors, let us try to revisit the program and understand what it is supposed to do. Have fun :-)

EDIT to fix the code in the question:

E = input('Please enter a number: ') 
Eint = int(E)
for N in range(8,-1,-1):
    if 2**N > Eint:
        print(0, end='')
    else:
        Eint = Eint - 2**N 
        print(1, end='')

print()
print('finished')

Please note that Python is a language that uses indentations to denote code blocks. This code will convert a decimal to binary. Now, note that the range start of 8 gives you a hint about the upper bound of the number that the code can translate. Therefore, an if condition must be added after the second statement to ensure we are not attempting to convert a number that is too large. Enjoy!

If it helps check my solution too. Because I guess you don't want to see the result on separate lines, so I create a list for you to see the result in one line.

E = int(input('Please enter a number\n'))
Eint = E
base_two=[]
while E > 0:
    a = int(float(E%2))
    base_two.append(a)
    E = (E-a)/2
base_two.append(0)
string = ""
for j in base_two[::-1]:
    string = string+str(j)
print("Binary for", Eint, "is", string)
print('finished')

I was late a little bit :)

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