函数返回格式

2024-10-01 04:59:19 发布

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

简单的ATM模拟练习-需要返回一些信息,包括字符串和整数,但是返回的是整行代码,而不仅仅是字符串和整数的组合

现金点代码

from SimpleCashPoint_v2 import cashpoint


print('\nTEST-EXAMPLE 1')

result = cashpoint('1234',3415.55)
print('\n---------\nRESULT:', result)
print('-' * 40, '\n')

cahspoint函数代码(在文件SimpleCashPoint_v2

elif trans_type == '2' : 
    withdraw = float(input('Amount to withdraw: '))
    result = ('\nYou have withdrawn ', withdraw, ' your remaining balance is ', (balance-withdraw),'£')

    return result

#我期望输出:

In[36]result

Out[36] You have withdrawn 10 your remaining balance is 50 £

我得到一个

In[36]result

Out[36]: ('\nYou have withdrawn ', 10, ' your remaining balance is ', 50, '£')

Tags: 字符串代码yourishave整数resultv2
2条回答

您可以替换:

result = ('\nYou have withdrawn ', withdraw, ' your remaining balance is ', (balance-withdraw),'£')

使用:

result = "\nYou have withdrawn {} your remaining balance is {} £".format(withdraw, balance-withdraw)

搜索字符串格式,例如https://realpython.com/python-string-formatting/

当你做结果的时候,你正在做一个元组

type(result)
<class 'tuple'>

所以我认为如果你把你的元素组合成一个字符串,它就可以工作了

一种非常天真的方法是:

withdraw = ...
result = "/nYou have withdrawn" + str(withdraw) + "your remaining balnce is" + str(balance-withdraw) + "$"
return result

相关问题 更多 >