I heard that when you toss a die often enough, you could get the value "one" a million times in a row.
I am a beginner in Python 3 and I tried to write a little program that generates 1 or 2 randomly and counts how often the value "one" has occured successively and how big this count could get.
You can also print out the program run or write it to a file to understand the result.
I would like to know if there are possibilities to improve the code quality by using tricks and mechanisms that Python offers to me or if I can reduce something / make something better in general.
from random import randint
import os.path
iterations = int(input("number of iterations: "))
file_with_details = input("create a log file? (y/n): ")
details = input("printing out details about the program run? (y/n): ")
log_file = "is not existing"
# generate folder and log file for program run information
if file_with_details == "y":
if not os.path.isdir("./logs"):
os.mkdir("./logs")
file_number = 1
file_name = "./logs/log" + str(file_number) + ".txt"
while os.path.isfile(file_name):
file_number += 1
file_name = "./logs/log" + str(file_number) + ".txt"
log_file = open(file_name, "w")
# start of random experiment
biggest_succession = 0
actual_succession = 0
random_number_before = 0
for i in range(iterations):
random_number = randint(1, 2)
if details == "y":
print("generated number:", random_number)
if file_with_details == "y":
log_file.write("generated number:" + str(random_number) + "\n")
if random_number == 1 and random_number_before == 1:
actual_succession += 1
if details == "y":
print("actual succession:", actual_succession)
if file_with_details == "y":
log_file.write("actual_succession:" + str(actual_succession) + "\n")
else:
if actual_succession > biggest_succession:
biggest_succession = actual_succession
if details == "y":
print("biggest succession has changed:", biggest_succession)
if file_with_details == "y":
log_file.write("biggest succession has changed:" + str(biggest_succession) + "\n")
actual_succession = 0
random_number_before = random_number
print("the number one was generated", biggest_succession, "times behind each other")
if file_with_details == "y":
log_file.write("the number one was generated " + str(biggest_succession + 1) + " times behind each other")
log_file.close()