是什么原因导致NameError:未定义名称'...'?

时间:2018-09-25 15:40:14

标签: python

我有这些要求。

enter image description here

我到这为止了

if something

我收到此错误:NameError:未定义名称'a_tickets_sold'

2 个答案:

答案 0 :(得分:1)

尝试一下

def main():
 a_tickets_sold = int(input('How many A tickets were sold?: '))
 b_tickets_sold = int(input('How many B tickets were sold?: '))
 c_tickets_sold = int(input('How many C tickets were sold?: '))
 d_tickets_sold = int(input('How many D tickets were sold?: '))
 return a_tickets_sold,b_tickets_sold,c_tickets_sold,d_tickets_sold

def show_total_income(a_total,b_total,c_total,d_total):
    print(sum([a_total,b_total,c_total,d_total]))

def calculate_class_incomes(a_tickets_sold,b_tickets_sold,c_tickets_sold,d_tickets_sold):
    a_total = a_tickets_sold * 30
    b_total = b_tickets_sold * 30
    c_total = c_tickets_sold * 30
    d_total = d_tickets_sold * 30   
    return show_total_income(a_total,b_total,c_total,d_total)

a_tickets_sold,b_tickets_sold,c_tickets_sold,d_tickets_sold = main()
calculate_class_incomes(a_tickets_sold,b_tickets_sold,c_tickets_sold,d_tickets_sold)

在主函数中,您将有4个变量。编译完主函数后,将返回这4个变量并将其存储在我们称为主函数的各个变量中。然后这些变量将被传递到calculate_class_income函数,在那里您可以轻松使用这四个变量。

答案 1 :(得分:0)

您可以为您的代码执行以下操作:

def main():
 a_tickets_sold = int(input('How many A tickets were sold?: '))
 b_tickets_sold = int(input('How many B tickets were sold?: '))
 c_tickets_sold = int(input('How many C tickets were sold?: '))
 d_tickets_sold = int(input('How many D tickets were sold?: '))

 a_income, b_income,c_income,d_income = calculate_class_incomes(a_tickets_sold ,b_tickets_sold ,c_tickets_sold ,d_tickets_sold )

def calculate_class_incomes(a_tickets_sold,b_tickets_sold ,c_tickets_sold ,d_tickets_sold):
 a_total = a_tickets_sold * 30
 b_total = b_tickets_sold * 20
 c_total = c_tickets_sold * 15
 d_total = d_tickets_sold * 10

 return a_total,b_total,c_total,d_total