Go to the RMD, PDF, or HTML version of this file. Go back to Python Code Examples Repository (bookdown site) or the pyfan Package (API).
There are parameters of a function, depending on the parameter type, execute the program differently. If integer, behave one way if string behave in another way.
# define the function
def get_speckey_dict(gn_speckey=None):
if isinstance(gn_speckey, str):
print(f'{gn_speckey=} is a string')
elif isinstance(gn_speckey, int):
print(f'{gn_speckey=} is an integer')
else:
raise TypeError(f'{gn_speckey=} was not a string or an integer')
# Call function with integer
get_speckey_dict(1)
# Call function with string
## gn_speckey=1 is an integer
get_speckey_dict('abc')
# Call function with a list
## gn_speckey='abc' is a string
try:
get_speckey_dict(['abc'])
except TypeError as e:
print(f'Exception{e=}')
## Exceptione=TypeError("gn_speckey=['abc'] was not a string or an integer")
There is a function that takes a string or an integer between certain values. Execute if either of these two conditions are satisfied, do not if neither is satisfied. Below, print if string or an int between 1 and 11.
# condition check function
def check_condition(gn_invoke_set):
bl_is_str = isinstance(gn_invoke_set, str)
bl_is_int = isinstance(gn_invoke_set, int)
if bl_is_int:
bl_between = (gn_invoke_set >= 1 and gn_invoke_set <= 11)
else:
bl_between = False
if bl_between or bl_is_str:
print(f'{gn_invoke_set=}')
else:
print(f'{gn_invoke_set=} is not string or an integer between 1 and 11')
# call with string or integer
check_condition('string')
## gn_invoke_set='string'
check_condition(11)
## gn_invoke_set=11
check_condition(1)
## gn_invoke_set=1
check_condition(199)
## gn_invoke_set=199 is not string or an integer between 1 and 11
check_condition(['abc'])
## gn_invoke_set=['abc'] is not string or an integer between 1 and 11