Argument types and type hints
Every value has a type. These are the ones you know so far:
>>> type(2026)
<class 'int'>
>>> type(9.81)
<class 'float'>
>>> type("hello")
<class 'str'>
>>> type(5 == 5)
<class 'bool'>int is a whole number, float a number with a decimal point, str a string and bool one of True and False.
A function works only when its arguments are of a type it can handle. This one multiplies a price by an amount, so it needs two numbers. The second call gets its amount straight from input:
def total_price(price, amount):
print("Total:", price * amount)
total_price(2.5, 4)
amount = input("How many? ")
total_price(2.5, amount)
3Total: 10.0
How many? 3Traceback (most recent call last):
File "main.py", line 7, in <module>
total_price(2.5, amount)
~~~~~~~~~~~^^^^^^^^^^^^^
File "main.py", line 2, in total_price
print("Total:", price * amount)
~~~~~~^~~~~~~~
TypeError: can't multiply sequence by non-int of type 'float'input always returns a string, so in the second call amount is "3", not 3. Inside the function, price * amount becomes 2.5 * "3". A string can only be repeated a whole number of times, and 2.5 isn't one, so Python stops. The error shows up inside the function, but the mistake is in the call: a number the user types must go through int (or float) before it's passed on. With a whole-number price it would be even sneakier: 2 * "3" is the string "33", and the program would print a wrong total without any error at all.
Type hints
To tell the people who use your function which types it expects, you can add type hints. A hint goes after a parameter, with a colon, and the type of the return value goes after an arrow -> before the final colon:
def shout(text: str, marks: int) -> str:
return text.upper() + "!" * marks
print(shout("hello", 3))
HELLO!!!This says: text should be a string, marks a whole number, and the function returns a string. Hints make a function easier to use correctly, and code editors use them to warn about mistakes.
Python itself doesn't check them, though. A hint is only a hint: a call with other types still runs, and the function does whatever its code does with those values:
def double(number: int) -> int:
return number * 2
print(double(4))
print(double("ha"))
print(double(1.5))
8
haha
3.0From now on, the starter code of many tasks has type hints. They tell you what the checks will give your function and what they expect back.