Python Forum

Full Version: Need help
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi, I'm a complete beginner

I try two versions and sending warnings. What is the problem?

1.

# 1USD= 0,8 Eur
def usd_to_eur(usd: int, euro: int) -> float: 
    return usd * euro
print(usd_to_eur(5,0.8))
Error:
Warning: Argument 2 to "usd_to_eur" has incompatible type "float"; expected "int" [arg-type]
2.

def usd_to_eur(usd: int) -> int:
    return usd * 0.8
print(int(usd_to_eur(80)))
Error:
Warning: Incompatible return value type (got "float", expected "int") [return-value]
There is no problem. The code does exactly what it was written to do.

In 1, you are using type annotations to tell python what type the arguments are expected to be. usd: int says the usd argument should be an int. euro: int says the euro argument should be an int. Then you call the function and pass an int to usd and a float to euro. You wrote code to tell python that euro is supposed to be an int, so it warns you when it is not.

In 2 you again run into a disagreement with what the code does, and what the type annotations say it should do. Your function is defined to return an int (-> int), but usd * 0.8 produces a float as a result. It doesn't matter that 80 * 0.8 == 10. The result does not matter. Python only looks at the operands. When you multiply an int by a float, the result is a float. Your told python that the function should return an int, so it warns you when it does not.
Deanhystad, thank you so much!

The first code is better then!

I apologize for the incorrectness of the post! Next time I will try to do it correctly!
And you should think about your type annotation