传递字典给函数

2024-03-29 09:49:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在函数中使用字典值,并且一直得到一个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()

这是回溯:

^{pr2}$

我尝试过将字典名称作为函数中的参数传递,但结果相同。另外,我应该注意到,我知道将文本文件读入字典的方法可能不是最佳方法,但我现在想把重点放在calculate_discount函数上。在

完全公开:这是一个任务。在


Tags: 函数idreadget字典defdiscountfloat
1条回答
网友
1楼 · 发布于 2024-03-29 09:49:51

正如我看到的类AddressBookGUI,有两个构造函数,但只有一个构造函数没有初始化addressbook = new ExtendedAddressBook();的参数

我想你可以调用第二个带标题的构造函数,这就是为什么addressbook为空。这是NullPointException的原因

==>;解决方案是在第二个构造函数中添加addressbook的初始化

错误的邮政编码:请参见此示例:

public class PostCodeCheck {
public static void main(String[] args) {
    String postcode = "ca14 3xn";
    System.out.print("\"" 
            + postcode 
            + "\" is " 
            + postcode.matches("[A-Z]{2}[0-9]{1,2} [0-9]{1,2}[A-Z]{2}"));
    postcode = "CA14 3XN";
    System.out.println(" And \n\"" 
            + postcode + "\" is " + postcode.matches("[A-Z]{2}[0-9]{1,2} [0-9]{1,2}[A-Z]{2}")
            + " \nbecause it accepts postcode with capital letter only!");
}

}

相关问题 更多 >