Hi experts, I'll have to create a python file to store all my function in one file and main program in another, to make

Business, Finance, Economics, Accounting, Operations Management, Computer Science, Electrical Engineering, Mechanical Engineering, Civil Engineering, Chemical Engineering, Algebra, Precalculus, Statistics and Probabilty, Advanced Math, Physics, Chemistry, Biology, Nursing, Psychology, Certifications, Tests, Prep, and more.
Post Reply
answerhappygod
Site Admin
Posts: 899603
Joined: Mon Aug 02, 2021 8:13 am

Hi experts, I'll have to create a python file to store all my function in one file and main program in another, to make

Post by answerhappygod »

Hi experts, I'll have to create a python file to store all myfunction in one file and main program in another, to make my codemuch neater. My main function will only include the menuoptions(Where I could select options) , functions andlist.
Example:
while True:
print(menu)
if choice == "1":
cross_vel()
elif choice == "2":
mean_vehicle()
elif choice == "3":
de_vehicle()
elif choice == "4":
cross_plot()
elif choice == "0":
break
else:
print("Wrong Choice")
full code:
# import plotting libraryimport matplotlib.pyplot as plt
# function to prompt the user to select the citydef citySelection(cities): # loop to validate the user input while True: # interate through all the city namesin city list and print for i in range(len(cities)): print(f"{i+1}.{cities}") # try exception to handle user inputdata type and slection validity try: # prompt user to enterhis choice city_choice =int(input("Select city: ")) # if selection is out ofthe options then raise exception if city_choice < 1 orcity_choice > len(cities): raiseValueError break # if all correctthen break the loop # print error message when exceptionoccurs except ValueError: print("Wrongchoice") # return index of selected city in city list return city_choice-1
def main(): # text for options options = """\nMenu options 1. The number of vehicles crossings by city in2016. 2. Mean of the vehicles crossing and years more thanmean in the period 2012 to 2019 3. Years and vehicles for which no.of vehiclesdecreased by at least 4% over previous year 4. Plots 0. Quit"""
# file name fileName = "crossing_data.csv" # open file, read file and close the file with open(fileName, 'r') as f: txt = f.read()
# split the text in the file into list oflines lines_list = txt.split("\n") # seperate list of years from above list oflines years = lines_list[0].split(",") # convert years from string to integer years = [int(i) for i in years[1:]]
# declare list for storing 2D data of vehiclescrossing list_2d = [] # declare list to store the cities name cities = []
# iterate through all the lines in list oflines for linne in lines_list[1:]: # split line into list words_list = linne.split(",") # add index 0 word to city list cities.append(words_list[0]) # add list of remaining part to 2D listafter converting string to integer listt = [int(i) for i inwords_list[1:]] list_2d.append(listt)
# loop for main menu options while True: # print menu options print(options) # prompt user to enter his choice choice = input("Please select youroption: ") # if choice 1 is selected if choice == '1': # initialise totalvehicles variable with 0 totalVehicles = 0 print("\nNumber ofvehicles crossings by city in 2016") print(f"City\tNo. ofvehicles crossing") # iterate through all the2D list for 2016 year (index is 6) data for all cities for i inrange(len(list_2d)): # printdetails for current city print(f"{cities}\t{list_2d[6]}") # updatetotal totalVehicles += list_2d[6] # print no. of totalvehicles crossings in 2016 from all cities print(f"\nTotal Vehiclescrossings: {totalVehicles}")
# whether option 2 is selected elif choice == '2': # prompt user to selectcity useing cityselection function city_index =citySelection(cities) # print selectedcity print(f"Selected city: {cities[city_index]}") # calculate mean of no ofvehicles crossings for selected city from 2012 to 2019 mean_vehicles_count =sum(list_2d[city_index][2:])/8 # print mean print(f"The mean ofnumber of vehicle crossings for the 8-year span of 2012 to 2019:{mean_vehicles_count}") print("\nYears andvehicles crossings exceed mean:") print("Year\tNo. ofvehicles") # iterate through all theyears from 2012 to 2019 for selected city for i inrange(2,len(years)): # if no ofvehicles crossing greater than mean calculated iflist_2d[city_index]>mean_vehicles_count: # print the details print(f"{years}\t{list_2d[city_index]}")
# whether option 3 is selected elif choice == '3': # prompt user to selectcity useing cityselection function city_index =citySelection(cities) # print selectedcity print(f"Selected city: {cities[city_index]}") print("\nYears andvehicles crossings, if no. of vehicles decreased by at least 4%over previous year:") print("Year\nNo. ofvehicles") # iterate through all theyears from 2011 to 2019 for selected city for i inrange(1,len(years)): # ifcurrent year no of vehicles crossings decreased atleast by 4% overprevious year (100-4)/100 = 96/100 iflist_2d[city_index] <(list_2d[city_index][i-1]*96/100): # print the details print(f"{years}\t{list_2d[city_index]}")
# whether option 4 is selected elif choice == '4': # a. Line plot for Numberof vehicles crossings from Anarcotes+Frontier, Boundary vs Year # list for Anarcotes +Frontier no. of vehicles year wise anarcos_front = [] # sum of Anarcotes +Frontier no. of vehicles year wise for i inrange(len(years)): anarcos_front.append(list_2d[0][i] + list_2d[3][i]) # list for Boundary no.of vehicles year wise boundry =list_2d[1] # set plot size f =plt.figure(figsize=[15,8]) # plot for Anarcotes +Frontier plt.plot(years,anarcos_front,label = "Anarcotes + Frontier") # plot for Boundary plt.plot(years,boundry,label = "Boundary") # set x, y labels, titleand legends plt.xlabel('Years') plt.ylabel('No. ofvehicles crossings') plt.legend() plt.grid('on') plt.title("Line plot forNumber of vehicles crossings from Anarcotes+Frontier, Boundary vsYear") #show plot plt.show()
# b.Line plot forNumber of vehicles crossings from Danville, Laurier vs Year # list of no. of vehiclesyear wise for Danville danville =list_2d[2] # list of no. of vehiclesyear wise for Laurier laurier =list_2d[4] # set plot size f =plt.figure(figsize=[15,8]) # plot for Danville plt.plot(years,danville,label = "Danville") # plot for Laurier plt.plot(years,laurier,label = "Laurier") # set x, y labels, titleand legends plt.xlabel('Years') plt.ylabel('No. ofvehicles crossings') plt.grid('on') plt.legend() plt.title("Line plot forNumber of vehicles crossings from Danville, Laurier vs Year") # show plot plt.show()
# if choice is 0 then exitloop elif choice == '0': break # print error for any otherchoice else: print("Wrongchoice.") # print break line print("-"*100)
if __name__ == "__main__": main()
This is my CSV file used:
City,2010,2011,2012,2013,2014,2015,2016,2017,2018,2019Anacortes,29057,30979,31746,32964,31738,31010,31158,28736,26821,28260Boundary,65048,72107,62209,64351,57882,39127,33337,31632,31907,29657Danville,54919,63034,60563,58634,52971,42634,41345,39437,36800,33984Frontier,42048,46313,46377,50835,49743,41148,41365,39102,42527,42610Laurier,54251,52889,54353,55951,61454,57259,61141,47323,43666,44069PortAngeles,57978,56881,58107,107629,57965,59485,60480,63894,65644,64884
Join a community of subject matter experts. Register for FREE to view solutions, replies, and use search function. Request answer by replying!
Post Reply