How to accept the input of both int and float types?

后端 未结 4 1483
广开言路
广开言路 2021-01-21 09:18

I am making a currency converter. How do I get python to accept both integer and float?

This is how I did it:

def aud_brl(amount,From,to):
    ER = 0.421         


        
4条回答
  •  南方客
    南方客 (楼主)
    2021-01-21 10:18

    I'm really hoping I'm not completely misunderstanding the question but here I go.

    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()
    

    (I made a few changes as well for the sake of neatness, I hope you don't mind <3)

提交回复
热议问题