def run_api(self): self.keyword = helper.text_checker(input("> ")) if self.keyword == 'quit': #allows the user to quit exit() url = self.url[0] + str(self.page) + self.url[1] + self.keyword print(url) headers = {'Authorization': 'Token token="855df50978dc9afd6bf86579913c9f8b"'} response = requests.get(url,headers=headers) data = json.loads(response.text) #turns into a python dictionary. load s is load into a string. load s => loads while True: #loops through each page and prints the results. Allows user to move on to next page. print(f"Page: {self.page}\n") self.print_quotes(data) if data['last_page'] == True: print("This is the last page. Enter 'prev' for the previous page or hit ENTER to enter a new keyword. ") turn = helper.text_checker(input("> ")) if turn == 'prev': self.page -= 1 else: return else: print("Enter 'prev' for the previous page, 'next' to continue to the next page, or 'keyword' to enter a new keyword..") #write exception for page1 new_page = helper.text_checker(input("> "), self.turns) if new_page == 'keyword': return elif new_page == 'prev': if self.page == 1: pass else: self.page -= 1 else: self.page += 1
def name_checker(name): all_names = [] for record in contacts: for attribute in record: if attribute == "Name": all_names.append(record[attribute]) return helper.text_checker(name, all_names)
def update_record(): print("Whose record would you like to update? ") name = name_checker(input("> ")).capitalize() record_idx = find_record_idx_by("Name", name) print("What attribute would you like to update? ") attribute = attribute_checker(input("> ")).capitalize() print("Please enter update: ") update = helper.text_checker(input("> ")).capitalize() contacts[record_idx][ attribute] = update #using the record_idx, we find the proper record w/in list of dictionaries. print(f"{name}'s {attribute} has been updated. ") print(f"{contacts} \n")
def get_city_data(self): print(f"\nAvailable cities are: ", end=' ') i = 0 for city in self.cities: if i == len(self.cities) - 1: print(city) else: print(city + ",", end=' ') i += 1 print("\nWhich city would you like information from? ") self.city = helper.text_checker(input("> "), self.cities, self.ok_formats) response = requests.get('http://' + self.info_urls['city'][0] + self.city + self.info_urls['city'][1] + self.state + self.info_urls['city'][2] + self.country + self.info_urls['city'][3] + self.key) self.city_data = json.loads(response.text)
def populate_states(self): print(f"\nAvailable countries are: ", end=' ') i = 0 for country in self.countries: if i == len(self.countries) - 1: print(country) else: print(country + ",", end=' ') i += 1 print("\nWhich country would you like information from? ") self.country = helper.text_checker(input("> "), self.countries, self.ok_formats) response = requests.get('http://' + self.info_urls['states'][0] + self.country + self.info_urls['states'][1] + self.key) states_dict = json.loads( response.text )['data'] #this gives us a list of dictionaries, where each dictionary is a state for state in states_dict: self.states.append(state['state'])
def get_page_info(data_lines): data_dicts = get_data_dicts(data_lines) data_avg = get_mean(data_dicts) data_var = get_variance(data_dicts, data_avg) data_std = math.sqrt(data_var) day_max = get_day_max(data_dicts) year_avg = get_year_avg(data_dicts) year_max = max(year_avg, key=year_avg.get) print(f"The average rainfall per day is {round(data_avg,2)} inches.") print( f"The variance on the data is {round(data_var,2)} inches with a standard deviation of {round(data_std,2)} inches." ) print( f"The day with the most rain was {day_max[0]} with a total of {day_max[1]} inches." ) print(f"The year with the most rain was {year_max}.") print( "\nWould you like a graph of all the data (total), monthly average (month), or yearly rainfall(year)? " ) graph_type = helper.text_checker(input("> "), ["total", "month", "year"]) if graph_type == "total": days_dict = get_days_dict(data_dicts) show_graph(days_dict) elif graph_type == "month": month_dict = get_month_dict(data_dicts) show_graph(month_dict) elif graph_type == "year": year_dict = get_year_dict(data_dicts) show_graph( year_dict, "yes" ) #this reverses the order, so it goes, farthest back to most recent else: print("ERROR: You should not have gotten here.") frameinfo = getframeinfo(currentframe()) print("line: ", frameinfo.lineno, "exit.") return
def run(self): print( f"Welcome to Trustworthy Bank, {self.name}. Where you can trust us because you don't have a choice. " ) actions = [ "Check balance, Check history, Check interest, Deposit, Withdraw, Quit" ] #this part matches a text input with a function to later call. functions = { "check balance": self.check_balance, "check history": self.print_transactions, "check interest": self.calc_interest, "deposit": self.deposit, "withdraw": self.withdraw, "quit": self.quit } while self.cont == "y": print( "\nWhat would you like to do? (Check balance, Check history, Check interest, Deposit, Withdraw, or 'Quit' to exit.)" ) action = helper.text_checker(input("> "), actions) functions[action]()
def choose_method(): acceptable_inputs = ["Roman", "Time", "Number"] print( "Would you like to get Roman Numerals / Time / Number Text? (Roman/Time/Number)" ) method = helper.text_checker(input("> ").capitalize(), acceptable_inputs) if method == "Roman": print( "Please enter a number to convert to Roman Numerals. (Hail Kaiser)" ) number = helper.digit_checker(input("> "), 3) print(roman_convert(number)) elif method == "Number": print("Please enter number to convert to text: ") number = helper.digit_checker(input("> "), 3) print(convert(number)) elif method == "Time": time_convert() else: print( "You entered an invalid input but somehow got through my checks... NOW WE BOTH HAVE TO QUIT. \nHOPE YOU'RE HAPPY." ) exit()
def populate_cities(self): print(f"\nAvailable states are: ", end=' ') i = 0 for state in self.states: if i == len(self.states) - 1: print(state) else: print(state + ",", end=' ') i += 1 print("\nWhich state would you like information from? ") self.state = helper.text_checker(input("> "), self.states, self.ok_formats) response = requests.get('http://' + self.info_urls['cities'][0] + self.state + self.info_urls['cities'][1] + self.country + self.info_urls['cities'][2] + self.key) cities_dict = json.loads( response.text )['data'] #this gives us a list of dictionaries, where each dictionary is a city for city in cities_dict: if type(city) == str: print(city) exit() self.cities.append(city['city'])
def take_turn(self): inputs = ['w', 'a', 's', 'd'] command = helper.text_checker( input('what is your command? (w/a/s/d): '), inputs) # get the command from the user if command == 'done': return 'n' # exit the game elif command in ['a']: if self.x_pos > 0: self.x_pos -= 1 # move left self.pos = [self.y_pos, self.x_pos] elif command in ['d']: if self.x_pos < self.width - 1: self.x_pos += 1 # move right self.pos = [self.y_pos, self.x_pos] elif command in ['w']: if self.y_pos > 0: self.y_pos -= 1 # move up self.pos = [self.y_pos, self.x_pos] elif command in ['s']: if self.y_pos < self.width - 1: self.y_pos += 1 # move down self.pos = [self.y_pos, self.x_pos] return 'y' #take_turn in lab27 is made to have a checker if the game is still continuing.
"The Air Quality here is Good. Air quality is considered satisfactory, and air pollution poses little or no risk." ) def run_api(self): self.get_data() self.populate_states() self.populate_cities() self.get_city_data() self.print_city_data() #code sometimes gives back an error. Something like: ''' Traceback (most recent call last): File "lab26_anyapi.py", line 119, in <module> new_api.run_api() File "lab26_anyapi.py", line 110, in run_api self.populate_cities() File "lab26_anyapi.py", line 72, in populate_cities self.cities.append(city['city']) TypeError: string indices must be integers ''' if __name__ == "__main__": cont = 'y' while cont == 'y': new_api = AirApi() new_api.run_api() print("Would you like to choose another city? (y/n)") cont = helper.text_checker(input("> "), ['y', 'n'])
'of': ['the', 'the', 'the', 'his'] #create this data structure to randomly select the words that most frequently follow }''' def print_input_pairs(word, ordered_pairs): i = 0 while i < 10: for pair in ordered_pairs: pair_words_list = pair[0].split() first_word = pair_words_list[0] second_word = pair_words_list[1] if word.lower() == first_word.lower(): print(pair) word = second_word i += 1 break response = requests.get('http://textfiles.com/etext/NONFICTION/epicurus-principal-749.txt', headers={'User-Agent': 'Mozilla/5.0'}) text = response.text text_list = re.findall(r'\w+', text) text_nopunct = [word for word in text_list if word.isalpha()] pair_counts = pair_dict(text_nopunct) ordered_pairs = ordered_tuples(pair_counts) dict_of_succeding_words = {} if __name__ == "__main__": print("This program will select a word that commonly follows the entry word, and then select one following that. \nPlease enter the word to search for.") search_word = helper.text_checker(input("> "), text_nopunct) #print_input_pairs(search_word,ordered_pairs) counted_dict = make_following_dict(ordered_pairs) print_following_random(search_word, counted_dict)
def attribute_checker(attribute): attribute = helper.text_checker(attribute, headers) attribute_idx = [i for i in range(len(headers)) if attribute in headers[i]] return headers[attribute_idx[0]]
import helper help = helper.text_checker(input("> "),["hello"])