r/pythonhelp • u/[deleted] • 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 00100001Current 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
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.