Monte Carlo Simulation for a Weather Application
importrandom
# In order to execute a set of N simulations (as soon as the user wants to run a simulation),
# ... we will use a while-loop
run_simulator =True
while run_simulator:
# Now, we will simulate days and days until a condition is met, so another while-loop is required
print("Welcome to the weather simulator!")
stop_days =False
day =1
inches =0
no_rain_days =0
rain_days =0
consecutive_rain =0
consecutive_norain =0
whilenot stop_days:
# Now, check the percentages
N =random.randint(1,100)
# If 1 <= N <= 5, 5%
if N <=5: # Heavy rain
inches +=3
rain_days +=1
consecutive_rain +=1
consecutive_norain =0
print("Heavy rain! 3 inches fell.")
elif N <=10:
inches +=1
rain_days +=1
consecutive_rain +=1
consecutive_norain =0
print("Light rain. 1 inch fell.")
else:
print("No rain today...")
no_rain_days +=1
consecutive_rain =0
consecutive_norain +=1
# Now check for stopping conditions
if inches >=8: # Total cumulative rainfall
print("Total rainfall reached at least 8 inches, so the soil moist enough to plant!")
stop_days =True
if consecutive_rain ==2:
print("2 consecutive days of rain... it is now safe to plant crops.")
stop_days =True
if consecutive_norain ==14:
print("14 consecutive days of no rain... It looks like a drought...")
stop_days =True
# Ask user for a valid option between yes no
invalid_option =True
while invalid_option:
option =input("Would you like to run the simulation again (yes/no)? ")
option =option.lower()
if option in ['yes','no']:
invalid_option =False
if option =='no':
run_simulator =False
else:
print("Invalid option. Please enter (yes/no).")