python-3.x 如何从用户输入列表中获取特定值并将其与另一个值相乘

yi0zb3m4  于 2023-06-25  发布在  Python
关注(0)|答案(1)|浏览(165)
# creating an empty list
game_titles = []
game_prices = []
 
# number of elements as input
n = int(input("Enter number of game titles (followed by ENTER on the keyboard): "))

# iterating till the range
print('Enter the name of each game (followed by ENTER on the keyboard):')
for i in range(0, n):
    input_names = input()
    # adding the element
    game_titles.append(input_names) 
    
print('Enter the price of each game (followed by ENTER on the keyboard):')
for i in range(0, n):
    input_prices = input('$')
    game_prices.append(input_prices) 
    
print('\nGAMES IN STOCK')
list_of_lists = [game_titles, game_prices]
 # make a list of lists
 
# to print list vertically
for i in range(len(list_of_lists)):
    for x in list_of_lists:
        print(x[i], end =' ')
    print()
    
while True:
    try:
        game_to_purchase = str(input("Please enter the name of the game you would like to purchase: "))
    except ValueError:
        print("Sorry, that game is not in stock. Please enter a game that is in stock:")
        continue

    if game_to_purchase not in game_titles:
        print("Sorry, that game is not in stock.\n")
        continue
    else:
        break
        #age was successfully parsed, and we're happy with its value.
        #we're ready to exit the loop.

while True:
    try:
        num_copies = int(input("Please enter the number of copies you would like to purchase (1-10): "))
    except ValueError:
        print("Sorry, that was an invalid input. Please try again.")
        continue

    if num_copies > 10:
        print("Sorry, there aren't enough copies. Please enter a number lower than 10.\n")
        continue
    else:
        break
    
total_price = (num_copies * ___)    
print('The total for', num_copies, 'of', game_to_purchase, 'is', total_price)

你好,我试图让用户输入两个列表,一个与视频游戏名称和另一个与价格。在循环的最后,我需要获取用户想要输入的副本数量,并将其乘以单个游戏的价格,以获得购买的总价。问题是,我真的不知道如何做到这一点,我已经挣扎了几个小时。有人可以推荐如何做到这一点吗?请看倒数第二行。谢谢你!

nhjlsmyf

nhjlsmyf1#

我稍微改变了你的程序流程。而不是得到所有的标题,然后价格,我要求的标题和价格为每个游戏的顺序,并存储在一个名单的dicts。我还添加了数量,这样您就不必硬编码10的限制。小事情,但你不需要str(input()),因为它总是一个字符串。这里还有很多可以改进的地方,这只是一个开始。

# creating an empty list
games = []

# number of elements as input
while True:
    try:
        n = int(input("Enter number of game titles (followed by ENTER on the keyboard): "))
        break
    except ValueError:
        print("Please enter a valid number.")
        continue

# iterating till the range
for i in range(1, n+1):
    while True:
        try:
            print(f'Enter the name game#{i} (followed by ENTER on the keyboard):')
            title = input()
            print(f'Enter the price game#{i} (followed by ENTER on the keyboard):')
            price = float(input())
            print(f'Enter the quantity available for game#{i} (followed by ENTER on the keyboard):')
            quantity = int(input())
            games.append({
                'title': title,
                'price': price,
                'quantity': quantity,
            })
            break
        except ValueError:
            print('Invalid input. Try again.')
            continue

print('\nGAMES IN STOCK')
# to print list vertically
print('{:<10} {:<10} {:<10}'.format('TITLE', 'PRICE', 'IN-STOCK QTY'))
for d in games:
    print('{:<10} {:<10} {:<10}'.format(d['title'], d['price'], d['quantity']))

while True:
    game_to_purchase = input("Please enter the name of the game you would like to purchase: ")

    if game_to_purchase not in [g['title'] for g in games]:
        print("Game not found. Try again.\n")
        continue
    else:
        price = [g['price'] for g in games if g['title'] == game_to_purchase][0]
        copies_available = int([g['quantity'] for g in games if g['title'] == game_to_purchase][0])
        break

while True:
    try:
        num_copies = int(input("Please enter the number of copies you would like to purchase: "))
        if num_copies > copies_available:
            print(f"Sorry, there aren't enough copies. Please enter a number lower than {copies_available}.\n")
            continue
        else:
            break
    except ValueError:
        print("Sorry, that was an invalid input. Please try again.")
        continue

total_price = num_copies * price
print(f'The total for {num_copies} of {game_to_purchase} is ${total_price}')

输出:

Enter number of game titles (followed by ENTER on the keyboard): 2
Enter the name game#1 (followed by ENTER on the keyboard):
game1
Enter the price game#1 (followed by ENTER on the keyboard):
10
Enter the quantity available for game#1 (followed by ENTER on the keyboard):
5
Enter the name game#2 (followed by ENTER on the keyboard):
game2
Enter the price game#2 (followed by ENTER on the keyboard):
20
Enter the quantity available for game#2 (followed by ENTER on the keyboard):
3

GAMES IN STOCK
TITLE      PRICE      IN-STOCK QTY
game1      10.0       5         
game2      20.0       3         
Please enter the name of the game you would like to purchase: game2
Please enter the number of copies you would like to purchase: 2
The total for 2 of game2 is $40.0

相关问题