iT邦幫忙

0

Python新手 仿造銀行存錢提錢,查餘額

Itzy 2021-05-21 22:34:252183 瀏覽
  • 分享至 

  • xImage

這個程式:輸入存款,提款查餘額,可是run出來,他最後都print0給我,是我後面哪裡寫錯了嗎??
class Account:
def init(self,name):
self.name=name
self.balance=0
def deposit(self):
x=int(input('你要存入多少錢?'))
while x<0:
print('Error')
break
else:
self.balance+=x
return self.balance
def withdraw(self):
y=int(input('你要提取多少錢?'))
while y<0:
print('Error')
break
else:
self.balance-=y
return self.balance
Account('Sam').deposit()
Account('Sam').withdraw()
while Account('Sam').balance<0:
print('Error')
break
else:
print(Account('Sam').balance)

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

0
johnsonnnn
iT邦新手 4 級 ‧ 2021-05-22 07:06:07
最佳解答

首先要放程式碼至少縮排也要正確,不然根本看不懂

  1. 你要用Account('Sam')創建一個物件且帶入參數時
    在第二行要使用def __init__(self, name):而不是def init(self, name)
    而且宣告後你要儲存到變數,使用bank = Account('Sam')宣告創造一個物件

  2. Account('Sam').deposit()Account('Sam').withdraw()Account('Sam').balance都只是一直在創建新的物件,你沒有把內容存起來
    要改成

bank = Account('Sam')
bank.deposit()
bank.withdraw()
while bank.balance<0:
...
  1. return的部分你沒有拿變數去接就會有點多餘,可以把return的值拿掉直接去呼叫bank.balance

完整程式碼

class Account:
    def __init__(self,name):
        self.name=name
        self.balance=0
    def deposit(self):
        x=int(input('你要存入多少錢?'))
        while x<0:
            print('Error')
            break
        else:
            self.balance+=x
        return
    def withdraw(self):
        y=int(input('你要提取多少錢?'))
        while y<0:
            print('Error')
            break
        else:
            self.balance-=y
        return

bank = Account('Sam')
bank.deposit()
bank.withdraw()
while bank.balance<0:
    print('Error')
    break
else:
    print(bank.balance)
Itzy iT邦新手 5 級 ‧ 2021-05-22 09:34:40 檢舉

感謝你詳細的解縮,第一次發文,下次會記得縮排的

0
海綿寶寶
iT邦大神 1 級 ‧ 2021-05-22 08:29:25

https://ithelp.ithome.com.tw/upload/images/20210522/2000178794JfIH4UHc.png

Itzy iT邦新手 5 級 ‧ 2021-05-22 09:37:02 檢舉

謝謝提醒

我要發表回答

立即登入回答