Lily C.

asked • 01/13/21

Python While loops and For loops

Is there a way for me to use for loops with not equal marks like you can you with while loops? For example, how can I convert while num!=0 to for loop


I created a code for converting binary to decimal using a while loop and I wanted to know how I could change it to using a for loop instead. I also need help displaying the value of each one bit(for example: 1 is 16; 1 is 8; 1 is 4 *or from right to left*)


I inserted my code below:


n1 = int(input("Enter binary number: "))


def binToDec(num):

sum = 0

i = 0

while num!=0:

remainder = num % 10

sum = sum + remainder * pow(2,i)

num = int(num/10)

i = i+1

print('Decimal Number : ', sum)


binToDec(n1)

//end


the output is:

Enter binary number: 1111

Decimal Number : 15


1 Expert Answer

By:

Patrick B. answered • 01/13/21

Tutor
4.7 (31)

Math and computer tutor/teacher

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.