简体   繁体   中英

How to store input in two different arrays in Python

I'm trying to store 10 values in two arrays. 5 in each array. How do I store values that are inputted by the user into the arrays?

One array is for strings (names of products) and the other is for the prices of the products in the first array. I've tried to append the input with no success.

products = []
prices = []

print ("Enter the names of the five products.")
for i in range(5):
    products.append(input())

print ("Enter the prices of the five products.")
for i in range(5):
    prices.append(input())

print (products, end  = "")
print (prices, end  = "")

print ("Press enter to quit ")
quit = input()

Expected results: for the first array to store five names of inputted products and the second array to have five prices.

Actual results: the program won't start. It crashes almost immediately.

Edit:

I'm looking for the code to create output like this:

['Apple', 'Micorsoft', 'Sony', 'Oppo', 'Samsung']
['100', '80', '70', '60', '40']

I hope that makes the question easier to understand.

Your current program will execute and end up with the following:

Enter the names of the five products.
Enter the prices of the five products.
[<built-in function input>]
[<built-in function input>]

What you need is a loop that will take the input from the user using the input() function:

products = []
prices = []

print ("Enter the names of the five products.")
for i in range(5):
    products.append(input())

print ("Enter the prices of the five products.")
for i in range(5):
    prices.append(input())

print(products)
print(prices)

OUTPUT:

Enter the names of the five products.
Apple
Micorsoft
Sony
Oppo
Samsung
Enter the prices of the five products.
100
80
70
60
40
['Apple', 'Micorsoft', 'Sony', 'Oppo', 'Samsung']
['100', '80', '70', '60', '40']

EDIT:

To avoid carriage return \\r :

print(products, end  = "")

You can modify your program to something like this :

#!/usr/bin/env python

products = []
prices = []

print ("Enter the names of the five products.")
for i in range(1,6):
    products.append(raw_input(str(i) + " :"))

print ("Enter the prices of the five products.")
for i in range(1,6):
    prices.append(raw_input(str(i) + " :"))

print (products)
print (prices)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM