我希望用户输入特定的产品名称(保存在文件中),因此我想打印出产品的价格(保存在不同的文件中),但无法这样做。
我刚刚开始编程,所以这对我来说是新的。
def find_in_file(f) :
myfile = open("file1.txt")
products = myfile.read()
products = products.splitlines()
if f in products:
return "Product is in list"
else:
return "Product is not in list"
def printing_in_file(p) :
myprice = open("file2.txt")
price = myprice.read()
price = price.splitlines()
return price
if code in sec_code.values():
product = input("Enter product name: ")
print(printing_in_file(p))
我希望价格是输出,但我得到name 'p' is not defined。
下面的这个答案有效,但并不完整,因为您没有提供输入文件的样本。
您提供的代码没有“p”变量,因此我将其替换为变量product。我在函数find_product(名为find_in_file)中为返回值创建了bool值。如果输入的产品名称完全匹配(这会产生问题),则返回布尔值 True。接下来,代码将为产品名称调用函数find_product_price(名为Printing_in_file)。我必须创建包含产品名称和价格的文件,因为您没有在问题中提供示例文件。
此代码有效,但有局限性,因为我不知道您的输入文件或 sec_code 值的确切格式。有了额外的信息,这个代码可以得到改进,或者一些新的东西可能会用更好的东西代替其中的一些。
祝这个编码问题好运。
def find_product(product_name) :
inventory_file = open('tmpFile.txt', 'r', encoding='utf-8')
products = inventory_file.read()
products = products.splitlines()
if product_name in products:
return True
else:
return False
def find_product_price(product_name) :
product_prices = open('tmpFile01.txt', 'r', encoding='utf-8')
prices = product_prices.read()
price = prices.splitlines()
if product_name in price:
return price
product = input("Enter product name: ")
product_search = find_product(product)
if product_search == True:
print ('The product is available.')
print(find_product_price(product))
# outputs
['cisco router $350']
elif product_search == False:
print (f'{product} are not available for purchase.')
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句