创建一个小型、简单的类似ATM的软件。我已经为各种操作提供了函数。但是,在输出中,我的全局变量“balance”没有被更新。下面是相关的代码片段
经过一些测试后,我意识到该值在函数中被理解为是变化的,因为当我存入一个值时,我能够提取大于初始余额的值。这意味着至少函数的变量正在更新
global menu
balance = float(input("Please enter your current balance: "))
menu = "Current balance is: {}\n Press 1 to withdraw\n Press 2 to deposit\n Press 3 to exit".format(balance)
def display():
global choice
global balance
print(menu)
choice = input("Please select a number: ")
return balance
def deposit():
global balance
global choice
amount_dep = float(input("Please enter the amount you'd like to deposit: "))
balance += amount_dep
return "Your current balance is{}".format(balance)
def withdraw():
global balance
global choice
amount_with = float(input("Please enter the amount you'd like to withdraw: "))
if amount_with > balance:
print("Sorry, but your balance is less than the amount you'd like to withdraw.")
else:
balance -= amount_with
return "Your current balance is{}".format(balance)
while finished == False:
display()
global choice
if choice == '1':
withdraw()
elif choice == '2':
deposit()
elif choice == '3':
finished = True
print("Thank you for using our service.")
else:
print("You entered an invalid number, please retry")
所以所有的输出都是有规律的,除了平衡值
在代码顶部定义变量菜单时,使用初始余额进行定义。当您在存款或取款后打印菜单时,显示例程仍在打印用初始余额定义的菜单
您可能正在处理一个任务,您应该使用全局变量,但这似乎不是一个很好的用例。取款函数返回一个字符串,说明当前余额,但您不使用它。您可以很容易地使用
balance = withdraw(balance)
调用取款函数,并将余额视为参数和返回。无论如何,继续努力,继续学习相关问题 更多 >
编程相关推荐