Last active
September 18, 2022 12:33
-
-
Save KianYang-Lee/e5d01048cdf1a22a5f59f9499d719d69 to your computer and use it in GitHub Desktop.
Contains code for the Medium article "Writing Functions that Accept Variable Length of Arguments in Python" (https://medium.com/@kianyang_lee/writing-functions-that-accept-variable-length-of-arguments-in-python-2c9e6408081a) and article "Understanding Keyword Arguments (**kwargs) in Python" (https://medium.com/@kianyang_lee/understanding-keyword…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def add_two_arguments(num_1: int, num_2: int) -> int: | |
return num_1 + num_2 | |
def add_three_arguments(num_1: int, num_2: int, num_3: int) -> int: | |
return num_1 + num_2 + num_3 | |
def add_arguments(*args) -> int: | |
sum = 0 | |
for arg in args: | |
sum += arg | |
print("Result of adding all arguments are: ", sum) | |
return sum | |
def multiply_sum_of_all_arguments_by_n_times(multiplier: int, *args) -> int: | |
sum = 0 | |
for arg in args: | |
sum += arg | |
multiplied_sum = sum * multiplier | |
print( | |
f"Result of adding all arguments and multiply the sum by {multiplier} are: {multiplied_sum}" | |
) | |
return multiplied_sum | |
def add_arguments_using_kwargs(**kwargs) -> int: | |
sum = 0 | |
for key, value in kwargs.items(): | |
print(f"Adding {key} variable with value: {value}") | |
sum += value | |
print("Result of adding all arguments are: ", sum) | |
return sum | |
def print_all(number_of_print_times: int = 2, **kwargs) -> None: | |
for i in range(1, number_of_print_times + 1): | |
print(f"Printing for round {i}") | |
for key, value in kwargs.items(): | |
print(f"Key: {key} - Value: {value}") | |
add_arguments(1, 2, 3, 4, 5, 6, 7) | |
add_arguments(1, 2, 3) | |
add_arguments_using_kwargs(first_arg=1, second_arg=2, third_arg=3) | |
print_all(local_fruit_in_malaysia="durian", capital_of_malaysia="Kuala Lumpur") | |
print_all( | |
local_fruit_in_malaysia="durian", | |
capital_of_malaysia="Kuala Lumpur", | |
number_of_print_times=1, | |
) | |
multiply_sum_of_all_arguments_by_n_times(2, 1, 2, 3) | |
multiply_sum_of_all_arguments_by_n_times(multiplier=2, 1, 2, 3) # this will throw SyntaxError |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment