r/pythonhelp • • Oct 06 '21

Problem nested loop in a personal challenge project (my code).

I am having a problem with my nested loop in this code I am playing with. This is not for class, but a personal quest. The goal is to random generate sets of 8 bits based on how many characters (ASCII) they want and then save to file output to "random.txt". The problem area begins with the "else:" statement and ends before "finally:", The problem is that it executes 8 iterations of the inner loop and once of the outer loop so I always get 8 bits.

Example of desired output of random.txt:

01001000 01100101 01101100 01101100 01101111 00100000 01010010 01100101 01100100 01100100 01101001 01110100 00100001

Current code:

import random

def generate():
    random_num = random.randint(0,1)
    return random_num

def main():
    try:
        output = open("random.txt", "w")

        num_of_num = int(input("How many characters should the file hold?"))

    except Exception as PotentialError:
           print("An error has occured.", PotentialError)

    else:
        for num_count in range(0, num_of_num + 1):
            for bits in range (1, 7 + 1):
                random_num = generate()
                output.write(str(random_num))
            return bits
        return num_count

        print(num_of_num, "numbers have been written to the file random.txt")

    finally:
            output.close()
main()
2 Upvotes

8 comments sorted by

View all comments

2

u/[deleted] Oct 06 '21

After your inner loop you return the number of iterations, which immediately exits the for loop. You also return after the outer for loop before you hit your print statement.

1

u/[deleted] Oct 06 '21

Took the returns out and was successful. What is the purpose of the return?

3

u/carcigenicate Oct 06 '21

To leave the function and at the same time return some data back to whoever called the function.

1

u/[deleted] Oct 06 '21

Why would adding a return prevent the execution of further iterations, does that force the loop to exit regardless??

2

u/carcigenicate Oct 06 '21

return causes the function to exit regardless of anything else like loops that it may be in. You could use yield to yield multiple values, but I wouldn't use that until you're more familiar with functions and returning.

1

u/[deleted] Oct 06 '21

Thanks for your mentorship and assistance! This is the furthest I have gotten with a modern programming/scripting language. Legit file I/O and functions.