Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you escape this while loop?

Tags:

python

binary

I'm currently in year 10 (9th grade) and I'm making a program for school that converts binary numbers into decimal numbers and vice versa on python. My coding knowledge isn't great so the program may not be as efficient as it can be so please bear with me.

The code below is checking whether the user input only contains 1's and 0's and that it does not go over the maximum of 8 bits. When I run it and input an invalid number, it works and loops just fine but when I input a valid number, it keeps on going back to the input command and asks me to input something instead of escaping the loop and moving onto the next thing. Please help!

max_8bits = 1
only_bin = 1
while max_8bits > 0 or only_bin > 0:

    b2d_num = input("Enter a binary number:")

    for i in range(len(b2d_num)):
        if b2d_num[i] == "0" or b2d_num[i] == "1":
            if i == len(b2d_num):
                only_bin -= 1
        else:
            print("Only enter a binary number! (0's and 1's)")
            break

    if len(b2d_num) > 8:
        print("Only enter up to 8 bits!")
    elif len(b2d_num) <= 8:
        max_8bits -= 1
like image 731
tysh444 Avatar asked Mar 06 '23 04:03

tysh444


2 Answers

The condition i == len(b2d_num) is never True because the last loop iteration is with i == len(b2d_num) - 1.

E.g.

>>> for i in range(10):
       pass

>>> print(i)
9
like image 141
Michael Butscher Avatar answered Mar 17 '23 01:03

Michael Butscher


The major problem is that you never set your flags to exit the loop. You never get to the point of having an index 8 in a loop that goes 0-7. When you break out of the for loop, you aren't properly managing the values. Suggestions:

  1. Use Booleans, not integers: that's the logic in your head.
  2. Simplify the value checking: use built-in Python functions.

Code:

too_long = True
not_bin = True

while too_long or not_bin:

    b2d_num = input("Enter a binary number:")

    # Check input length
    too_long = len(b2d_num) > 8
    if too_long:
        print("Only enter up to 8 bits!")
        continue

    # Check input content
    not_bin = False

    for i, bit in enumerate(b2d_num):
        not_bin = not_bin or bit not in "01"

    if not_bin:
        print("Only enter a binary number! (0's and 1's)")
like image 23
Prune Avatar answered Mar 17 '23 02:03

Prune