def game(): number = random.randint(0, 100) print("I have generated some integer between 0 and 100. Can you guess it?") guess = pyip.inputInt(prompt="Your guess is:\n", min=0, max=100) counter = 1 while counter != 3: if guess == number: break elif number > guess: guess = pyip.inputInt( prompt= "Your number is lower than my number. What is your new guess?\n", min=0, max=100) counter += 1 else: guess = pyip.inputInt( "Your number is higher than my number. What is your new guess?\n", min=0, max=100) counter += 1 if guess != number: print( "You are out of attempts! My number was {}. Do you want to play again?" .format(number)) else: print("You are right! This is {}. Do you want to play again?".format( number)) further_action()
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 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.")
def addRecords(): userInput = pyip.inputMenu(['clients', 'books', 'orders']) if userInput == 'clients': name = pyip.inputStr('name:') surname = pyip.inputStr('surname:') city = pyip.inputStr('city:') cur.execute('INSERT INTO clients VALUES(NULL, ?, ?, ?);', (name, surname, city)) elif userInput == 'books': authorName = pyip.inputStr('author name:', blank=True) authorSurname = pyip.inputStr('author surname:', blank=True) title = pyip.inputStr('title of the book:') price = pyip.inputFloat('price:') cur.execute('INSERT INTO books VALUES(NULL, ?, ?, ?, ?);', (authorName, authorSurname, title, price)) elif userInput == 'orders': idClient = pyip.inputInt('client\'s ID:') idBook = pyip.inputInt('book\'s ID:') date = pyip.inputStr('date: (YYYY-MM-DD)', allowRegexes=[r'\d\d\d\d-\d\d-\d\d']) state = pyip.inputChoice(['oczekiwanie', 'wyslano'], 'state: (oczekiwanie/wyslano)') cur.execute('INSERT INTO orders VALUES(NULL, ?, ?, ?, ?);', (idClient, idBook, date, state)) con.commit()
def getCRNs(): print('Enter CRN for each course one at a time. ("0" when done)') crns = [] course = pyip.inputInt() while course != 0: crns.append(course) course = pyip.inputInt() return crns
def roulette(): global money bet = pyip.inputInt( prompt="We\'re playing roulette now. Please make your bet.\n", min=1, max=money) choice = pyip.inputMenu( choices=['number', 'else'], prompt="Will your guess be regarding the nature of number or " "the number itself? Please enter either \'number\' of" " \'else\'.\n") if choice == 'number': guess = pyip.inputInt( prompt="Please enter any number between 0 and 36.\n", min=0, max=36, allowRegexes=[r'00']) else: guess = pyip.inputMenu(choices=['odd', 'even'], prompt='Please enter either odd or even.\n') print("Your guess is {} and your bet is {}$.".format(guess, bet)) time.sleep(1) money -= bet win = 2 * bet loss = -bet num = random.randint(0, 36) if (guess == 'Even') or (guess == 'Odd'): if (guess == "Even") and (num != 0) and (num % 2 == 0): money += win print( "The number on the roulette is {} and it is even! You won {}. Your balance is {}." .fromat(num, win, money)) time.sleep(1) elif (guess == "Odd") and (num != 0) and (num % 2 == 1): money += win print( "The number on the roulette is {} and it is odd! You won {}. Your balance is {}." .fromat(num, win, money)) time.sleep(1) else: print( "You didn\'t guess this time. The number on the roulette is {} and it is not {}. You lost {}. " "Your balance is {}.".format(num, guess, loss, money)) time.sleep(1) else: if guess == num: money += win print( "The number on the roulette is {}! You won {}. Your balance is {}." .fromat(num, win, money)) time.sleep(1) else: print( "You didn\'t guess this time. The number on the roulette is {}. You lost {}. " "Your balance is {}.".format(num, loss, money)) time.sleep(1)
def timer(): s = pyin.inputYesNo( 'Do you know the time in seconds you want to exercise for') if s == 'yes': t = pyin.inputNum( 'Enter the time in seconds you want the timer to go for') else: hours = pyin.inputInt( 'Enter the amount of hours you will be working for') mins = pyin.inputInt( 'Enter the amount of minutes you will be working for') t = seconds(hours, mins) countdown(t)
def createChar(): maxPoints = 20 while True: printMenu(["What is your name?"], topText="Create your Character") name = pyip.inputStr(">") printMenu([ "%s: %s" % (count + 1, className) for count, className in enumerate(classNames) ]) print("Choose your class: ") playerClass = pyip.inputInt(">", min=1, max=len(classNames)) print("You chose %s" % classNames[playerClass - 1]) if playerClass == 4: maxPoints /= 2 printLine("-") printWrapped( "You have up to %s skill points to spend however you like on your starting health, strength and speed." % maxPoints) # add for loop here strength = pyip.inputInt(">Enter strength: ", min=1, max=maxPoints - 1) printLine("-") printCentered("Points remaining: " + str(maxPoints - strength)) speed = pyip.inputInt(">Enter speed: ", min=1, max=maxPoints - strength) printLine("-") printCentered("Points remaining: " + str(maxPoints - strength - speed)) sleep(.5) confirm = pyip.inputYesNo( "%s will have %s strength and %s speed.\n>Is this okay? " % (name, strength, speed)) # replace with dictionary if confirm == "yes": if playerClass == 1: player = Warrior(name, strength, speed) elif playerClass == 2: player = Ranger(name, strength, speed) elif playerClass == 3: player = Rogue(name, strength, speed) else: # change to allow Deprived player = Deprived(name, strength, speed) pass break enterDungeon(player)
def get_books(self): for i in range(self.num_books): new_title = pyip.inputStr(f'What is the name of book {i + 1}: ') self.book_set.append(book.Book(new_title)) for i in range(len(self.book_set)): current_page = pyip.inputInt( f"What is the current page of {self.book_set[i].title}?: ", min=1) current_HW_page = pyip.inputInt( f"What is the current HW page of {self.book_set[i].title}?: ", min=1) self.book_set[i].current_page = current_page self.book_set[i].current_HW_page = current_HW_page
def rounds(self): ''' with this method players can choose how many rounds they want to play ''' total = pyip.inputInt(prompt='How many round do you want to play?: ', min=3, max=10) return total
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 pick_card(): global money bet = pyip.inputInt( prompt= "We're randomly picking the card. The winner card is the one which number is larger. " "Please make your bet.\n", min=1, max=money) print("Your bet is {}. Let\'s choose cards!".format(bet)) time.sleep(1) money -= bet win = 2 * bet loss = -bet deck = [i for i in range(2, 11)] for i in range(2): deck += deck[:] card1 = random.choice(deck) deck.remove(card1) card2 = random.choice(deck) if card1 > card2: money += win print( "Congratulations! Your card is {} and it is higher than my card, which is {}. You won {}. Your " "balance is {}.".format(card1, card2, win, money)) time.sleep(1) elif card1 < card2: print( "You lost this time. Your card is {} and it is lower than my card which is {}. You lost {}. Your " "balance is {}.".format(card1, card2, loss, money)) time.sleep(1) elif card1 == card2: money += bet print("It's a tie! Both cards are {}. You won {}. Your balance is {}.". format(card1, bet, money)) time.sleep(1)
def flip_coin(): global money bet = pyip.inputInt( prompt="We\'re playing flipping the coin now. Please make your bet.\n", min=1, max=money) guess = pyip.inputMenu( choices=['Heads', 'Tails'], prompt="What\'s your guess? Enter either Heads or Tails.\n") print("Your guess is {} and your bet is {}$. Flipping the coin!".format( guess, bet)) time.sleep(1) money -= bet win = 2 * bet loss = -bet coin = random.randint(1, 2) if (coin == 1) and (guess == 'Heads'): money += win print("Congratulations, it is Heads! You won {}. Your balance is: {}". format(win, money)) time.sleep(1) elif (coin == 2) and (guess == 'Tails'): money += win print("Congratulations, it is Tails! You won {}. Your balance is: {}.". format(win, money)) time.sleep(1) else: print( "You lost this time. Amount of your loss is {}. Your balance is: {}." .format(loss, money)) time.sleep(1)
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 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 create_fighter(name=None): while True: # если параметров не было, то попросить ввести имя if name == None: name = pyip.inputStr( "Введите имя: ", blockRegexes=[r'[@#$%^&*()_+!"№;:?*-=.,><"]$']) # если такое имя есть... if isExist(name): # то предложить создать бойца с другим именем response = print_yn( "Боец с таким именем уже существует! Хотите ввести другое? y/n\n" ) if (response == "yes"): name = None continue else: return # если нет такого имени, то продолжаем else: break # выбрать класс ans_class = pyip.inputInt("Выберите класс: 1 - Воин, 2 - Маг\n", min=1, max=2) new_fighter = None if (ans_class == 1): new_fighter = Warrior(name) else: new_fighter = Mage(name) print_g("Боец создан!") return new_fighter
def createTable(self): con = sqlite3.connect(self.name + '.db') con.row_factory = sqlite3.Row cur = con.cursor() print('1. CREATE FROM DB STUDIO LEVEL') print('2. CREATE BY SQL QUERY') userChoice = pyip.inputChoice(['1', '2'], ('(1/2)')) if userChoice == '1': tableName = pyip.inputStr('Table name:') # CREATING TABLE OBJECT table = Table(tableName) columnsAmount = pyip.inputInt('Columns amount:') for i in range(columnsAmount): columnName = pyip.inputStr('Column name: ') columnType = pyip.inputStr('Column type: ') # CREATING COLUMN OBJECT column = Column(columnName, columnType) # ADDING COLUMN OBJECT TO THE COLUMNS PROPERTY IN TABLE OBJECT table.columns.append(column) # ADDING TABLE TO THE TABLES PROPERTY IN DATABASE OBJECT self.tables.append(table) # CREATING SQL QUERY query = 'CREATE TABLE ' + table.name + ' (\n' for i in range(len(table.columns)): query += table.columns[i].name + table.columns[i].type + ',\n' # HEREEEE for i in range(len(table.columns)): print(table.columns[i].name, table.columns[i].type, table.columns[i].value)
def calc(): operation = pyip.inputMenu(['+', '-', '/', '*', '%']) first_num = pyip.inputInt(prompt="Please enter the first number:\n") second_num = pyip.inputInt( prompt="Please enter the second number(or the whole percent):\n") answer = operations(operation, first_num, second_num) if operation == '%': print("\n{n2}% of {n1} = {a}\n".format(n2=second_num, n1=first_num, a=answer)) else: print("\n{n1} {op} {n2} = {a}\n".format(n1=first_num, n2=second_num, op=operation, a=answer)) more_actions()
def question_generator(max_val): # Variables to increment guesses = 0 global correct global incorrect # Use max_value method to get range for values # Assign values for question val1 = random.randint(0, max_val) val2 = random.randint(0, max_val) # Print the question print(f"What is {val1} * {val2}? ") # Set a boolean for the while Loop guessed = False while guessed is False: timer() # Take user input user_answer = pyip.inputInt() # Increment guesses here guesses += 1 # If all guesses are exhausted if guesses == 3: print("You have exceeded your limit") print(f"{val1} * {val2} = {val1*val2}") # Increment the counter 'incorrect' incorrect += 1 guessed = True # If user provides the correct answer elif user_answer == val1 * val2: print(f"That is correct! {val1} * {val2} is {user_answer}!") # Increment the counter 'correct' correct += 1 guessed = True # If user provides incorrect answer else: print(f"Sorry try again!") continue
def prompt_user_for_NUMBER_OF_STATES(): states_facts = build_states_facts_dictionary() NUMBER_OF_STATES = len(states_facts) how_many = (f"\nHow many states would you like to drill in that category?" \ f" (select an integer between 1 and " \ f"{NUMBER_OF_STATES})\n> ") return pyip.inputInt(how_many, min=1, max=NUMBER_OF_STATES)
def deposit_money(data): """This funcction deposit money to user bank account. First it calls the check credential method to make sure the user is correct one, if user is correct it then adds the new depsoit amount to the balance cell value returned by the _check_credenctial function and finnaly save the file. Parameters: ----------- data: Dictionary -- contain user entered id and password. Return: boolean --------------- False: if the credential is wrong . True: if the depsiting is done seccessfully. """ balance_cell = BankOperationsBackend.__check_credetials(data) if not balance_cell: print(messages.invalid_credentials) return False print("\n") deposit_amount = pyip.inputInt("Amount of money you want to deposit: ", greaterThan=0) balance_cell.value = balance_cell.value + deposit_amount bank_data.save("bank_data.xlsx") print( messages.withdraw_deposit_success.format("Desposited", balance_cell.value)) print("\n") return True
def daily_book(self): print("\nWhich book will you use today: ") limit = 0 for books in range(len(self.book_set)): print(f'{books + 1}: {self.book_set[books].title}') limit += 1 response = pyip.inputInt("Please choose: ", min=1, max=limit) return response
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 dntStore(): username = pyip.inputStr( prompt= 'Enter Goldmine Username (Your UTEP Email without "@miners.utep.edu"): ' ) pswrd = getpass.getpass() print('Choose installed browser:\n(1) Chrome\t(2) Firefox') browsPic = pyip.inputInt() destroy_window2()
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 create_user_data(): username = pyip.inputStr(prompt='Username: '******'First Name: ') last_name = pyip.inputStr(prompt='Last Name: ') age = pyip.inputInt(prompt='Age: ', min=1, max=99) email = pyip.inputEmail(prompt='Email: ', ) country = pyip.inputStr(prompt='Country: ') join_date = get_date() return username, first_name, last_name, age, email, country, join_date
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 chooseChar(): while True: printMenu([ "%s: %s" % (index + 1, className) for index, className in enumerate(classNames) ], topText="Choose your Character") choice = pyip.inputInt(">", min=1, max=4) player = presetChars[choice - 1] enterDungeon(player)
def test_inputInt(self): self._test_inputNumTemplate(pyip.inputInt, '42', int) # Test blockRegexes keyword arg, with a single regex. pauseThenType('42\n43\n') self.assertEqual(pyip.inputInt(blockRegexes=['42']), 43) self.assertEqual(getOut(), 'This response is invalid.\n') # Test blockRegexes keyword arg, with multiple regexes. pauseThenType('42\n44\n43\n') self.assertEqual(pyip.inputInt(blockRegexes=['42', r'[02468]$']), 43) self.assertEqual(getOut(), 'This response is invalid.\nThis response is invalid.\n') # Test postValidateApplyFunc keyword arg. # (The blocklist regex will block uppercase responses, but the # postValidateApplyFunc will convert it to uppercase.) pauseThenType('42\n41\n') self.assertEqual(pyip.inputInt(blockRegexes=['[02468]$'], postValidateApplyFunc=lambda x: x+1), 42) self.assertEqual(getOut(), 'This response is invalid.\n')
def quizMultiplication(): ''' To see how much PyInputPlus is doing for you, try re-creating the multiplication quiz project on your own without importing it. This program will prompt the user with 10 multiplication questions, ranging from 0 × 0 to 9 × 9. You’ll need to implement the following features: - If the user enters the correct answer, the program displays "Correct!" for 1 second and moves on to the next question. - The user gets three tries to enter the correct answer before the program moves on to the next question. - Eight seconds after first displaying the question, the question is marked as incorrect - even if the user enters the correct answer after the 8-second limit. Compare your code to the code using PyInputPlus in "Project: Multiplication Quiz" on page 196. ''' import pyinputplus as pyip import random, time questionTotal = 10 answersCorrect = 0 for question in range(questionTotal): userAnswer = 0 numberFirst = round(random.uniform(0, 9)) numberSecond = round(random.uniform(0, 9)) correctAnswer = numberFirst * numberSecond questionText = '\nQuestion ' + str(question + 1).zfill(2) + ': What is ' questionText += str(numberFirst) + ' * ' + str(numberSecond) + '?' print(questionText) try: userAnswer = pyip.inputInt('Your answer: ', limit=3, timeout=8, blank=False) if userAnswer == correctAnswer: print(' * Correct!') answersCorrect += 1 time.sleep(1) except pyip.RetryLimitException: print( ' * Too many invalid responses received; moving to next question.' ) except pyip.TimeoutException: print( ' * Answer not provided within alloted time; moving to next question.' ) print('\nYour results: ' + str(answersCorrect) + ' correct answers / ' + str(questionTotal) + ' possible')