簡體   English   中英

將字典傳遞給函數

[英]Passing dictionary to a function

我試圖在函數中使用字典值,並且不斷收到NameError 不知道我在做什么錯。

import re

def main():
    sales_amount = get_amount()
    customer_ID = get_ID()
    discounts = read_discounts()
    calculate_discount(sales_amount, discounts)
    print(discount_percentage)
    #print (discounts)

def get_amount():
    return float(input("Enter total sales amount: "))

def get_ID():
    return float(input("Enter customer ID: "))

#function to read discount values, strip non-alphanumeric characters and add values to dictionary
def read_discounts():
    myFile = open('discount.txt', 'r')
    discountValues = {}

    #read and split first line
    firstLine = myFile.readline()
    firstLine = re.sub(r'\$','',firstLine)
    firstLine = re.sub(r'\%','',firstLine)
    firstLine = firstLine.split()
    #add values to dictionary
    discountValues['UpperLimit1'] = {firstLine[2]}
    discountValues['UpperLimit1'] = [ float(x) for x in discountValues['UpperLimit1'] ]
    discountValues['PercentDiscount1'] = {firstLine[4]}
    discountValues['PercentDiscount1'] = [ float(x) for x in discountValues['PercentDiscount1'] ]

    return (discountValues)

def calculate_discount(sales_amount,discounts):

    if sales_amount < discountValues[UpperLimit1]: 
        discount_percentage = discountValues[PercentDiscount1]

main()

這是回溯:

Traceback (most recent call last):
  File "C:\Users\Sam\Desktop\test.py", line 92, in <module>
main()
  File "C:\Users\Sam\Desktop\test.py", line 7, in main
calculate_discount(sales_amount, discountValues)
NameError: global name 'discountValues' is not defined

我試過將字典名稱作為函數中的參數傳遞,但結果相同。 另外我還應該注意,我知道將文本文件讀入字典的方法可能不是最佳方法,但我現在想重點關注calculate_discount函數。

完全公開:這是一項作業。

discounts = read_discounts()
calculate_discount(sales_amount, discountValues)

您節省了discounts 使用它代替discountValues

再次在這里:

def calculate_discount(sales_amount,discounts):

    if sales_amount < discountValues[UpperLimit1]: 
        discount_percentage = discountValues[PercentDiscount1]

一致使用名稱。

您的read_discounts()方法似乎也有不正確的縮進。

在您的主要功能中,您正在一行中使用變量“ discountValues”:

calculate_discount(sales_amount, discountValues)

它尚未被聲明,如果您打算使用gloabl,請在main()函數內使用此語句。

def main():
    global discountValues
    ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM