问题描述
最初,我在存款和取款功能中包含“全局”语句。 教授告诉我,我不能使用全局语句来完成这项作业。 Codio在顶部创建了一个变量,我无法移动它。 我必须在我的函数中访问该变量。 现在,我需要让我的函数返回,以使“ account_balance”变量在每次取款和存款后都会更新。 当前,该代码功能大部分还可以,但是在每次进行货币操作后,我都会为余额函数输入“ b”,并且先前的操作将被清除,而我又恢复了默认余额。 我在这里做错了什么? 代码如下:
import sys
#account balance
account_balance = float(500.25)
#<--------functions go here-------------------->
#printbalance function
def balance():
print('Your current balance:\n%.2f' % account_balance)
#deposit function
def deposit(temp):
deposit_amount = float(input('How much would you like to deposit today?\n'))
temp = temp + deposit_amount
print('Deposit was $%.2f, current balance is $%.2f' % (deposit_amount, temp))
return temp
#withdraw function
def withdraw(temp2):
withdrawal_amount = float(input('How much would you like to withdraw today?\n'))
if withdrawal_amount > temp2:
print('$%.2f is greater than your account balance of $%.2f ' % (withdrawal_amount, temp2))
else:
temp2 -= withdrawal_amount
account_balance = temp2
print('Withdrawal amount was $%.2f, current balance is $%.2f' % (withdrawal_amount, temp2))
return temp2
#User Input goes here, use if/else conditional statement to call function based on user input
userchoice = ''
while userchoice!= 'Q':
userchoice = input('What would you like to do?\n(B)alance?, (W)ithdraw?, (D)eposit?, (Q)uit?\n')
userchoice = userchoice.upper()
if (userchoice == 'B'):
balance ()
elif userchoice == 'W':
withdraw (account_balance)
elif userchoice == 'D':
deposit (account_balance)
elif userchoice == 'Q':
print('Thank you for banking with us.')
break
1楼
问题在于传递给函数的值是副本,而不是对原始值的引用。 您可以执行以下两项操作之一:
- 在函数中使用全局语句
- 将函数的返回值存储到全局变量中
第一选择
我认为这是你的教授所禁止的:
def deposit():
global account_balance
deposit_amount = float(input('How much would you like to deposit today?\n'))
account_balance = account_balance + deposit_amount
print('Deposit was $%.2f, current balance is $%.2f' % (deposit_amount, temp))
return account_balance
第二选择
while userchoice!= 'Q':
userchoice = input('What would you like to do?\n(B)alance?, (W)ithdraw?, (D)eposit?, (Q)uit?\n')
userchoice = userchoice.upper()
if (userchoice == 'B'):
balance ()
elif userchoice == 'W':
account_balance = withdraw (account_balance)
elif userchoice == 'D':
account_balance = deposit (account_balance)
elif userchoice == 'Q':
print('Thank you for banking with us.')
break
2楼
由于不允许使用全局变量,因此您需要使用由存款和取款函数返回的变量。
while userchoice!= 'Q':
userchoice = input('What would you like to do?\n(B)alance?, (W)ithdraw?, (D)eposit?, (Q)uit?\n')
userchoice = userchoice.upper()
if (userchoice == 'B'):
balance ()
elif userchoice == 'W':
new_balance = withdraw(account_balance)
if new_balance:
account_balance = new_balance
elif userchoice == 'D':
account_balance = deposit (account_balance)
elif userchoice == 'Q':
print('Thank you for banking with us.')
break
提款功能要么返回新的帐户余额,要么打印出您的帐户中没有足够的钱。 调用withdraw函数()后,检查它是否返回了任何东西。 如果是这样,您将使用存储在new_balance中的返回值更新account_balance。
对于存款功能,您只需要使用该功能返回的值来更新account_balance。