Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Need help
#1
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]
deanhystad write Nov-14-2023, 07:10 PM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply
#2
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.
Reply
#3
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!
Reply
#4
And you should think about your type annotation
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020