如何在python中显示函数的输出?

2024-05-29 07:43:08 发布

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

我试图制作一个简单的转换程序,但是输出结果要么很奇怪,要么根本没有。我该如何解决这个问题?这是我的密码

#crypto = [Bitcoin, Ethereum, XRP, Litecoin]
bitcoin = [1, 40.19, 38284.22, 168.73]
ethereum = [.025, 1, 951.99, 4.20]
xrp = [.000026, .001, 1, .003]
litecoin = [.0058, .231, 223.81, 1]

def crypto2Crypto(x,y,w):
    if(x == "BE"):
        w =+ (y * bitcoin[1])
    if(x == "XL"):
        y * xrp[3]
    if(x == "EB"):
        y * ethereum[0]
    if(x == "LX"):
        y * litecoin[2]

def main():
    print("Welcome to the Cryptocurrency exchange!")
    conversion = input('"What will you be converting today? B = Bitcoin, E = Ethereum, X = XRP, Litecoin = L. Please give an exchange with the following syntax crypto1crypto2, ex. type "BE" for Bitcoin to Ethereum."')
    amountOfCurrency = float(input("How much do you have of " + conversion[0] + " ?"))
    w = crypto2Crypto(conversion,amountOfCurrency,0)
    print(w)
main()

Tags: ifmaindefbebitcoinprintethereumconversion
2条回答

将其附加到crypto2Crypto函数的末尾

return w 

不确定w是否是您需要的,但返回您需要的

三个问题

  1. =+运算符(是,复数)与+=运算符不同

    • 分配(=

      >>> a = 2
      >>> a =+ 1
      >>> a
      1
      

      为什么??因为a =+ 1变成了a = +1a = 1

    • 扩充赋值(+=

      >>> a = 2
      >>> a += 1
      >>> a
      3
      

      为什么??因为a += 1变成了a = a + 1a = 2 + 1a = 3。更多关于扩充赋值here

  2. 如果您自己不从函数返回某些值,Python将自动使其返回None。因此,您应该向crypto2Crypto添加一个return语句。这已在下一节的解决方案中显示

  3. 二进制浮点数(Python的float类型,在main中用于获取amountOfCurrency的值的类型)及其算术不准确。有关详细信息,请阅读Python教程的chapter 15

解决方案

crypto2Crypto函数更改为:

def crypto2Crypto(x, y, w):
    if x == "BE":
        w += (y * bitcoin[1])
    if x == "XL":
        w += (y * xrp[3])
    if x == "EB":
        w += (y * ethereum[0])
    if x == "LX":
        w += (y * litecoin[2])

    return w

至于浮点的奇怪之处,您可以使用内置的^{}函数四舍五入到所需的小数位数

相关问题 更多 >

    热门问题