POP77001 Computer Programming for Social Scientists
if)while, for)len())TypeError)ifif - defines condition under which some code is executed
if - elseif - else - defines both condition under which some code is executed and alternative code to execute
if - elif - elseif - elif - ... - else - defines both condition under which some code is executed and several alternativesif <boolean_expression>:
<some_code>
elif <boolean_expression>:
<some_other_code>
...
...
else:
<some_more_code>
<expr1> if <test> else <expr2>
whilewhile - defines a condition under which some code (loop body) is executed repeatedlywhile <boolean_expression>:
<some_code>
forfor - defines elements and sequence over which some code is executed iterativelyfor <element> in <sequence>:
<some_code>
range() Functionrange() function generates arithmetic progressions and is essential in for loops.range() is a generator function.range(start, stop[, step])
range() Function: Examples__iter__ method, which return iterator.range()).zip() function provides a convenient way of iterating over several sequences simultaneously.keys() - keys.values() - values.items() - key-value pairs.break and continuebreak - terminates the loop in which it is containedcontinue - exits the iteration of a loop in which it is contained[<expr> for <elem> in <iterable>]
[<expr> for <elem> in <iterable> if <test>]
[<expr> for <elem1> in <iterable1> for <elem2> in <iterable2>]
{<expr> for <elem> in <iterable> if <test>}
{<key>: <value> for <elem1>, <elem2> in <iterable> if <test>}
break and continue to shorten iterations.len(), range(), zip().def statement.help()).def <function_name>(arg_1, arg_2, ..., arg_n):
"""<docstring>"""
<function_body>
return statement is encounteredreturnNone if no return statement<function_name>(arg_1, arg_2, ...)
* in function definition collects unmatched position arguments into a tuple.** collects keyword arguments into a dictionary.local to the function, if a variable is assigned inside defnonlocal to nested function, if a variable is assigned in an enclosing defglobal to the file (module), when a variable is assigned outside all defslambda expression.lambda arg_1, arg_2,... arg_n: <some_expression>
[-inf, 0.0, 0.6931471805599453, 1.0986122886681098, 1.3862943611198906, 1.6094379124341003, 1.791759469228055, 1.9459101490553132, 2.0794415416798357, 2.1972245773362196]
.py file with Python definitions and statements.import statement.import <module_name>
<module_name>.<object_name>
import <module_name> as <new_name>
<new_name>.<object_name>
from <module_name> import <object_name>
<object_name>
| Module | Description |
|---|---|
datetime |
Date and time types |
math |
Mathematical functions |
random |
Random numbers generation |
statistics |
Statistical functions |
os.path |
Pathname manipulations |
re |
Regular expressions |
pdb |
Python Debugger |
timeit |
Measure execution time of small code snippets |
csv |
CSV file reading and writing |
pickle |
Python object serialization (backup) |