Programming Flashcards
What are functions used for?
Encapsulating code to do a particular job.
They create modularity
Promote good variable scoping and crearer control flow.
What is an argument of a function?
The bit in brackets
‘def function(argument):’
A function can have many arguments
What is the scope of a variable
The area of the code from which the variable can be used. Global variable have global scope (can be used anywhere), but function declared in a module can only be used in that module unless they are passed into another function as an argument.
Unknown and unlimited arguments
‘*args’ is passed into a function as the argument to represent an unknown number of arguments.
‘**kwargs’ is passed into a function as the argument to represent key work arguments, e.g. “conf.xml”. These arguments are accessed by their key rather than position
Pep8
PEP8 is a general style guide for commenting
PEP257
PEP257 specifies docstrings that describe functions and modules
RegEx characters
., ^, $, *, +, ?, []
. -Matches any characters except new line
^ -Matches the start of a string and immediately after new line
$ -Matches end of a string
* -Resulting RegEx matches 0 or more repetitions of given character(s)
+ -Resulting RegEx matches 1 or more repetitions of given character(s)
? -Resulting RegEx matches 0 or 1 repetition of given character(s) [not greedy]
[] -Used to indicate a set of characters in a set . E.g. [0-9A-Fa-f]
Environment variables
import time
print(time.gmtime())
the gmtime bit is an environment variable
Scripts - Inline direct execution
- Start to end execution
- Threads are created and managed per run or job
- The route through the program is largely predetermined and independent of other programs
- Idempotent programs – output should be reproducible (except for intentional randomness) with the same input
Asynchronous execution
- Asynchronous jobs are run from a queue and don’t have to be executed in the order they occur
- Crucial for automation
- This can improve load management by reducing bottlenecks although can create concurrency issues
Example of asynchronous event driven architecture
Websites use this
Flask
Python Path
Environment variable where additional modules are stored - pip installs to here.
Module used to schedule commands for a specific time
Sched module
What is ‘@app.route(“/home”)’
Code for flsk to show code run when the /home page of your website is run
Restful API calls
Using API key with a url to use data from a website in a program.
Data usually received in a .json file, and relevant parts can be taken from this.
Software reliability - Defensive programming
Used for edge cases to stop program crashing
Software reliability - Exceptions
An exception is raised when one one of these errors occurs:
IndexError I ValueError I EOFError I AssertionError I SyntaxError I
IndentationError I KeyboardInterrupt
or you can define your own exceptions
Try-except (try-catch)
The try: … except: statement attempts to run code, but if it would raise an exception (crash the program), the code below except is executed instead
try … except … finally
The try: … except: … finally: overrides all error handling as final block. The code under ‘finally’ will run regardless of any raised exceptions.
‘raise’ keyword
To raise an exception in your code use the keyword raise - this is beneficial for defensive programming.
Keyword for unit testing in python
'assert' assert function(“test”) == “test result”
try: tests() except AssertionError as message: print(message) game_play()
assert “rat” in word_lookup(“tar”), “word_lookup: FAILED“
Logging
• Log files keep a log of system activity
• Like a ledger they are immutable
• If something is created and then deleted the live system should have no record of it. However, the log should retain the update record
showing the existence of something for that period
- Logs record a persistent history of the system
• Log files have two main uses:
- Tracing errors; An error log
- Recording system events; A system log
Slicing a string string = "hello" a = string[1:3] b = string[0:6:2] a =... b =...
string = "hello there" a = string[1:3] b = string[0:6:2] a = "el" b = "hlo" (stride = 2)
Dictionaries
A dictionary behaves like a list, but it can be ’indexed’ by
arbitrary variables. (Is like JSON)
D = { ’ dracula ’ : 18 , ’a ’ : 1113 , ’ mystery ’ : 6}
Order of keys and values
- If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are
called with no intervening modifications to the dictionary- then the lists will directly correspond
- This allows the creation of (value, key) pairs using zip(): pairs = zip(d.values(), d.keys())
zip function
zips 2 lists together to create a list of tuple pairs of items of the same index from either list. Only as long as the shorter list.
making dictionaries with zip() and dict()
zip together a list of keys and a list of values, then dict(the zip) to make it into a dictionary.
How would you increment the value of one key? (‘dracula’)
D [’dracula’] += 1
How would you add a new item to the dictionary? (‘stake’)
D [’stake’] = 1
How would you check whether a key exists?
’ dracula ’ in D
True
»> ’ coffin ’ in D
False
How would you remove a key-value pair?
Same as list but key instead of index -
D.pop(‘mystery’)
How is hashing used in a dictionary?
The keys are hashed and the hash identifies each key
When to use dictionary/list
Use lists when there is a natural order to the keys/indices,
but dictionaries when there is no particular order
Immutable vs mutable
Immutable variables are not changed in place (memory location), while
mutable variables are changed in place
Tuples
- Immutable sequences
* Automatically packed and unpacked on assignment
when is ‘a is b’ true
when a and b hold the same position in memory
a = “hello”
b = “hello”
a is b =…
a == b =…
a = “hello”
b = “hello”
a is b = False
a == b = True
a = 20 b = 20 c = 500 d = 500 a is b =... a == b =... c is d =... c == d =...
a = 20 b = 20 c = 500 d = 500 a is b = True (since 20 < 256) a == b = True c is d = False c == d = True
What is recursion?
When something is defined in terms of itself (calls itself from within)
Needs a base case to escape the loop when a certain condition is met. At each recursion we get closer to this case.
What make a function a first class object?
A function is a first class object because you can • Store functions in collections • Use functions as arguments to other functions • Use functions as return values of other functions • Create new functions from preexisting functions at run-time
reduce — accumulating a result from a list
reduce applies the function of two arguments cumulatively to the items in the sequence S, resulting in a single value. If initial is supplied it is placed before the other items in the sequence.
- reduce(function, sequence) reduces the sequence cumulatively to a scalar result.
reduce( lambda x , y : x + y , [1 , 2 , 3 , 4 , 5])
= 15
(Computes ((((1 + 2) + 3) + 4) + 5))
map function
• map(function, sequence [sequence, sequence, ...]) applies function to each item in sequence (or sequences)
filter function
• filter(function, sequence) returns the list comprising the items in sequence for which function returned True. (Same as our sieve.)
Insertion sort
Build a new list from the old one inserting each element in the correct
place
Takes about N^2 operations
Useful for small lists
Bubble sort
Go through the list swapping pairs of adjacent elements that are out of order; repeat until list is sorted On average takes about N 2 operations. Not practical - insertion better
Shell sort
- Sort pairs of elements far apart from each other.
- Progressively reduce the gap between elements to be compared.
- This can move out-of-order elements into position faster than neighbour exchange
Merge sort
divide the list into rough halves, sort each half and merge the results
on average about Nlog2(N) operations
Suitable for sorting very large lists which must be stored offline
Can be implemented in-place, but complicated and not fast
Python standard sort
Standard sort is list method that sorts in-place
The ‘sorted’ function returns a copy of the sorted list
> S = sorted ( L )
Software Development Lifecycle (7 steps)
1) Planning - resourcing and setting up the environment
2) Requirements engineering - fleshing out the technical requirements
3) Design + prototype - does it work with test examples
4) Software development - writing production software
5) Testing - providing tests to demonstrate functionality
6) Deployment - publish and run the software in the wild
7) Operation and maintenance - upkeep
What is a python package
• A Python package is just a directory containing python modules • Python provides a module namespace within packages - package.module • Python also provide 'setuptools' and 'distutils' to help configure, build and distribute coherent package resources
__init__.py package
- Necessary for package to be recognised
- Initialise any code for the package and set __all__ variables
- Often empty for basic projects