gpt4 book ai didi

python - 可能的全局变量问题?

转载 作者:太空宇宙 更新时间:2023-11-03 19:20:49 25 4
gpt4 key购买 nike

我正在做这个家庭作业,但我被困在一个我知道是一个非常简单的问题上。该代码的前提是一个小额现金系统,用户可以在其中存款、取款并获取当前余额。我的问题是提款和存款似乎没有通过我的帐户类。是全局变量的问题吗?稍后我将添加时间戳。预先感谢您。

import datetime
import time

class Account:
def __init__(self, initial):
self.balance = initial

def deposit(self, amt):
self.balance = self.balance + amt

def withdraw(self,amt):
self.balance = self.balance - amt

def getbalance(self):
return self.balance

def yesno(prompt):
ans = raw_input(prompt)
return (ans[0]=='y' or ans[0]=='Y')

def run():
done = 0
while not done:
user_options()
print
done = not yesno("Do another? ")
print

def user_options():
print ("Here are your options:")
print
print (" (a) Deposit cash")
print (" (b) Withdraw cash")
print (" (c) Print Balance")
print
u = raw_input("Please select a letter option: ").lower()
user_input(u)

def user_input(choice):
account = Account(0.00)
if choice == "a" or choice == "b" or choice == "c":

if choice == "a":
d = input("Enter Deposit Amount: $")
account.deposit(d)

if choice == "b":
w = input ("Enter Withdraw Amount: $")
account.withdraw(w)

if choice == "c":
print ("Balance Amount: $"),
print account.getbalance()

else:
print ("Not a correct option")


run()

#now = datetime.datetime.now()

Python版本:2.7.2

最佳答案

问题是:

account = Account(0.00)

每次调用 user_input 时,您都会创建一个新的空帐户。由于 user_input 是从 user_options 调用的,而 user_options 在运行时的 while 循环内调用,因此这发生在每个事务之前。

您需要将该行移出循环,例如:

def run():
done = 0
global account # just showing you one way, not recommending this
account = Account(0.00)
while not done:
user_options()
print
done = not yesno("Do another? ")
print

关于python - 可能的全局变量问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9816685/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com