Skip to content

Commit 6b42853

Browse files
add *args and **kwargs examples
1 parent 90e3c4b commit 6b42853

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

Diff for: random_examples.py

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
def add(*args):
2+
"""
3+
This shows one use of * in Python: it indicates this function takes in non-key argument and a variable length of arguments
4+
:param args:
5+
:return:
6+
"""
7+
return sum(args)
8+
9+
10+
print(add(1, 2, 3, 4, 5))
11+
12+
13+
def print_food(**kwargs):
14+
"""
15+
Here double asterisk( ** ) is also used as **kwargs, the double asterisks allow passing keyword argument.
16+
This special symbol is used to pass a keyword arguments and variable-length argument list.
17+
18+
Keyword arguments (or named arguments) are values that, when passed into a function,
19+
are identifiable by specific parameter names.
20+
A keyword argument is preceded by a parameter and the assignment operator, = .
21+
22+
Keyword arguments can be likened to dictionaries in that they map a value to a keyword.
23+
:param kwargs:
24+
:return:
25+
"""
26+
for items in kwargs:
27+
print(f"{kwargs[items]} is a {items}")
28+
29+
30+
print(print_food(fruit ='cherry', vegetable ='potato', boy ='srikrishna'))

0 commit comments

Comments
 (0)