问题描述
我将如何为 get_credit_score 中的所有变量实现一个全局变量,以便它们可以在advice_to_be_given 中读取。
def close_window(self):
self.master.destroy()
def get_credit_score(self):
monthlyWage = int(input("What is your monthly wage? "))
monthlySpendings = int(input("What are your monthly spendings? "))
monthlyOverdraft = int(input("What is your monthly overdraft? "))
monthlySavings = int(input("How much do you add into your savings account per month? "))
def advice_to_be_given(self):
if monthlySavings == 0:
print("You should add more into your Savings account. ")
if monthlyOverdraft == 0:
print("Maintain not having an overdraft")
if monthlySavings > monthlySpendings and overdraft > 0:
print("Spend more money on essentials,instead of putting it into your savings. Ensure that you are not spending too much on essentials,as this can increase your overdraft")
#if monthlySpending >==3 monthlySavings:
#print("You are spending too much money in a month,add some money into savings. ")
if monthlyOverdraft < 0:
print("Add 15% of your monthly savings into paying off overdraft. ")
if monthlyOverdraft > monthlySavings and monthlyOverdraft > monthlySpendings:
print("Cut down on how much money goes into savings,and ensure that your overdraft is being paid off. ")
解决方法
def get_credit_score(self):
Global monthlyWage
monthlyWage = 2
def advice_to_be_given(self):
print(monthlyWage)
,
您可以简单地在函数外定义它们,然后在要使用它们的函数内使用 global 关键字。
例如:
monthlyWage = 0
monthlySpendings = 0
monthlyOverdraft = 0
monthlySavings = 0
def get_credit_score(self):
global monthlyWage
global monthlySpendings
global monthlyOverdraft
global monthlySavings
monthlyWage = int(input("What is your monthly wage? "))
monthlySpendings = int(input("What are your monthly spendings? "))
monthlyOverdraft = int(input("What is your monthly overdraft? "))
monthlySavings = int(input("How much do you add into your savings account per month? "))
他们变量出侧的功能可以由任何其他功能时,与全球关键字引用被使用