You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: lecture3.md
+73-1Lines changed: 73 additions & 1 deletion
Original file line number
Diff line number
Diff line change
@@ -161,11 +161,83 @@ print(res)
161
161
## More on Functions
162
162
[Code](day3/functions.py)
163
163
164
-
### Keyword Arguments
164
+
### Keyword Arguments and Positional Arguments
165
+
- A function can have two types of arguments: ones with default values and those without it.
166
+
- The arguments which have a default value are termed as `keyword arguments` and required ones are `positional arguments`.
167
+
- These arguments should always be the last ones, i.e. All the *required (positional) arguments go first*. They are then *followed by the optional keyword arguments*.
168
+
- Arguments without defaults are required otherwise you get a syntax error.
169
+
- You can pass in none, some or all of the keyword arguments.
170
+
- You can pass in parameters by keyword (name defined for argument).
165
171
172
+
<details>
173
+
<summary>
174
+
Function with keyword arguments (code)
175
+
</summary>
176
+
177
+
```py
178
+
# for eg the print function we use has 'sep' as a keyword argument which is '\n' by default
179
+
180
+
# below is also a way you can document your function using docstrings
181
+
defdistance_travelled(t, u=0, g=9.81):
182
+
"""
183
+
Function distance_travelled calculates the distance travelled by an object
184
+
with initial speed u, in a time interval of t, where acceleration due to gravity is g
185
+
186
+
input: t (time taken), u (initial speed) g (acceleration due to gravity)
187
+
output: distance travelled
188
+
189
+
Example:
190
+
>>> distance_travelled(1.0)
191
+
192
+
4.905
193
+
"""
194
+
d = u*t +0.5* g * t**2
195
+
return d
196
+
197
+
print(distance_travelled(2.0))
198
+
print(distance_travelled(2.0, u=1.0))
199
+
print(distance_travelled(2.0, g=9.7))
200
+
print(distance_travelled(g=9.7, t=2.0))
201
+
```
202
+
203
+
</details>
166
204
167
205
### Function scope
168
206
207
+
```py
208
+
# scope inside a function is different than the one outside it
209
+
# inside function scope, you can access the outer scope variables but cannot change them
210
+
211
+
defset_name(input_name):
212
+
name = input_name
213
+
print(f"Name inside the function: {name}")
214
+
215
+
set_name("Scaler")
216
+
# print(name) # NameError: this variable is not defined
217
+
```
218
+
219
+
### Exercise
220
+
221
+
<details>
222
+
<summary>
223
+
Guess output of the code
224
+
</summary>
225
+
226
+
```py
227
+
# Exercise: What should be the output for this piece of code?
228
+
# NEVER USE ARGUMENTS WITH LISTS AS DEFAULT VALUES!!!
0 commit comments