如何接受int和float类型的输入? [英] How to accept the input of both int and float types?
问题描述
我正在制作货币转换器。如何使python接受整数和浮点数?
I am making a currency converter. How do I get python to accept both integer and float?
这就是我的方法:
def aud_brl(amount,From,to):
ER = 0.42108
if amount == int:
if From.strip() == 'aud' and to.strip() == 'brl':
ab = int(amount)/ER
print(ab)
elif From.strip() == 'brl' and to.strip() == 'aud':
ba = int(amount)*ER
print(ba)
if amount == float:
if From.strip() == 'aud' and to.strip() == 'brl':
ab = float(amount)/ER
print(ab)
elif From.strip() == 'brl' and to.strip() == 'aud':
ba = float(amount)*ER
print(ba)
def question():
amount = input("Amount: ")
From = input("From: ")
to = input("To: ")
if From == 'aud' or 'brl' and to == 'aud' or 'brl':
aud_brl(amount,From,to)
question()
我如何做的简单例子它:
Simple example of how I did it:
number = input("Enter a number: ")
if number == int:
print("integer")
if number == float:
print("float")
这两个不起作用。
推荐答案
我真的希望我是并没有完全误解这个问题,但我在这里。
I'm really hoping I'm not completely misunderstanding the question but here I go.
看起来你只想确保传入的值可以像浮动一样操作,无论是否输入是 3
或 4.79
例如,对吗?如果是这种情况,那么只需将输入转换为浮点数,然后再对其进行操作。以下是您修改后的代码:
It looks like you just want to make sure the value passed in can be operated upon like a float, regardless of whether the input is 3
or 4.79
for example, correct? If that's the case, then just cast the input as a float before operating on it. Here's your modified code:
def aud_brl(amount, From, to):
ER = 0.42108
if From.strip() == 'aud' and to.strip() == 'brl':
result = amount/ER
elif From.strip() == 'brl' and to.strip() == 'aud':
result = amount*ER
print(result)
def question():
amount = float(input("Amount: "))
From = input("From: ")
to = input("To: ")
if (From == 'aud' or From == 'brl') and (to == 'aud' or to == 'brl'):
aud_brl(amount, From, to)
question()
(为了整洁,我做了一些改动,我希望你不介意< ; 3)
(I made a few changes as well for the sake of neatness, I hope you don't mind <3)
这篇关于如何接受int和float类型的输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!