在Jupiter笔记本中工作的脚本在IDE中无法按预期工作

2024-04-19 12:15:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经在Jupiter笔记本上完成了一个熟悉的Python初学者项目(银行账户,运行余额-你们都会马上认出它),它工作得非常完美。在Jupiter笔记本中,存款和/或取款时会更新余额。我想做一个应用程序与图形用户界面的代码,但它不工作在我的IDE(闲置)。你知道吗

我已将代码复制到IDLE中,因此如下所示:

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

    def __str__(self):
        return("Account holder: {}\nBalance R".format (self.owner, self.balance))

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


    def withdraw(self, with_amt ):
        if self.balance >= with_amt:
            self.balance = self.balance - with_amt
        else:
            print("insufficient funds")

cust1 = Account("Hernandez, Jose", 100.00)


print("\n", cust1)


cust1.deposit(100.00)
# cust1.withdraw(300.00)


print("\nAccount Holder: ", cust1.owner)
print("Account Balance: R", float(cust1.balance))

我本以为,如果脚本连续运行多次,每次都会触发“cust1.deposit(100)”,余额会增加100,就像我在Jupiter笔记本中反复运行cust1.deposit(100)一样。但这不会发生。余额保持不变为200(初始余额为100加上100押金)。你知道吗

我做错什么了?你知道吗

安德烈


Tags: 代码selfdefwith笔记本account余额print
2条回答

在Jupyter笔记本中,您应该在一个单元格上声明class Account,并在另一个单元格上使用cust1.deposit(100)。在Jupyter notebook中,您可以单独执行代码的一部分,它允许您多次运行cust1.deposit(100),因此每次都会增加平衡。但在ide中,不能多次执行部分代码。当您运行它时,整个代码都会被执行,这意味着balance被初始化为100,并且在调用cust1.deposit(100)时它会增加100。因此,无论运行多少次,都会看到200的余额。你知道吗

您的代码按预期工作。问题是,当您直接从IDE运行python脚本时,它只运行一次,但是Jupyter笔记本的工作方式不同。当您在Jupyter中运行代码行时,该操作的结果将被记住,我只能将其描述为“python会话”。balance是300的原因是您可能用cust1.deposit(100.00)运行了两次cell。如果要在脚本中执行此操作,应执行同一命令两次:

cust1 = Account("Hernandez, Jose", 100.00)
cust1.deposit(100.00)
cust1.deposit(100.00)
print("\n", cust1)
# will print balance with value of 300.00

相关问题 更多 >