Code Explanation:
1. Importing Union from typing
from typing import Union
Union is used in type hints to indicate that a value can be more than one type.
It's part of Python's typing module, which provides support for type annotations.
2. Defining the Function with Type Hints
def stringify(val: Union[int, float, str]) -> str:
val: Union[int, float, str] means the function accepts a value that can be either:
an int (e.g., 5),
a float (e.g., 3.14),
or a str (e.g., "hello").
-> str means the function will return a str.
3. Converting the Value to String
return str(val)
The built-in str() function converts any supported type to a string.
Example: str(3.14) → "3.14"
4. Calling the Function and Printing the Result
print(stringify(3.14))
3.14 is a float, which is allowed by the function.
The function converts it to the string "3.14", and print displays it.
Output:
3.14
.png)

0 Comments:
Post a Comment