首页 > 解决方案 > 如何在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()

标签: pythonfunctionoutput

解决方案


三个问题

  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。更多关于增强任务在这里

  2. 如果你自己没有从函数中返回一些值,Python 会自动让它返回None。所以,你应该returncrypto2Crypto. 这已在下一节的解决方案中显示。

  3. 二进制浮点数(Python 的float类型,用于main获取 的值amountOfCurrency)及其算术不准确。有关详细信息,请阅读 Python 教程的第 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

至于浮点怪异,您可以使用内置round函数四舍五入到所需的小数位数。


推荐阅读