python 银行账户交易
Given a few transactions (deposit, withdrawal), and we have to compute the Net Amount of that bank account based on these transactions in Python.
给定几笔交易(存款,提款),我们必须根据这些交易在Python中计算该银行帐户的净额。
Example:
例:
Input:
Enter transactions: D 10000
Want to continue (Y for yes): Y
Enter transaction: W 5000
Want to continue (Y for yes): Y
Enter transaction: D 2000
Want to continue (Y for yes): Y
Enter transaction: W 100
Want to continue (Y for yes): N
Output:
Net amount: 6900
Logic:
逻辑:
For this program, we will input transactions (till user’s choice is "Y") with type ("D" for deposit and "W" for withdrawal) and the amount – for that we will computer it in an infinite loop while True:
对于此程序,我们将输入类型(“ D”代表存款,“ W”代表提款)和金额的交易(直到用户选择是“ Y”)和金额-为此,我们将在无限循环中将其计算为True:
Transactions will be like "D 2000" that means Deposit 2000, so there are two values needs to be extracted 1) "D" is the type of transaction and 2) 2000 is the amount to be deposited.
交易将类似于“ D 2000”,这表示存款2000,因此需要提取两个值1)“ D”是交易的类型,而2)2000是要存入的金额。
A transaction input will be string type- convert/split the values to the list which is delimited by the space. For this, we use string.split() method.
事务输入将是字符串类型-将值转换/分割到由空格分隔的列表。 为此,我们使用string.split()方法。
Now, the values will be in the list, the first value is the type – which is in string format and the second value is the amount – which is in also string format, we need to convert the amount in integer format. So we will convert its type (example code: amount = int(list[1])).
现在,这些值将在列表中,第一个值是类型-字符串格式,第二个值是数量-也是字符串格式,我们需要将数量转换为整数格式。 因此,我们将转换其类型(示例代码: amount = int(list [1]) )。
After that, based on the transaction type check the conditions and adding/subtracting the amount from the net amount.
之后,根据交易类型检查条件并从净额中减去/减去金额。
After that, ask for the user for the next transaction and check the weather, if the user’s choice is not "Y" or "y", break the loop and print the net amount.
之后,要求用户进行下一次交易并检查天气,如果用户选择的不是“ Y”或“ y”,则中断循环并打印净额。
Program:
程序:
# computes net bank amount based on the input
# "D" for deposit, "W" for withdrawal
# define a variable for main amount
net_amount = 0
while True:
# input the transaction
str = raw_input ("Enter transaction: ")
# get the value type and amount to the list
# seprated by space
transaction = str.split(" ")
# get the value of transaction type and amount
# in the separated variables
type = transaction [0]
amount = int (transaction [1])
if type=="D" or type=="d":
net_amount += amount
elif type=="W" or type=="w":
net_amount -= amount
else:
pass
#input choice
str = raw_input ("want to continue (Y for yes) : ")
if not (str[0] =="Y" or str[0] =="y") :
# break the loop
break
# print the net amount
print "Net amount: ", net_amount
Output
输出量
Enter transaction: D 10000
want to continue (Y for yes) : Y
Enter transaction: W 5000
want to continue (Y for yes) : Y
Enter transaction: D 2000
want to continue (Y for yes) : Y
Enter transaction: W 100
want to continue (Y for yes) : N
Net amount: 6900
python 银行账户交易