通过函数获取用户输入

0 投票
5 回答
20374 浏览
提问于 2025-04-20 17:45

这是我的代码:

def bitcoin_to_usd(btc):
    amount = btc * 527
    print(amount)

btc = input("Input your Bitcoins amount: ")

bitcoin_to_usd(btc)

我想从用户那里获取比特币的数量,然后计算出它值多少美元。

但是这段代码让我输入的数字重复了。例如,如果你输入 2,它会返回 222222222222222222222222....,并没有进行计算。

我的Python版本是3.4.1,我在使用PyCharm。

有什么想法吗?

5 个回答

-1

在你定义的函数里面使用下面这一行代码:

amount = float(btc) * 527
0

你可以试试这个,没有参数的函数:

    def sum():
        return x+y
    x = int(input("Val of x"))
    y = int(input("Val of y"))
    print(sum())

或者你也可以试试这个,有参数的函数:

def sum(x,y):
       return x+y
x = int(input("Val of x"))
y = int(input("Val of y"))
print(sum(x,y))
0

你可以使用

btc = input("Input your Bitcoins amount: ")

def bitcoin_to_usd(btc):
    amount = btc * 527
    print(amount)


bitcoin_to_usd(btc)
0

在python3.x中,input这个函数返回的是一个字符串1,而不是数字。如果你想要一个数字,就需要把输入的字符串转换成浮点数或整数。

btc = float(input("Input your Bitcoins amount: "))

1这也解释了为什么结果是这样,字符串乘以一个整数会导致这个字符串重复那个次数。

2

你的代码没问题,只是你需要把输入的结果转换一下,因为输入返回的是字符串,而你需要的是数字。我们可以试试用 float 来处理小数类型的数据:

def bitcoin_to_usd(btc):
    amount = btc * 527
    print(amount)

btc = float( input("Input your Bitcoins amount: ") )

bitcoin_to_usd(btc)

撰写回答