def sandwichMaker(): promptOne = 'What kind of bread do you want?' promptTwo = 'What kind of protein do you want?' promptThree = 'What kind of cheese do you want?' promptFour = 'What kind of additional food do you want?' promptFive = 'Do you want a cheese?\n' promptSix = 'Do you want any additional food?\n' promptSeven = 'How many sandwiches do you want?\n' breadMenu = list(breadType.keys()) proteinMenu = list(proteinType.keys()) cheeseMenu = list(cheeseType.keys()) additionalFoodMenu = list(additionalFood.keys()) print(promptOne) bread = pyip.inputMenu(breadMenu, lettered=True) breadPrice = breadType[bread] print(promptTwo) protein = pyip.inputMenu(proteinMenu, lettered=True) proteinPrice = proteinType[protein] cheeseOrNot = pyip.inputYesNo(promptFive) cheesePrice = 0 if cheeseOrNot == 'yes': print(promptThree) cheese = pyip.inputMenu(cheeseMenu, lettered=True) cheesePrice = cheeseType[cheese] additionalFoodOrNot = pyip.inputYesNo(promptSix) addedPrice = 0 if additionalFoodOrNot == 'yes': print(promptFour) addedFood = pyip.inputMenu(additionalFoodMenu, lettered=True) addedPrice = additionalFood[addedFood] priceOfOneSandwich = breadPrice + proteinPrice + cheesePrice + addedPrice numOfSandwiches = pyip.inputInt(promptSeven, min=1) totalPrice = priceOfOneSandwich * numOfSandwiches print('The total price is %s$' % (totalPrice))
def delete_sheet(chosen_file): print('Delete sheets') option = 'yes' while option == 'yes': #choose what sheet openbook = openpyxl.load_workbook(chosen_file) #the main workbook sheets = openbook.sheetnames chosen_sheet = None if len(sheets) >= 2: chosen_sheet = pyip.inputMenu(sheets, numbered=True) elif len(sheets) == 1: chosen_sheet = sheets[0] else: print('N/A') if chosen_sheet != None: chosen_sheet_obj = openbook[ chosen_sheet] #change it into sheet obj view_sheet(chosen_file, chosen_sheet) delete = pyip.inputYesNo('To delete?[Y/N]') if delete == 'yes': del openbook[chosen_sheet] openbook.save(chosen_file) print('%s is deleted.' % chosen_sheet) option = pyip.inputYesNo('Anymore to delete?')
def item_menu(ftp_connection): ''' Prompt user with an item menu and issue class functions accordingly. Promp user for choice to re-run through file upload/download again. ''' while True: print("=" * 12 + " MENU " + "=" * 12) print("Please choose an option from the menu:") print("1) Upload") print("2) Download") print("3) Exit program") choice = inputNum(prompt="Option: ", min=1, max=3) if choice == 1: while True: ftp_connection.upload_prompt() ftp_connection.upload_file() retry_upload = inputYesNo(prompt="Upload another? ") if 'yes' in retry_upload: continue else: break continue elif choice == 2: while True: ftp_connection.download_prompt() ftp_connection.download_file() retry_download = inputYesNo(prompt="Download another? ") if 'yes' in retry_download: continue else: break continue else: print("Exiting program. Goodbye!") sys.exit()
def finalScore(user, comp): #if the user won if user > comp: print() print("You beat me!") print("The score was {} to {}.".format(user, comp)) print() print("I want a rematch.") play_again = pyip.inputYesNo("Want to play again? (yes/no)") if play_again == 'yes': print("Good choice!") game() else: print() print("Okay, see you next time!") #if the user lost elif comp < user: print() print("Good game!") print("I won this one {} to {}.".format(comp, user)) print() play_again = pyip.inputYesNo("Want to play again? (yes/no)") if play_again == 'yes': print("Challenge accepted!") game() else: print() print("Okay, see you next time!")
def makeSandwich(): sandwichList = [] totalCost = 0 #Ask customer for type of bread bread = pyip.inputMenu(['wheat', 'white', 'sourdough']) sandwichList.append(bread) #Ask customer for choice of protein meat = pyip.inputMenu(['chicken', 'turkey', 'ham', 'tofu']) sandwichList.append(meat) #Ask customer if they want cheese cheesePrompt = 'Would you like cheese' cheese = pyip.inputYesNo(cheesePrompt) if cheese == 'yes': typeCheese = pyip.inputMenu(['cheddar', 'swiss', 'mozzarella']) sandwichList.append(typeCheese) mayoPrompt = 'Would you like mayo' mayo = pyip.inputYesNo(mayoPrompt) if mayo == 'yes': sandwichList.append('mayo') mustardPrompt = 'Would you like mustard' mustard = pyip.inputYesNo(mustardPrompt) if mustard == 'yes': sandwichList.append('mustard') lettucePrompt = 'Would you like lettuce' lettuce = pyip.inputYesNo(lettucePrompt) if lettuce == 'yes': sandwichList.append('lettuce') tomatoPrompt = 'Would you like tomato' tomato = pyip.inputYesNo(tomatoPrompt) if tomato == 'yes': sandwichList.append('tomato') #Ask how many sandwiches they want numSandwichesPrompt = 'How many sandwiches would you like' print(numSandwichesPrompt) numSandwiches = pyip.inputInt(min=1) for ingredient in sandwichList: if ingredient == 'wheat' or ingredient == 'white' or ingredient == 'sourdough': totalCost += 1 elif ingredient == 'chicken' or ingredient == 'turkey' or ingredient == 'ham': totalCost += 3 elif ingredient == 'tofu': totalCost += 4 elif ingredient == 'cheddar' or ingredient == 'swiss' or ingredient == 'mozzarella': totalCost += 1 totalCost = totalCost * int(numSandwiches) print(sandwichList) return print('Total cost is: $' + str(totalCost))
def make_sandwiches(): """ Summary: Takes inputs for sandwich preferences and displays final cost. """ import pyinputplus as pyip choices = [] total_cost = 0 # Dictionary of products and prices price_list = { 'Wheat': 3, 'White': 3, 'Sourdough': 3.5, 'Chicken': 1, 'Turkey': 1, 'Ham': 1, 'Tofu': 1.5, 'Cheddar': 1, 'Swiss': 1.5, 'Mozzarella': 0.5, 'None': 0 } # Bread selection bread_type = pyip.inputMenu(['Wheat', 'White', 'Sourdough'], numbered=True) choices.append(bread_type) # Protein selection protein_type = pyip.inputMenu(['Chicken', 'Turkey', 'Ham', 'Tofu'], numbered=True) choices.append(protein_type) # Cheese seletction if pyip.inputYesNo('Would you like cheese? ("yes" or "no")') == 'yes': cheese_type = pyip.inputMenu(['Cheddar', 'Swiss', 'Mozzarella'], numbered=True) choices.append(cheese_type) else: cheese_type = 'None' # Condiment selection if pyip.inputYesNo('Would you like condiments? ("yes" or "no")') == 'yes': condiments = pyip.inputMenu(['Mayo', 'Mustard', 'Lettuce', 'Tomato'], numbered=True) # Calculate sandwiche cost for item in choices: total_cost += price_list[item] # Number of sandwiches number_sandwiches = pyip.inputInt('How many sandwiches would you like?', min=1) # Print total cost print(f'''Your sandwich's price is ${float(total_cost)}. Your total cost will be ${float(total_cost * number_sandwiches)} ''')
def sandwich(): # I assigned these prices completely random :) prices = { 'Wheat': 2, 'White': 2.50, 'Sourdough': 3, 'Chicken': 2, 'Turkey': 2, 'Ham': 3, 'Tofu': 3, 'Cheddar': 1, 'Swiss': 2, 'Mozzarella': 1.50, 'saucey': 0.50 } print(f'To select bread type:') bread = pyip.inputMenu(['Wheat', 'White', 'Sourdough'], numbered=True) print(f'To select protein type:') protein = pyip.inputMenu(['Chicken', 'Turkey', 'Ham', 'Tofu'], numbered=True) cheese = pyip.inputYesNo( 'Do you want cheese? Please enter yes if you do, and no if you don\'t: ' ) if cheese.lower() == 'yes': print('To select cheese type:') cheesetype = pyip.inputMenu(['Cheddar', 'Swiss', 'Mozzarella'], numbered=True) if cheese.lower() == 'no': cheesetype = 'Cheddar' prices['Cheddar'] = 0 sauce = pyip.inputYesNo( 'Do you want mayo, mustard, lettuce, or tomato in sandwich?: ') if sauce.lower() == 'yes': sauce = 'saucey' if sauce.lower() == 'no': sauce = 'saucey' prices['saucey'] = 0 each = pyip.inputInt('How many sandwiches you want: ', min=1) if cheese.lower() == 'yes': print(f'You choose {bread},{protein},cheese:{cheese}', f'({cheesetype}), ', f'Sauce:{sauce}, {each} sandwiches.') if cheese.lower() == 'no': print(f'You choose {bread},{protein},cheese:{cheese}', f'Sauce:{sauce}, {each} sandwiches.') y = pyip.inputYesNo('You want to buy? (Yes/No) ') if y == 'yes': print( (prices.get(str(bread)) + prices.get(str(protein)) + prices.get(str(cheesetype)) + prices.get(str(sauce))) * int(each)) if y == 'no': sandwich()
def sandwichMaker(): sandwichPrice = 0.0 option = "" # prompt user for bread type in form of a numbered menu option = pyip.inputMenu(kBreadChoices, numbered=True) # if statements to determine what option the user picked, and will add the price of ingredient to the sandwich total if option == kBreadChoices[0]: sandwichPrice += 1 elif option == kBreadChoices[1]: sandwichPrice += 1.3 elif option == kBreadChoices[2]: sandwichPrice += 1.7 # prompt user for protien options in form of a numbered menu option = pyip.inputMenu(kProteinChoices, numbered=True) # if statements to determine what option the user picked, and will add the price of ingredient to the sandwich total if option == kProteinChoices[0]: sandwichPrice += 1.5 elif option == kProteinChoices[1]: sandwichPrice += 2 elif option == kProteinChoices[2]: sandwichPrice += 1 elif option == kProteinChoices[3]: sandwichPrice += 2.5 # asks user if they want to add cheese, if the answer is yes, will then show a menu of cheese options if pyip.inputYesNo("Would you like to add cheese?\n") == 'yes': option = pyip.inputMenu(kCheeseChoices, numbered=True) # if statements to determine what option the user picked, and will add the price of ingredient to the sandwich total if option == kCheeseChoices[0]: sandwichPrice += 1 elif option == kCheeseChoices[1]: sandwichPrice += 1.5 elif option == kCheeseChoices[2]: sandwichPrice += 2 # asks user if they want to add mayo, mustard, lettuce, or tomatoes, if the answer is yes, the sandwich total is increased if pyip.inputYesNo( "Would you like to add mayo, mustard, lettuce, or tomatoes?\n" ) == 'yes': sandwichPrice += 2 # prompts user for value on how many sandwiches they would like to order, will then multiply sandwich total with input option = pyip.inputInt("How many sandwiches would you like to order?\n", greaterThan=0) sandwichPrice = sandwichPrice * option # round and print the sandwich total price sandwichPrice = round(sandwichPrice, 2) print(f"Your total is: ${sandwichPrice}\n")
def current_guess(self): """Guess a letter.""" letter = input("Guess a letter: ").lower() # check whether letter was already guessed if letter in self.guessed: print("Letter already guessed.") self.current_guess() # add letter to already guessed self.guessed.append(letter) # check if letter in word if letter in self.word: idxs = [] for num, let in enumerate(self.word): if let == letter: idxs.append(num) for i in idxs: self.empty[i] = letter else: self.mistakes += 1 # check if game is finished if "_" in self.empty and self.mistakes < 10: self.show_status() self.current_guess() elif self.mistakes == 10: print("Game over") self.show_status(t=5) print("The word was:", self.word) again = pyip.inputYesNo("Play again? ") if again == "yes": print("ok") self.reset() else: print("Try again later") elif "_" not in self.empty: print("You win") again = pyip.inputYesNo("Play again? ") if again == "yes": print("ok") self.reset() else: print("Try again later") else: print("The computer is confused.")
def sandWichePrefs(): breadType = pyip.inputMenu(['wheat', 'white', 'sourdough'], numbered=True) proteinType = pyip.inputMenu(['chicken', 'turkey', 'ham', 'tofu'], numbered=True) wantCheese = pyip.inputYesNo(prompt='Do you want cheese?') if wantCheese: cheeseType = pyip.inputMenu(['cheddar', 'Swiss', 'Mozarella'],prompt='Enter cheese type: ') wantMayo = pyip.inputYesNo(prompt='Do you want mayo, musturd, lettuce, or tomato? ') quantity = pyip.inputInt(prompt='How many sandwiches do you want? ') perPieceCost = prices[breadType] + prices[proteinType] totalCost = perPieceCost * quantity print('price per sandwiches is $%s' %(perPieceCost)) print('For %s sandwiches your cost is: $%s.' % (quantity, totalCost))
def add_sheet(chosen_file): print('Add sheets') option = 'yes' while option == 'yes': #choose what sheet openbook = openpyxl.load_workbook(chosen_file) #the main workbook sheets = openbook.sheetnames add = pyip.inputYesNo('To add?[Y/N]') if add == 'yes': sheet_name = pyip.inputStr('New sheet name:') openbook.create_sheet(sheet_name) openbook.save(chosen_file) print('%s is add.' % sheet_name) openbook.save(chosen_file) option = pyip.inputYesNo('Anymore to added?')
def edit_sheet(chosen_file): #edit sheets option = 'yes' while option == 'yes': #choose what sheet openbook = openpyxl.load_workbook(chosen_file) sheets = openbook.sheetnames chosen_sheet = None if len(sheets) >= 2: chosen_sheet = pyip.inputMenu(sheets, numbered=True) elif len(sheets) == 1: chosen_sheet = sheets[0] else: print('N/A') if chosen_sheet != None: chosen_sheet_obj = openbook[ chosen_sheet] #change it into sheet obj view_sheet(chosen_file, chosen_sheet) chosen_row = pyip.inputInt('Choose a row:') chosen_column = pyip.inputInt('Choose a column:') new_value = pyip.inputStr('New value:') chosen_sheet_obj.cell(\ row = chosen_row,column = chosen_column ).value = new_value openbook.save(chosen_file) option = pyip.inputYesNo('Anymore to edit?')
def create_file(): print('This is an example:') view_sheet('sample.xlsx') creating = pyip.inputYesNo('Adding?[Y/N]') if creating == 'yes': filename = input('File name:') #name of file #for the titles of each heading fontsetting = Font(bold=True) titles = int(input('Number of titles:')) #no of sets of items items = int(input('Number of items:')) wb = openpyxl.Workbook() current = wb.active #current sheet #row is vertical, column is horizontal for i in range(titles): #add titles title = input('title:') current.cell(row=1, column=i + 1).font = fontsetting current.cell(row=1, column=i + 1).value = title for j in range(items): #to add items for k in range(titles): item = input('item:') current.cell(row=j + 2, column=k + 1).value = item wb.save('%s.xlsx' % filename)
def get_tolerance(): response_tol = pyip.inputYesNo(f"\nSoll eine Bin-Toleranz abweichend von (+/-) 2.5 % verwendet werden? (yes/no) \n") =="yes" if response_tol==True: tolerance = pyip.inputNum(f"\nEnter the percent")/100 else: tolerance = 2.5/100 return tolerance
def delete_report_card(): #call this so the records are fetched to show to the user result = view_report_card(mode='delete') no_of_records = len(result) if no_of_records == 0: print("No Records Found To Delete") return choice = pyip.inputYesNo( prompt= f"Found { no_of_records }. Are you sure you want to delete all of the above? (yes/no)" ) if choice == 'no': print("Skipping Delete...") return session = Session() for card in result: session.delete(card) session.commit() print(f"Deleted { no_of_records } records") return
def ask_to_makefile(): ask = pyip.inputYesNo('\nCreate CSV file of results ? (yes or no): ') if ask.lower() == 'yes': makecsv = True else: makecsv = False return makecsv
def addacc(): #add acc Account_id = None UserID = input('New UserID/email:') #can be left blank pw_option = pyip.inputYesNo('Generate random password?') if pw_option == 'yes': Pass = passwordgenerator() else: Pass = pyip.inputStr('Password:'******'Remarks:') displaypurpose() items = list(cursor.execute('''SELECT * from Purpose''').fetchall()) key_list = [str(item[0]) for item in items ] if len(key_list) >= 2: print('Choose the following keys:') choose_key = pyip.inputMenu(key_list,numbered=True) #choose the key of the item else: choose_key = key_list[0] #1st item db.execute('''INSERT INTO Accounts('Account_id','UserID','Pass','Remarks','PurposeID') VALUES (?,?,?,?,?)''',\ (Account_id,UserID,Pass,Remarks.title(),choose_key)) if Remarks != '': Remarks = Remarks.title() acctable db.commit() print('Finish adding')
def make_sandwich(): sum_of_sandwich = 0 a = 1 dif = '' count = 0 amount_of_sandwiches = pyip.inputInt( prompt="How many sandwiches do you want? ", min=1) if amount_of_sandwiches == 1: print(f'Ok {amount_of_sandwiches} sandwich') print(f'Ok {amount_of_sandwiches} sandwiches') while amount_of_sandwiches != count: bread_type = pyip.inputMenu(['wheat', 'white', 'sourdough']) sum_of_sandwich += 2 protein_type = pyip.inputMenu(['chicken', 'turkey', 'ham', 'tofu']) sum_of_sandwich += 4 cheese_or_no = pyip.inputYesNo(prompt="Do you want cheese or not?") if cheese_or_no == 'no': sendwich = f'{bread_type} bread, {protein_type} protein and no cheese!! It cost is {sum_of_sandwich}$' else: cheese_type = pyip.inputMenu(['cheddar', 'swiss', 'mozzarella']) sum_of_sandwich += 5 sendwich = f'{bread_type} bread, {protein_type} protein and {cheese_type} cheese!!! It cost is {sum_of_sandwich}$' dif += f'{a} with: {sendwich} \n' sendwich = '' a += 1 count += 1 sum_of_sandwich = 0 print(dif)
def idiot(): while True: prompt = 'Want to know how to keep an idiot busy for hours? \n' response = pyip.inputYesNo(prompt) if response == 'no': break print('Thank you. Have a nice day')
def save_pw(self, pw=None, copy_from_clipboard=True): try: if not pw and copy_from_clipboard: print("[IN PROGRESS] Copying password from clipboard ...") pw = pyperclip.paste() if pw == '': print("[ALERT] No password was found in clipboard.") ans = pyip.inputYesNo( "Do you want to input the password? (y/n): \n", yesVal='y', noVal='n') if ans != 'y': print("[INFO] No passwords were saved.") return pw = Utils.input_pw() elif not pw: pw = Utils.input_pw() pw_ref = Utils.input_ref(max_len=32) print("[IN PROGRESS] Storing password ...") pw_id = Utils.autoincrement_id(self.db, table_name="passwords") if not self.db.register_pw(pw_id, self.__user_id, pw_ref, pw_hash=Utils.encrypt( pw, encoding='utf-8')): print(f"[INFO] No passwords were saved.") return print(f"[INFO] Password succesfully stored!") except Exception as ex: self.log.exception(f"TYPE: <{type(ex)}> - {ex}\n", traceback.format_exc()) print( f"[ERROR] An exception has ocurred. check {LOG_FILE_PATH} for more info." )
def selectiveCopier(filepath, fileType): p = Path(filepath) c = Path(p / 'Copy') #Create a new Dictonary while True: try: #If succesfull create one and break the Loop os.makedirs(c) break #Folder exists alredy except: #Should be a new one created? prompt = 'Copy Folder exists already\nShould a new Copy be created (yes/no)\n' response = pyinputplus.inputYesNo(prompt) response = response.lower() #Create a new folder Path with New name, os.makedits above creates new one or another erros leads back here if response == 'yes': prompt2 = 'Name?\n' newName = str(pyinputplus.inputStr(prompt2)) c = Path(p / newName) #Close Program else: os._exit(1) #Walks through entire Path for filename in p.rglob('*.jpg'): try: #Copies of possible shutil.copy(filename,c) except: #Files can't exist twice print(f'"{filename}" is already Backed up')
def valid_user(self): self.screen.display() if not self.db.check(self.__id): try: print(f"[INFO] {self.__id} is not registered yet.", end=' ') ans = pyip.inputYesNo('Do you want to register? (y/n) ', limit=3, yesVal='y', noVal='n') if ans == 'y': name = pyip.inputStr('Enter a name: ', limit=3) money = pyip.inputInt('Initial money (default 0): ', limit=3, default=None) response = self.db.register(self.__id, name, money) if response: self.add(money) print( f'[INFO] User: (id:{self.__id}, name:{name}, money:{money}$) was succesfully registered in the Database.' ) else: print('[ERROR] Something was wrong with the register.') print('Thanks for using the script!') sys.exit() else: sys.exit() except pyip.RetryLimitException: print(f'[ERROR] Limit of attempts exceeded.')
def handleNearbyEnemies(room, player): # checks if an enemy is in the same spot as the player for enemy in room.enemies: if player.roomLocation == enemy.roomLocation: print(enemy.stealth) # check if player noticed the enemy if player.perception + randint(-2, 2) > enemy.stealth: enemy.detected = True print("you notice a %s nearby." % enemy.name) # if enemy noticed the player if player.stealth + randint(-2, 2) < enemy.perception: player.detected = True else: if enemy.detected: print("it didn't see you") player.detected = False # can choose if you want to fight the nearby enemy you see if enemy.detected: print("attack the %s?" % enemy.name) if pyip.inputYesNo(">") == "yes": Combat(player, enemy) room.enemies.remove(enemy) room.enemyCount -= 1 return print("you decide to try and leave it alone.") # if the enemy sees you and you don't see it, # it may sneak attack you if player.detected: if randint(0, 10) < enemy.aggression: print("but %s saw you and attacks" % enemy.name) Combat(player, enemy) room.enemies.remove(enemy) room.enemyCount -= 1
def delete(self): # allows user to delete an existing category while True: clear_screen() print('********** Select Category to DELETE **********') category_list = self.categories category_list.append('Back') category = pyip.inputMenu( category_list, prompt='\n\n\nWhat do you want to DELETE?\n\n', numbered=True) if category == 'Back': break else: choice = pyip.inputYesNo( prompt= f'\nAre you sure you want to DELETE "{category}"?\n> ') if choice == 'yes': cat = self.wb[category] self.wb.remove(cat) print(f'\n"{category}" has been deleted.') time.sleep(1) break elif choice == 'no': continue
def playAgain(): # This function returns True if the player wants to play again, otherwise it returns False. playAgainPrompt = 'Do you want to play again? (yes/no)\n' response = pyip.inputYesNo(prompt=playAgainPrompt) return response.startswith('y')
def main(): while True: response = pyip.inputYesNo( 'Want to know how to keep an idiot busy for hours?\n') if response == 'no': break print('Thank you. Have a nice day.')
def run_setup(): # for persistent data; saves and retrieves user credentials # Will prompt user for credentials and for servers running call manager service # enter servers seperated by comma "," no spaces e.g. 10.10.10.1,10.10.10.2,10.10.10.3 st_setup = pyip.inputYesNo('\nEnter setup ? (yes or no): ') setup_var = shelve.open('cli_var') if st_setup == 'yes': usern = input('username: '******'password: '******'s seperated by comma ',' :") servers = servers.split(',') setup_var['cli_user'] = usern setup_var['cli_pw'] = pphrase setup_var['servers'] = servers setup_var.close() else: if ('cli_user' in setup_var) and ('cli_pw' in setup_var): print('Using saved credentials') usern = setup_var['cli_user'] pphrase = setup_var['cli_pw'] servers = setup_var['servers'] setup_var.close() return usern, pphrase, servers
def main(): print("pdf_paranoia_0.0.1") print("pdf_paranoia will encrypt your PDF files.") file_path = prompt_file_path() password = prompt_encryption_key() pdf_files = grab_pdfs(file_path) if pdf_files == []: print("No PDF files were found in the given directory.") return None encrypt_pdfs(pdf_files, password) if test(file_path, password): print(f"All PDF files in {file_path} were properly encrypted.") else: print(f"PDF files in {file_path} were not properly encrypted.") return None response = pyinputplus.inputYesNo( prompt="Would you like to delete the original, unecrypted files?\n", yesVal="yes", noVal="no", ) if response == "no": print("pdf_paranoia.py has finished running.") elif response == "yes": delete_originals(pdf_files) print( "Unencrypted PDF files have been deleted. Thank you for using pdf_paranoia." )
def add(self): # allows user to add a purchase to a category while True: clear_screen() print('********** Add Purchase **********') self.print_categories() category = self.get_category() if category == 'Back': return # Get Purchase, Cost, and Date from user purchase = self.get_purchase() cost = self.get_cost() date = self.get_date() full_purchase = f'Date: {date}\nPurchase: {purchase}\nCost: ${cost}' wb_sheet = self.wb[category] # Confirm to add purchase text = f'\n\nDo you want to add the following purchase to {category}?\n\n{full_purchase}\n\n> ' choice = pyip.inputYesNo(prompt=text) first_empty_row = wb_sheet.max_row + 1 # If confirmed, write purchase to worksheet if choice == 'yes': wb_sheet[f'A{first_empty_row}'].value = date wb_sheet[f'B{first_empty_row}'].value = purchase wb_sheet[f'C{first_empty_row}'].value = cost self.sort_purchases_by_date(wb_sheet) print(f'\nPurchase has been added.') break # If canceled, start over if choice == 'no': break self.save() time.sleep(1)
def dndRolls(): print("How many sides should the fates consider?") #get number of sides the dice needs sides = pyip.inputInt("Give me ___-sided dice.", min=1, max=20) print("And how many fortunes do you dare to roll?") #get number of dice to roll dice = pyip.inputInt("Roll ___ dice.", min=1) print() print("The fates have spoken.") print() #define loop trigger rolls = 0 #roll for specified number of dice while rolls < dice: roll = random.randint(1, sides) #redefine loop trigger rolls = rolls + 1 #print result of dice roll print("Fortune {}:".format(rolls), roll) print() else: #When all dice are rolled ask if they want to roll again roll_again=pyip.inputYesNo("Do you seek further wisdom?"\ "(yes/no)") #if yes send back to top of function if roll_again == 'yes': dndRolls() #if no, exit text else: print() print("Good luck, adventurer!") print("May the fates decide in your favor.")