Reputation: 353
I have the following exercise:
Annotate with correct types the parameters and the return values of the functions, as well as of the variables, in the program in the other panel. For that, you only need to replace every occurrence of Any, except for the very first line, by an appropriate type.
Example: The first Any in line 3, i.e., n: Any, must be replaced by int. You can see that from the line 9.
While I understand the theory of type hints I don't get the exercise, most probably because I do not get at this point the use of Any. Furthermore the exercise is ambiguous, it says to replace every occurrence of Any.
If this is the case would the first line be:
def get_half(n : int) -> int:
return n/2
If so it does not work.
from typing import Any #do not edit this line
def get_half(n : Any) -> Any:
return n/2
def print_half(n : Any) -> Any:
print(n/2)
y = get_half(10)
print_half(20)
def is_present(s : Any, char : Any) -> Any:
found : Any = False
l : Any = len(s)
for i in range(0, l):
if s[i] == char:
found = True
return found
print(is_present("john", "h"))
Upvotes: 0
Views: 315
Reputation: 353
This is the correct solution thanks to your answers
This link was very useful
https://mypy-play.net/?mypy=latest&python=3.10
from typing import Any #do not edit this line
def get_half(n : int) -> float:
return n/2
def print_half(n : int) -> None:
print(n/2)
y = get_half(10)
print_half(20)
def is_present(s : str, char : str) -> bool:
found : bool = False
l : int = len(s)
for i in range(0, l):
if s[i] == char:
found = True
return found
print(is_present("john", "h"))
Upvotes: 1
Reputation: 709
The first any is an int
like the example said def get_half(n : int) -> Any:
and the return value will differ depending if your exercise is for python 2 or 3.
Python2: def get_half(n : int) -> int:
Python3: def get_half(n : int) -> float:
The reason for this is that Python 2 always returns an int
if you divide and int
with an int
. int/int=int
And Python 3 uses "true division" and therefor returns an float
. int/int=float
For more info see: https://en.wikibooks.org/wiki/Python_Programming/Operators
Upvotes: 0