Пример #1
0
def showPlayerInventory(player):
    # the indices corresponding to the items that can be chosen in inventory

    while True:
        validChoices = [str(x) for x in range(1, len(player.inventory) + 1)]
        validChoices.append("b")
        inventory = player.inventoryStrings()
        printMenu(inventory, topText="Inventory")
        printCentered("*enter the number to inspect or press 'b' to return*")
        choice = pyip.inputChoice(validChoices, prompt=">")
        if choice == "b":
            printLine("-")
            break
        item = player.inventory[int(choice) - 1]
        printMenu(item.itemStrings(), topText=item.name)
        if item.equippable:
            printCentered(
                "*press 'e' to equip, 'd' to drop, or 'b' to return*")
            choice = pyip.inputChoice(["e", "d", "b"], prompt=">")
            if choice == "e":
                player.equip(item)
            elif choice == "d":
                player.dropItem(item)
        elif item.usable:
            printCentered("*press 'e' to use, 'd' to drop, or 'b' to return*")
            choice = pyip.inputChoice(["e", "d", "b"], prompt=">")
            if choice == "e":
                player.consumeItem(item)
            elif choice == "d":
                player.dropItem(item)
        else:
            printCentered("*press 'd' to drop or 'b' to return*")
            choice = pyip.inputChoice(["e", "d", "b"], prompt=">")
            if choice == "d":
                player.dropItem(item)
Пример #2
0
    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)
Пример #3
0
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()
Пример #4
0
def search(word):
    if not words_list():  # ie no words in the dictionary
        print("Dictionary is empty :(")
        return

    # get all words and meanings
    words = {}
    f = open("C:\\Users\\abukh\\MyPythonScripts\\dictionary.txt")
    for w in f:
        if w == '\n':
            continue
        w = w.split(' ')
        words[w[0].lower()] = " ".join(w[1:])
    f.close()

    # display word if it exists, else offer to add it to the dictionary
    if word in words.keys():
        print(f'\n{word.capitalize()}\n   -{words[word]}')
    else:
        add_word = pyip.inputChoice(
            ['y', 'n'],
            "No such word found in your dictionary, wanna add it (y/n)? ")
        if add_word == 'y':
            print(f"\nWord: {word.capitalize()}")
            meaning = pyip.inputStr(f"Enter {word}'s meaning: ")
            add(word.lower(), meaning)
            print("Word added!")
Пример #5
0
    def get_naki(self, action_list):
        (naki_options_str, naki_huros,
         naki_choices) = self.parse_naki_options(action_list)

        selected_naki = int(
            pyinput.inputChoice(
                naki_choices,
                prompt=f"""Please select naki type using number:
{naki_options_str}""",
                blank=True))

        if selected_naki == 6:
            return Naki.NONE, None

        possible_huro_opt = naki_huros[selected_naki]
        possible_huro_str = ""
        for i, huro in enumerate(possible_huro_opt):
            huro_str = "".join([unicode_block[h.index] for h in huro])
            possible_huro_str += f"{i}: {huro_str}\n"
        possible_huro_str += "6: Cancel\n"

        selected_huro = pyinput.inputNum(
            f"""Please select huro set using number:
{possible_huro_str}""",
            min=0,
            max=6)
        if selected_huro == 6:
            return Naki.NONE, None

        return selected_naki, possible_huro_opt[selected_huro]
def createDB():
    # clear the screen
    clear()
    print('CREATING DATABASE')
    print('1. CREATE FROM DB STUDIO LEVEL')
    print('2. CREATE MANUALLY BY SQL')
    print('3. EXIT')
    userInput = pyip.inputChoice(['1', '2', '3'], '(1/2/3):')
    # IF USER PRESS 3 EXIT
    if userInput == '3':
        return
# CREATING DB FROM THE DB STUDIO LEVEL
    elif userInput == '1':
        ifExists = True
        # getting db name and checking if such DB exists
        while ifExists:
            DBName = pyip.inputStr('Provide name of the DataBase:')
            path = Path.cwd() / DBName
            if path.exists():
                print('There is DB with this name already!')
            else:
                ifExists = False
# CREATING DB BY SQL QUERY
    else:
        query = pyip.inputStr('Provide SQL query:',
                              allowRegexes=(r'CREATE DATABASE (/w)+;'),
                              blockRegexes=(r'.*'),
                              limit=3)
        DBName = re.sub('CREATE DATABASE ', '', query)
        DBName = re.sub(';', '', DBName)
    DB = DataBase(DBName)
Пример #7
0
def selectiveCopy(folder):
     # Make sure the path is absolute path
     folder = os.path.abspath(folder)

     # Choose what files will be copied (txt, jpg)
     print("Choose which files to be copied. ", end = "")
     fileExtension = pyip.inputChoice([".txt", ".jpeg", ".pdf", ".jpg"])

     # Figure out what filename this folder should use based on what folder name exists
     number = 1
     while True:
          newFolder = os.path.basename(folder) + "_copy_" + str(number)
          if not os.path.exists(newFolder):
               break
          number += 1

     # Create the new folder name
     print(f"Creating {newFolder}...")
     os.mkdir(newFolder)
     time.sleep(1)

     # Walk through the folder tree and copy the files in a new directory
     for foldername, subfolders, files in os.walk(folder):
          if newFolder in subfolders:
               subfolders.remove(newFolder)
          print(f"We're in {foldername}...")
          time.sleep(1)

          for file in files:
               if file.endswith(fileExtension):
                    print(f"Copying {file} in {newFolder}...")
                    shutil.copy(os.path.join(foldername, file), newFolder)
                    time.sleep(1)

     print("Done.")
Пример #8
0
    def loot(self, container):
        while True:
            inventoryMenu = container.inventoryStrings()
            validChoices = [str(x) for x in range(1, len(container.inventory) + 1)]
            validChoices.extend(["b", "a"])

            printMenu(inventoryMenu, topText=container.name)
            # if everything has been looted, exit
            if len(validChoices) == 2:
                break
            printCentered("*enter the number to take item, press 'a' to loot all, or 'b' to return*")
            choice = inputChoice(validChoices, prompt=">")
            # exit loot menu option
            if choice == "b":
                break
            # loot all
            elif choice == "a":
                for item in container.inventory:
                    self.addToInventory(item)
                break
            # loot one item
            else:
                item = container.inventory[int(choice) - 1]
                self.addToInventory(item)
                container.inventory.remove(item)
def coin_toss_game():
    guess_to_toss_dict = {0: 'tails', 1: 'heads'}
    coin_flip_guess_prompt = "Guess the coin toss! Enter 'heads' or 'tails':\n"
    guess = pyip.inputChoice(prompt=coin_flip_guess_prompt,
                             choices=['heads', 'tails'])

    toss = random.randint(0, 1)  # 0 is tails, 1 is heads

    if guess_to_toss_dict[toss] == guess:
        print('You got it!')
    else:
        print('Nope! Guess again!')
        guess = pyip.inputChoice(prompt=coin_flip_guess_prompt,
                                 choices=['heads', 'tails'])
        if guess_to_toss_dict[toss] == guess:
            print('You got it!')
        else:
            print('Nope. You are really bad at this game.')
Пример #10
0
def initiate_program():
    currency_keys = list(requests.get("https://free.currconv.com/api/v7/currencies?apiKey=f97208f085855f51e65c").json()['results'].keys())
    print("Enter the currency you want to convert FROM:")
    currency_from = pyinputplus.inputChoice(currency_keys, limit=2, prompt="")
    
    print("Enter the currency you want to convert TO:")
    currency_to = pyinputplus.inputChoice(currency_keys, prompt="", limit=2)
    
    print(f"Enter the  Number of {currency_from.upper()}")
    currency_num = pyinputplus.inputInt(limit=2, prompt="")
    
    current_value_of_money = get_data(currency_from, currency_to)
    converted_value = currency_num * current_value_of_money 
    
    # print(pprint.pprint(response.json()))
    print(f"The Converted Value:\n{converted_value}")
    pyperclip.copy(converted_value)
    print("\nConverted value copied to clipboard")
Пример #11
0
 def get_category(self):
     # Asks user for category to add purchase to
     categories = self.categories
     if 'Back' not in categories:
         categories.append('Back')
     print(
         '\n\n\n\nWhich category do you want to add a purchase to? - (Enter "back" to return to menu)'
     )
     category = pyip.inputChoice(categories, '> ')
     return category
Пример #12
0
def inputPlayerLetter():
    # Lets the player type which letter they want to be
    # Returns a list with the player's letter as the first item, and the computer's letter as the second.

    letter = ''

    playerPrompt = 'Would like you be to X or O?\n'
    letter = pyip.inputChoice(['X', 'O'], prompt=playerPrompt)

    if letter == 'X':
        return ['X', 'O']
    else:
        return ['O', 'X']
Пример #13
0
def deleteCSV():
    CSVfiles = r"C:\Users\svill\Documents\Programación\Proyectos cortos Python\Backmarket scrapper\BMscrapper\CSV"
    #os.chdir(CSVfiles)

    borrar = pyip.inputChoice(['si', 'no'],
                              prompt='¿Quieres eliminar los archivos CSV?\n')
    while True:
        if borrar == 'si':
            try:
                shutil.rmtree(CSVfiles)
                sleep(1)
                print('Los archivos CSV han sido eliminados.')
                sleep(5)
                break
            except Exception as err:
                print('Ha ocurrido un error: ' + str(err))
                sleep(10)
                break

        elif borrar == 'no':
            break
Пример #14
0
def build_sandwich(quantity):
	''' int -> list
	
	Ask the user for input to make the order.	Return a list with quantity sandwiches in it, where each sandwich is also a list.
	
	>>> order = build_sandwich(2)
	>>> print(order)
	order = [['White', 'Beef', 'Cheddar', ['Lettuce'], 'Mayo'], ['Rye', 'Ham', 'Havarti', ['Cucumber slices', 'Pickles', 'Mushrooms'], 'BBQ']]
	'''
	order = []
	
	for sandwich in range(quantity):
		this_sandwich = []
		bread = pyip.inputMenu(['White', 'Wheat', 'Rye', 'Sourdough', 'Onion', 'Garlic', 'With Seeds'], numbered= True, prompt="What type of bread would you like for this sandwich?\n")
		this_sandwich.append(bread)
		protein = pyip.inputMenu(['Beef', 'Chicken', 'Turkey', 'Ham', 'Tofu', 'Fried Egg', 'Chopped Boiled Egg', 'No protein'], numbered= True, prompt="What type of protein would you like?\n")
		this_sandwich.append(protein)
		cheese_1 = pyip.inputYesNo(prompt="Would you like cheese with it? (y/n)\n")
		if cheese_1 == 'yes':
			cheese_2 = pyip.inputMenu(['Cheddar', 'Swiss', 'Mozzarella', 'Havarti', 'Parmesan', 'Feta crumbles', 'Roquefort', 'Port Salut', 'Brie', 'Camembert'], numbered=True, prompt="What type of cheese would you like to add?\n")
			this_sandwich.append(cheese_2)
		else:
			this_sandwich.append("No")
		veggies_1 = pyip.inputYesNo(prompt="Would you like some veggies with your sandwich? (y/n)\n")
		if veggies_1 == 'yes':
			num_veggie = pyip.inputChoice(['1', '2', '3'], prompt="How many veggies would you like to add? (1, 2 or 3)\n")
			veggies = []
			for num in range(int(num_veggie)):
				veggies_2 = pyip.inputMenu(['Lettuce', 'Tomato slices', 'Cucumber slices', 'Pickles', 'Mushrooms', 'Green Olives', 'Black Olives', 'Sauted Eggplant', 'Bell Peppers', 'Chili Peppers', 'Onion slices', 'Shredded Carrots'], numbered=True, prompt="What veggie would you like to add?\n")
				veggies.append(veggies_2)
			this_sandwich.append(veggies)
		else:
			this_sandwich.append(["No veggies"])
		sauce = pyip.inputMenu(['Mayo', 'Dijon Mustard', 'Ketchup', 'Ranch', 'Tzatziki', 'Teriyaki', 'BBQ'], numbered=True, prompt="And finally, what sauce would you like to add?\n")
		this_sandwich.append(sauce)
		print('\n')
	
		order.append(this_sandwich)
	
	return order
Пример #15
0
def category_selector():
    print("Here is a list of budget categories: ")
    for cat_list in (list(dict.keys(categories))):
        print(cat_list)
    if bool(categories) == False:
        print("There are no categories yet.")

    edit_category = pyip.inputYesNo("Would you like to add or remove a category? yes/no ")
    if edit_category == "yes":
        add_category = pyip.inputChoice(['add', 'delete'])
        if add_category == "add":
            new_cat_name = input("What is the name of the new category? ")
            categories[new_cat_name] = {}
            cat_add_add = list(dict.keys(categories))
            print(f"How much would you like allocate for {new_cat_name} ?")
            categories[new_cat_name] = pyip.inputNum(new_cat_name + ": ")
            income.append(categories[new_cat_name])

        elif add_category == "delete":
            if bool(categories) == False:
                print("There are no categories to delete")

            else:
                del_cat_name = input("Which category would you like to delete ")
                del categories[del_cat_name]

    income[0] = income[0] - income[-1]

    # Budget overdrawn warning
    if income[0] <= 0:
        print("WARNING: You're over budget!")
    print(f"Balance: R{income[0]}\n")

    # Print categories & their budgets
    for key, value in categories.items():
        print(key, ' : ', value)
Пример #16
0
# main loop
while program:
    # Getting YT link
    ytLink = pyip.inputURL('Provide YouTube link:')

    # Trying to create YT object
    try:
        yt = YouTube(ytLink)
    except:
        print(
            'Error occured. It could be connection error or check your URL validity'
        )
        # program = False
        break
    # let user to choose quality of the movie or only audio
    quality = pyip.inputChoice(['high', 'low', 'only audio'],
                               'Choose quality: (high, low, only audio):')
    if quality == 'low':
        stream = yt.streams.get_lowest_resolution()
    elif quality == 'high':
        stream = yt.streams.get_highest_resolution()
    elif quality == 'only audio':
        stream = yt.streams.get_audio_only()

    # default path for downloaded files
    path = str(Path('/Users/bartoszszadkowski/Downloads'))

    # ask for different path if yes get from the user
    differentPath = pyip.inputYesNo(
        'Would you like specify path to download?(y/n) (by default is: /Users/bartoszszadkowski/Download)'
    )
    if differentPath == 'Yes':
Пример #17
0
priceTally = 0
totalPrice = 0

breadType = pyip.inputMenu(['wheat', 'white', 'sourdough'],
                           prompt="Bread Type: ",
                           allowRegexes=['^wheat$|^white$|^sourdough$'])
priceTally += prices.get(breadType, 0)

proteinType = pyip.inputMenu(['chicken', 'turkey', 'ham', 'tofu'],
                             prompt="Protein Type: ",
                             allowRegexes=['^chicken$|^turkey$|^tofu$|^ham$'])
priceTally += prices.get(proteinType, 0)

cheese = pyip.inputYesNo(prompt='Do you want cheese?')

if cheese == 'yes':
    cheeseType = pyip.inputMenu(['cheddar', 'swiss', 'mozarella'],
                                prompt="Cheese Type: ",
                                allowRegexes=['^swiss$|^cheddar$|^mozarella$'])
    priceTally += prices.get('cheese', 0)

condimentType = pyip.inputChoice(['mayo', 'mustard'],
                                 prompt="Choose either mayo or mustard: ",
                                 allowRegexes=['^mayo$|^mustard$'])

sandwichNumber = pyip.inputInt(prompt='Number of sandwiches: ', min=1)
totalPrice = sandwichNumber * priceTally

print(f'Your total price is ${totalPrice}')
Пример #18
0
    # user throws scissors
    elif matchTuple == ('scissors', 'rock'):
        winner = 'computer'
        compWins += 1
    elif matchTuple == ('scissors', 'paper'):
        winner = 'user'
        userWins += 1

    return winner

print("Who dares to challenge the computer in a competition of rock, paper, and scissor?")

weapons = ['rock', 'paper', 'scissors']
userWins = 0
compWins = 0

while (userWins < 2) and (compWins < 2):
    print("\nBring forth your fist! Or press enter to flee like the coward you are!")
    compWeapon = weapons[random.randint(0,2)]
    userWeapon = pyinputplus.inputChoice(['rock', 'paper', 'scissors'], blank=True)
    match = (userWeapon, compWeapon)
    if userWeapon == '':
        break
    else:
        printOutcome(matchOutcome(match))

if userWins > compWins:
    print("Gah! You have defeated me!")
else:
    print("Bwahaha! You loose!")
Пример #19
0
    passwordStrong = True
    return passwordStrong


# MAIN PROGRAM
# IMPORTING MODULES
import re
import random
import pyinputplus as pyip
import pyperclip

inputMenu = 'ok'

while inputMenu != 'EXIT' and inputMenu != '3':
    inputMenu = pyip.inputChoice(
        ['1', '2', '3', 'PASSWORD GENERATOR', 'PASSWORD CHECKER', 'EXIT'],
        '1. PASSWORD GENERATOR\n2. PASSWORD CHECKER\n3. EXIT\n')
    if inputMenu == 'PASSWORD GENERATOR' or inputMenu == '1':
        # PASSWORD GENERATOR
        print('PASSWORD GENERATOR')
        lettersAmount = pyip.inputInt('How many letters would you like? ',
                                      min=2)
        numbersAmount = pyip.inputInt('How many numbers would you like? ',
                                      min=2)
        charactersAmount = pyip.inputInt('How many characters would you like?',
                                         min=2)
        withoutSigns = pyip.inputStr(
            'Provide signs you do not want to in your password: '******'PASSWORD CHECKER' or inputMenu == '2':
Пример #20
0
    def test_inputChoice(self):
        # Test typical usage.
        pauseThenType('cat\n')
        self.assertEqual(pyip.inputChoice(['cat', 'dog']), 'cat')
        self.assertEqual(getOut(), 'Please select one of: cat, dog\n')

        # Test order of choices.
        pauseThenType('cat\n')
        self.assertEqual(pyip.inputChoice(['dog', 'cat']), 'cat')
        self.assertEqual(getOut(), 'Please select one of: dog, cat\n')

        # Test case-insensitivity.
        pauseThenType('CAT\n')
        self.assertEqual(pyip.inputChoice(['cat', 'dog']), 'cat')
        self.assertEqual(getOut(), 'Please select one of: cat, dog\n')

        # Test custom prompt.
        pauseThenType('cat\n')
        self.assertEqual(pyip.inputChoice(['cat', 'dog'], prompt='Choose:'),
                         'cat')
        self.assertEqual(getOut(), 'Choose:')

        # Test blank prompt.
        pauseThenType('cat\n')
        self.assertEqual(pyip.inputChoice(['cat', 'dog'], prompt=''), 'cat')
        self.assertEqual(getOut(), '')

        # Test that prompt reappears.
        pauseThenType('\ncat\n')
        self.assertEqual(pyip.inputChoice(['cat', 'dog'], prompt='Choose:'),
                         'cat')
        self.assertEqual(getOut(),
                         'Choose:Blank values are not allowed.\nChoose:')

        # Test default keyword arg with retry limit keyword arg.
        pauseThenType('\n\n')
        self.assertEqual(
            pyip.inputChoice(['cat', 'dog'], default='def', limit=2), 'def')
        self.assertEqual(
            getOut(),
            'Please select one of: cat, dog\nBlank values are not allowed.\nPlease select one of: cat, dog\nBlank values are not allowed.\n'
        )

        # Test default keyword arg with timeout keyword arg.
        pauseThenType('cat\n')
        self.assertEqual(
            pyip.inputChoice(['cat', 'dog'], default='def', timeout=0.01),
            'def')
        self.assertEqual(getOut(), 'Please select one of: cat, dog\n')

        # Test retry limit with no default value.
        with self.assertRaises(pyip.RetryLimitException):
            pauseThenType('\n\n')
            pyip.inputChoice(['cat', 'dog'], limit=2)
        self.assertEqual(
            getOut(),
            'Please select one of: cat, dog\nBlank values are not allowed.\nPlease select one of: cat, dog\nBlank values are not allowed.\n'
        )

        # Test timeout limit with no default value, entering valid input.
        with self.assertRaises(pyip.TimeoutException):
            pauseThenType('cat\n')
            pyip.inputChoice(['cat', 'dog'], timeout=0.01)
        self.assertEqual(getOut(), 'Please select one of: cat, dog\n')

        # Test timeout limit with no default value, entering invalid input.
        with self.assertRaises(pyip.TimeoutException):
            pauseThenType('\n')
            pyip.inputChoice(['cat', 'dog'], timeout=0.01)
        self.assertEqual(
            getOut(),
            'Please select one of: cat, dog\nBlank values are not allowed.\n')

        # Test timeout limit but with valid input and default value.
        pauseThenType('cat\n')
        self.assertEqual(
            pyip.inputChoice(['cat', 'dog'], default='def', timeout=9999),
            'cat')
        self.assertEqual(getOut(), 'Please select one of: cat, dog\n')

        # Test retry limit but with valid input and default value.
        pauseThenType('\ncat\n')
        self.assertEqual(
            pyip.inputChoice(['cat', 'dog'], default='def', limit=9999), 'cat')
        self.assertEqual(
            getOut(),
            'Please select one of: cat, dog\nBlank values are not allowed.\nPlease select one of: cat, dog\n'
        )

        # Test blank=True with blank input.
        pauseThenType('\n')
        self.assertEqual(pyip.inputChoice(['cat', 'dog'], blank=True), '')
        self.assertEqual(getOut(), 'Please select one of: cat, dog\n')

        # Test blank=True with normal valid input.
        pauseThenType('cat\n')
        self.assertEqual(pyip.inputChoice(['cat', 'dog'], blank=True), 'cat')
        self.assertEqual(getOut(), 'Please select one of: cat, dog\n')

        # Test blank=True with normal valid input and a default value. (Make sure
        # the default value isn't used.)
        pauseThenType('cat\n')
        self.assertEqual(
            pyip.inputChoice(['cat', 'dog'], blank=True, default='def'), 'cat')
        self.assertEqual(getOut(), 'Please select one of: cat, dog\n')

        # Test applyFunc keyword arg.
        pauseThenType('c\n')
        self.assertEqual(
            pyip.inputChoice(['cat', 'dog'], applyFunc=lambda x: x + 'at'),
            'cat')
        self.assertEqual(getOut(), 'Please select one of: cat, dog\n')

        # Test allowRegexes keyword arg.
        pauseThenType('cat\n')
        self.assertEqual(pyip.inputChoice(['cat', 'dog'], allowRegexes=['.*']),
                         'cat')
        self.assertEqual(getOut(), 'Please select one of: cat, dog\n')
        pauseThenType('cat\n')
        self.assertEqual(
            pyip.inputChoice(['cat', 'dog'], allowRegexes=['cat']), 'cat')
        self.assertEqual(getOut(), 'Please select one of: cat, dog\n')

        # Test blockRegexes keyword arg, with a single regex.
        pauseThenType('cat\ndog\n')
        self.assertEqual(
            pyip.inputChoice(['cat', 'dog'], blockRegexes=['cat']), 'dog')
        self.assertEqual(
            getOut(),
            'Please select one of: cat, dog\nThis response is invalid.\nPlease select one of: cat, dog\n'
        )

        # Test blockRegexes keyword arg, with multiple regexes.
        pauseThenType('cat\ncAT\ndog\n')
        self.assertEqual(
            pyip.inputChoice(['cat', 'dog'], blockRegexes=['cat', r'c\w+']),
            'dog')
        self.assertEqual(
            getOut(),
            'Please select one of: cat, dog\nThis response is invalid.\nPlease select one of: cat, dog\nThis response is invalid.\nPlease select one of: cat, dog\n'
        )

        # Test postValidateApplyFunc keyword arg.
        # (The blocklist regex will block uppercase responses, but the
        # postValidateApplyFunc will convert it to uppercase.)
        pauseThenType('CAT\ncat\n')
        self.assertEqual(
            pyip.inputChoice(['cat', 'dog'],
                             blockRegexes=['[A-Z]+'],
                             postValidateApplyFunc=str.upper), 'CAT')
        self.assertEqual(
            getOut(),
            'Please select one of: cat, dog\nThis response is invalid.\nPlease select one of: cat, dog\n'
        )

        # Test strip keyword arg
        pauseThenType('   cat    \n')
        self.assertEqual(pyip.inputChoice(['cat', 'dog']), 'cat')
        self.assertEqual(getOut(), 'Please select one of: cat, dog\n')

        pauseThenType(' cat \ncat\n')
        self.assertEqual(pyip.inputChoice(['cat', 'dog'], strip=False), 'cat')
        self.assertEqual(
            getOut(),
            "Please select one of: cat, dog\n' cat ' is not a valid choice.\nPlease select one of: cat, dog\n"
        )

        pauseThenType('xxxcat\n')
        self.assertEqual(pyip.inputChoice(['cat', 'dog'], strip='x'), 'cat')
        self.assertEqual(getOut(), 'Please select one of: cat, dog\n')

        pauseThenType('xyzcatxxx\n')
        self.assertEqual(pyip.inputChoice(['cat', 'dog'], strip='xyz'), 'cat')
        self.assertEqual(getOut(), 'Please select one of: cat, dog\n')
Пример #21
0
import pyinputplus as pyip

menu = ['red', 'blue', 'yellow']
# s = pyip.inputNum('请输入数字:')
# print(s)
# user_input = pyip.inputMenu(menu)
# print(user_input)

user_input = pyip.inputChoice(menu)
print(user_input)

user_email = pyip.inputEmail('请输入email')
print(user_email)
Пример #22
0
def main():
    if len(sys.argv) > 1:  # to handle command line input
        word = sys.argv[1].lower()
        meaning = ' '.join(sys.argv[2:])

        print("Word:", word.capitalize())
        if word in words_list():
            print("Word already exits in your dictionary!")
        else:
            print("Meaning:", meaning)

            add(word, meaning)
            print("Word added to your dictionary!")

        quit = pyip.inputChoice(
            ['m', 'q'],
            "\nType 'm' to go to the main menu or type 'q' to quit: ")
        if quit == 'q':
            print("Bye bye!")
            return

    spacer()
    choice = display_menu()

    while choice != 5:
        if choice == 1:  # display words
            spacer()

            print("##### YOUR WORDS LIST #####\n")

            display_words()

            choice = pyip.inputChoice([
                'm', 's'
            ], "\nType 's' to search for a word or 'm' to go back to the main menu: "
                                      )
            if choice == 's':
                choice = 's'
                continue
        elif choice == 's' or choice == 2:  # search for a word
            spacer()

            print("##### SEARCH FOR A WORD #####\n")

            w = pyip.inputStr("Enter a word to search: ")

            search(w)

            choice = pyip.inputChoice([
                's', 'm'
            ], "\nType 's' to search again or 'm' to go back to the main menu: "
                                      )
            if choice == 's':
                choice = 's'
                continue
        elif choice == 3:  # add word
            spacer()

            print("##### ADD NEW WORD #####")

            word = pyip.inputStr("\nEnter the word: ")

            if word in words_list():
                print("Word already exits in your dictionary!")
            else:
                meaning = pyip.inputStr(f"Enter {word}'s meaning: ")
                add(word, meaning)

                print("Word added to your dictionary!")

            choice = pyip.inputChoice([
                'm', 'a'
            ], "\nType 'a' to add another word or 'm' to go back to the main menu: "
                                      )
            if choice == 'a':
                choice = 3
                continue
        elif choice == 4:
            spacer()

            print("##### DELETE A WORD #####\n")

            word = pyip.inputStr("Enter the word you wish to delete: ")

            delete(word)

            choice = pyip.inputChoice([
                'm', 'd'
            ], "\nType 'd' to delete another word or 'm' to go back to the main menu: "
                                      )
            if choice == 'd':
                choice = 4
                continue

        spacer()
        choice = display_menu()

    print("\nBye bye!")
Пример #23
0
    "mayo": 1,
    "mustard": 1,
    "lettuce": 1,
    "tomato": 2,
    "numberOfSandwiches": 0,
}

totalCost = 0
breadType = pyip.inputMenu(["wheat", "white", "sourdough"])
totalCost += priceList[breadType]
print(f"Your sandwich costs {totalCost} €")
proteinType = pyip.inputMenu(["chicken", "ham", "turkey", "tofu"])
totalCost += priceList[proteinType]
print(f"Your sandwich costs {totalCost} €")
cheese = pyip.inputYesNo("Do you like cheese on your sandwich?")
if cheese == ("yes"):
    cheeseType = pyip.inputMenu(["cheddar", "swiss", "mozzarella"])
    totalCost += priceList[cheeseType]
    print(f"Your sandwich costs {totalCost} €")
if pyip.inputYesNo("Do you like Ketchup or Mayo on your sandwich?") == "yes":
    thingyOnSandwich = pyip.inputChoice(
        ["mayo", "mustard", "lettuce", "tomato"])
    totalCost += priceList[thingyOnSandwich]
    print(f"Your sandwich costs {totalCost} €")
amountOfSandwiches = pyip.inputInt("How many sandwiches do you want?\n")
if amountOfSandwiches < 1:
    print("Your must take atleast 1 sandwich")

totalCost *= amountOfSandwiches
print(f"Your total amount is {totalCost} €")
Пример #24
0
    folderPath = input(
        "\nThe path for the folders tree that you want to search your files in:\n"
    )
    folderPath = path(folderPath)

    if folderPath:
        break

while True:
    try:
        direction = input("\nThe path for the new folder:\n")
        new_file_direction = path(direction)
        if not new_file_direction == None:
            break

    except:
        print("\nMake sure you entered the right path\n")
        continue

fileRegex = re.compile(r'.*\.png|jpg')  #Put the extension/name of your files

move(folderPath, fileRegex, new_file_direction, response)

response = response = pypi.inputChoice(
    ['no', 'yes'],
    prompt="\nDo you want to rename your files?(answer with yes/no)\n")

if response == "yes":
    rename(new_file_direction)
    # Draw Condition
    if user_move == AI_move:
        print ("It's a tie")

    # User Wins Condition
    elif (user_move == 'rock' and AI_move == 'scissors' or
    user_move == 'paper' and AI_move == 'rock'
    or user_move == 'scissors' and AI_move == 'paper'):
        print (user_name + " wins!")
        user_winscount += 1

    # AI Wins Condition
    else:
        print (user_name + " lost!")

    # Calculating the counter
    games_played += 1
    print (user_name + ", you've won " + str(user_winscount) + " games out of " + str(games_played) + ".")


    # Ask to try again
    print ("Try again?")
    tryagain_option = pyip.inputChoice(['Y', 'N'])

    if tryagain_option == 'Y':
        continue
    elif tryagain_option == 'N':
        print ("It was fun playing with you! Goodbye")
        break

Пример #26
0
import pyinputplus as pyip

prompt_welcome = "Welcome to the Sandwich Maker :) \n"

print(prompt_welcome)
bread = pyip.inputChoice(["wheat", "white", "sourdough"])
protein = pyip.inputChoice(["chicken", "turkey", "ham", "tofu"])

want_cheese = pyip.inputYesNo(prompt="Do you want cheese?\n")
if want_cheese == "yes":
    cheese = pyip.inputMenu(["cheddar", "Swiss", "mozzarella"])

want_mayo = pyip.inputYesNo(prompt="Do you want mayo?\n")
want_mustard = pyip.inputYesNo(prompt="Do you want mustard?\n")
want_lettuce = pyip.inputYesNo(prompt="Do you want lettuce?\n")
want_tomato = pyip.inputYesNo(prompt="Do you want tomato?\n")

mayo = "mayo" if want_mayo else "empty"
mustard = "mustard" if want_mustard else "empty"
lettuce = "lettuce" if want_lettuce else "empty"
tomato = "tomato" if want_tomato else "empty"

nr_sandwiches = pyip.inputInt(prompt="How many ssandwhiches do you want?\n")

sandwich = [bread, protein, cheese, mayo, mustard, lettuce, tomato]
prices = {
    "wheat": 0.75,
    "white": 0.69,
    "sourdough": 0.82,
    "chicken": 1.4,
Пример #27
0

def divide(x, y):
    return x / y


def breakOut(i):  # check if input is empty / user wants to end the script
    if i == '':
        raise Exception()


try:
    while True:
        x = ip.inputNum('\nenter number...\n', blank=True)
        breakOut(x)
        c = ip.inputChoice(['+', '-', '*', '/', ''], blank=True)
        breakOut(c)
        y = ip.inputNum('enter number...\n', blank=True)
        breakOut(y)

        if c == '+':
            result = add(x, y)
            print(result)

        elif c == '-':
            result = subtract(x, y)
            print(result)

        elif c == '*':
            result = multiply(x, y)
            print(result)
# python 3
# calculator.py - simple calculator program


import pyinputplus as pyip

# Asks user to enter two numbers and ensures the user enters a number
number1 = pyip.inputNum(prompt='Please enter number 1: ')
number2 = pyip.inputNum(prompt='Please enter number 2: ')

# Asks user to make choice
result = pyip.inputChoice(['+', '-', '*', '/'])

if result == '+':
    print(number1 + number2)
if result == '-':
    print(number1 - number2)
if result == '*':
    print(number1 * number2)
if result == '/':
    while number2 == 0:
        number2 = pyip.inputNum(prompt='Dividing by 0!\nPlease enter number 2: ')
    print(number1 / number2)
Пример #29
0
# Create a while loop to check for an absolute folder path input
while True:
    print("On what absolute folder path would you like to perform the action?")
    folder_path = input()
    if Path(folder_path).exists() == True:
        break
    else:
        print("Please enter a valid absolute folder path.")
        continue

# Input choice for action to perform
print(
    "What action would you like to perform on the files in the folder: Move, Copy, or Delete?"
)
action = pyip.inputChoice(['Move', 'Copy', 'Delete'])

if action in 'MoveCopy':

    # Create a while loop for the destination folder which will:
    #     -Check to see if the folder path currently exists
    #     -If it doesn't exist, ask user whether they want to create the folder path
    #     -If user wants to create folder path, check to see if the absolute folder path is valid
    #     -Ask user to provide a valid path if an invalid one was entered

    while True:
        print("What is the destination folder?")
        destination_folder = input()
        if Path(destination_folder).exists() == True:
            break
Пример #30
0
def game():
    #define loop triggers
    comp_score = 0
    user_score = 0
    #if neither has won then keep playing
    while comp_score < 2 and user_score < 2:
        print("Make your choice: 'Rock', 'Paper' or 'Scissors'")
        print("Ready?")
        #get user choice
        user_choice=pyip.inputChoice(('Rock','Paper','Scissors'),prompt=""\
                                     "Rock, Paper, Scissors. Shoot!")
        #generate computer choice
        comp_choice = compChoice()
        #if they are the same
        if user_choice == comp_choice:
            print()
            print("You chose {}".format(user_choice))
            print("I chose {}".format(comp_choice))
            print("We tied!")
            print()
            print("Score:")
            print("You've won {}.".format(user_score))
            print("I've won {}.".format(comp_score))
        #if the user chose rock
        elif user_choice == 'Rock':
            #compare to computer choice
            if comp_choice == 'Paper':
                print()
                print("You chose {}".format(user_choice))
                print("I chose {}".format(comp_choice))
                print("{} beats {}!".format(comp_choice, user_choice))
                print()
                #redefine loop trigger
                comp_score = comp_score + 1
                print("Score:")
                print("You've won {}.".format(user_score))
                print("I've won {}.".format(comp_score))
            elif comp_choice == 'Scissors':
                print()
                print("You chose {}".format(user_choice))
                print("I chose {}".format(comp_choice))
                print("{} beats {}!".format(user_choice, comp_choice))
                print()
                #redefine loop trigger
                user_score = user_score + 1
                print("Score:")
                print("You've won {}.".format(user_score))
                print("I've won {}.".format(comp_score))
        #if the user choce paper
        elif user_choice == 'Paper':
            #compare to computer choice
            if comp_choice == 'Scissors':
                print()
                print("You chose {}".format(user_choice))
                print("I chose {}".format(comp_choice))
                print("{} beats {}!".format(comp_choice, user_choice))
                print()
                #redefine loop trigger
                comp_score = comp_score + 1
                print("Score:")
                print("You've won {}.".format(user_score))
                print("I've won {}.".format(comp_score))
            elif comp_choice == 'Rock':
                print()
                print("You chose {}".format(user_choice))
                print("I chose {}".format(comp_choice))
                print("{} beats {}!".format(user_choice, comp_choice))
                print()
                #redefine loop trigger
                user_score = user_score + 1
                print("Score:")
                print("You've won {}.".format(user_score))
                print("I've won {}.".format(comp_score))
        #if the user chose scissors
        elif user_choice == 'Scissors':
            #compare to computer choice
            if comp_choice == 'Rock':
                print()
                print("You chose {}".format(user_choice))
                print("I chose {}".format(comp_choice))
                print("{} beats {}!".format(comp_choice, user_choice))
                print()
                #redefine loop trigger
                comp_score = comp_score + 1
                print("Score:")
                print("You've won {}.".format(user_score))
                print("I've won {}.".format(comp_score))
            elif comp_choice == 'Paper':
                print()
                print("You chose {}".format(user_choice))
                print("I chose {}".format(comp_choice))
                print("{} beats {}!".format(user_choice, comp_choice))
                print()
                #redefine loop trigger
                user_score = user_score + 1
                print("Score:")
                print("You've won {}.".format(user_score))
                print("I've won {}.".format(comp_score))
    #when someone has won(i.e. gotten 2 wins)
    else:
        finalScore(user_score, comp_score)