-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy path11_args.py
More file actions
76 lines (54 loc) · 1.83 KB
/
11_args.py
File metadata and controls
76 lines (54 loc) · 1.83 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
74
75
76
# 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.
def f1(arg1, arg2):
return 1 + 2
print(f1(1, 2))
# Write a function f2 that takes any number of integer arguments and returns the
# sum.
# Note: Google for "python arbitrary arguments" and look for "*args"
def f2(*arg):
result = 0
for args in arg:
result = result + args
return result
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(arg1, arg2=1):
return arg1 + arg2
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(a, b="Null"):
return "key: \"a\", value: \"b\""
# Should print
# key: a, value: 12
# key: b, value: 30
print(f4(a=12, b=30))
# Should print
# key: city, value: Berkeley
# key: population, value: 121240
# key: founded, value: "March 23, 1868"
#print(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)