-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy path11_args.py
More file actions
73 lines (54 loc) · 1.96 KB
/
11_args.py
File metadata and controls
73 lines (54 loc) · 1.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# Experiment with positional arguments, arbitrary arguments, and keyword
# arguments.
# Write a function f1 that takes two integer positional arguments and returns
# the sum. This is what you'd consider to be a regular, normal function.
# * SOLUTIONS BELOW:
# * OPEN INTERPRETER && RUN: python3 11_args.py
def f1(n1, n2):
if(n1 or n2) != 0: return (n1 + n2)
print(f1(1, 2))
# Write a function f2 that takes any number of integer arguments and prints the
# sum.
# Note: Google for "python arbitrary arguments" and look for "*args"
def f2(*n): print(sum(n))
print(f2(1)) # Should print 1
print(f2(1, 3)) # Should print 4
print(f2(1, 4, -12)) # Should print -7
print(f2(7, 9, 1, 3, 4, 9, 0)) # Should print 33
a = [7, 6, 5, 4]
# How do you have to modify the f2 call below to make this work?
print(f2(*a)) # Should print 22
# Write a function f3 that accepts either one or two arguments. If one argument,
# it returns that value plus 1. If two arguments, it returns the sum of the
# arguments.
# Note: Google "python default arguments" for a hint.
def f3(param1, param2 = False):
if (param1 and param2): return param1 + param2
elif (param2) != True: return param1 + 1
print(f3(1, 2)) # Should print 3
print(f3(8)) # Should print 9
# Write a function f4 that accepts an arbitrary number of keyword arguments and
# prints out the keys and values like so:
#
# key: foo, value: bar
# key: baz, value: 12
#
# Note: Google "python keyword arguments".
def f4(**kwargs):
for key, value in kwargs.items():
print(F'|key| {key}, |value| {value}')
# Should print
# key: a, value: 12
# key: b, value: 30
f4(a=12, b=30)
# Should print
# key: city, value: Berkeley
# key: population, value: 121240
# key: founded, value: "March 23, 1868"
f4(city="Berkeley", population=121240, founded="March 23, 1868")
d = {
"monster": "goblin",
"hp": 3
}
# How do you have to modify the f4 call below to make this work?
f4(**d)