首页 > 解决方案 > 有人可以逐步分解他们如何获得此代码的输出吗?

问题描述

有人可以逐步分解他们如何获得此代码的输出吗?

余额 = 1000

def withdraw(current_balance,amount):
    current_balance = current_balance - amount
    print('Withdrawing money.')
    return current_balance

def deposit(current_balance,amount):
    current_balance = current_balance + amount
    print('Depositing money.') 
    return current_balance


balance = withdraw(balance,100)
balance = withdraw(balance,50)
balance = balance + 10 
balance = deposit(balance,100)
print(balance)

标签: python-3.x

解决方案


欢迎来到堆栈溢出!!

基于这个问题,我假设您是 Python 新手。所以让我解释一下,因为我曾经是编码和 Python 的新手。

# This is the starting balance
balance = 1000

# In Python a function is defined using the def keyword.
# Information can be passed to functions as parameter (e.g, current_balance).
#
def withdraw(current_balance, amount):
  # Note the minus sign, so funds are being
  # withdrawn from the balance
  current_balance = current_balance - amount
  print('Withdrawing money.')
  # returns the new balance
  return current_balance

def deposit(current_balance,amount):
  # Note the plus sign, so funds are being
  # added to the balance
  current_balance = current_balance + amount
  print('Depositing money.') 
  # returns the new balance
  return current_balance

# withdraws funds from the original balance
# 900 = withdraw(1000, 100)
balance = withdraw(balance,100)

# withdraws funds from the previous balance
# 850 = withdraw(900, 50)
balance = withdraw(balance,50)

# adds funds to the previous balance 
# 860 = 850 + 10
balance = balance + 10 

# deposit funds to the previous balance 
# 960 = deposit(860, 100)
balance = deposit(balance,100)

# prints the current balance 
print(balance)
# output
960

推荐阅读