2013-07-26 48 views
-1

我正試圖編寫一個程序,要求用戶輸入產品名稱,價格和數量。從那裏,所有的信息將被添加到一個表(字典?)此外,一個ID號碼必須分配給所有創建的新項目。我對ID號段感到困惑。Python:添加一個條目?

items = {} 

product = str(input("Enter the name of a product: ")) 
price = int(input("Enter a price: ")) 
quantity = int(input("Enter a quantity: ")) 

#Assign unique ID number. 

我試圖讓下面的結果爲例:

ID#70271, shoes. 7 available, at $77.00 
+3

您將不得不詳細說明您的身份證號碼的要求。您還應列出您爲生成身份證號碼所嘗試的內容。 – Amber

+0

多少個ID號碼? –

回答

0

你可以使用uuid4創建的唯一ID

>>> from uuid import uuid4 
>>> uuid4().clock_seq 
7972L 
>>> uuid4().clock_seq 
11807L 
>>> uuid4().clock_seq 
15487L 
+0

我有一種感覺,這將是大規模的矯枉過正的產品號碼......當然不希望鍵入那些,在商店或東西;) –

0
items = {} 
import hashlib 
product = "dinosaur" 
price = 10.99 
quantity = 20 
uid = hashlib.md5(product).hexdigest() #is one way but you probably don't 
# need a hash if you just want simple number id's: a much easier way is 
otheruid = len(items) # just have the next item be the UID 
items[otheruid] = (product, price, quantity) 
0

你需要能夠檢索信息?你可能會考慮多個字典鍵,或者只是想使用一個元組或列表。

你幾乎肯定需要導入一些東西來創建ID,特別是如果它是隨機的。以下是一些將該信息添加到已存在的已填充列表或空列表的代碼。

def storesInfo(product,quantity,price,listInfo): #takes list as a variable 
    import random 
    ID = random.randrange(0,10000) 
    listInfo.append([product,price,quantity,ID]) 
    return('ID%s, %s. %f available, at %f.'%(ID, product, quantity, price),listInfo) 

def main(): 
    product = str(input("Enter the name of a product: ")) 
    price = int(input("Enter a price: ")) 
    quantity = int(input("Enter a quantity: ")) 
    listA = [[2983, 'socks',32,65.23],[9291,'gloves',98,29.00]] 
    print(storesInfo(product,quantity,price,listA)) 

main() 
+0

是的,我需要檢索信息。另外,有沒有辦法做到這一點,而不需要導入任何模塊? – user2581724

+0

不,爲了創建一個隨機ID,必須導入該模塊。如果非隨機ID是正常的,那麼你不需要它。 – AppliedNumbers