Lab 2 Python Intro
The in operator quickly checks if a given value is in a list (or another iterable, including strings).
my_list = [1, 2, 3, 4, 5] >>> 2 in my_list True "a" in "aeiou" true
Parts of a string can be accessed using slicing, which is indicated by square brackets [ ]. Slicing syntax is [start:stop:step]. The parameters start and stop default to the beginning and end of the string, respectively. The parameter step defaults to 1.
str1="My string" str1[::2] == "M tig" The index for the first position of a string is 0
Common list methods (functions) include append(), insert(), remove(), and pop()
> my_list = [1, 2] # Create a simple list of two integers. >>> my_list.append(4) # Append the integer 4 to the end. >>> my_list.insert(2, 3) # Insert at location 2 the value 3. >>> my_list [1, 2, 3, 4] >>> my_list.remove(3) # Remove 3 from the list. >>> my_list.pop() # Remove (and return) the last entry. 4 >>> my_list [1, 2]
Tuples use parentheses, lists use brackets, both sets and dictionaries use braces
>> {c[0]:c for c in colors} {'r': 'red', 'b': 'blue', 'y': 'yellow'}
A list comprehension uses for loop syntax between square brackets to create a list. This is a powerful, efficient way to build lists. The code is concise and runs quickly
>>> [float(n) for n in range(5)] [0.0, 1.0, 2.0, 3.0, 4.0]
The following loop and list comprehension produce the same list, but the list comprehension takes only about two-thirds the time to execute.
for i in range(5): ... loop_output.append(i**2) list_output = [i**2 for i in range(5)]
x,y = math(4,5) math was a function I defined in a python file I was working on at the time, it is not the math module, poor choice of name on my part here
xy=math(4,5) this one is a tuple unlike the other side of the card
Like a set, a Python dict (dictionary) is an unordered data type. A dictionary stores key-value pairs, called items. The values of a dictionary are indexed by its keys. Dictionaries are initialized with curly braces, colons, and commas. Use dict() or {} to create an empty dictionary
# Add a value indexed by 'science' and delete the 'business' keypair. >>> my_dictionary["science"] = 6284 >>> my_dictionary.pop("business") # Use 'pop' or 'popitem' to remove. 4121 dictionaries include methods such as .keys and .values
On rare occasion, it is necessary to define a function without knowing exactly what the parameters will be like or how many there will be. This is usually done by defining the function with the parameters *args and **kwargs. Here *args is a list of the positional arguments and **kwargs is a dictionary mapping the keywords to their argument. This is the most general form of a function definition.
>>> def report(*args, **kwargs): ... for i, arg in enumerate(args): ... print("Argument " + str(i) + ":", arg) ... for key in kwargs: ... print("Keyword", key, "-->", kwargs[key]) ... >>> report("TK", 421, exceptional=False, missing=True) Argument 0: TK Argument 1: 421 Keyword exceptional --> False Keyword missing --> True See https://docs.python.org/3.6/tutorial/controlflow.html for more on this topic the default sep for print is " "
>>> for i, color in enumerate(colors): ... print(i, color)
>>> for item in sorted(colors): ... print(item, end=' ')
>>> vowels = "aeiou" >>> colors = ["red", "yellow", "white", "blue", "purple"]
>>> for letter, word in zip(vowels, colors): ... print(letter, word)
my_list = [10, 20, 30, 40, 50] >>> my_list[0] = -1 >>> my_list[3:] = [8, 9] Note we can use slicing syntax to reference a portion of an array, and then define it to be equal to something of different size, so long as the new definition still results in an array syntactically legal size.
>>> print(my_list) [-1, 20, 30, 8, 9]
>>> colors = ["red", "green", "blue", "yellow"] >>> for entry in colors: ... print(entry + "!")
A for loop iterates over the items in any iterable. Iterables include (but are not limited to) strings, lists, sets, and dictionaries. (and tuples)
>>> def typewriter(func): ... """Decorator for printing the type of output a function returns""" ... def wrapper(*args, **kwargs): ... output = func(*args, **kwargs) # Call the decorated function. ... print("output type:", type(output)) # Process before finishing. ... return output # Return the function output. ... return wrapper
Apply a decorator to a function by tagging the function's denition with an @ symbol and the decorator name >>> @typewriter ... def combine(a, b, c): ... return a*b // c This is equivalent to placing the following code after the function's definition combine = typewriter(combine)
The return statement instantly ends the function call and passes the return value to the function caller. However, functions are not required to have a return statement. A function without a return statement implicitly returns the Python constant None, which is similar to the special value null of many other languages. Calling print() at the end of a function does not cause a function to return any values.
If you have any intention of using the results of a function, use a return statement.
In this and subsequent labs, the triple brackets >>> indicate that the given code is being executed one line at a time via the Python interpreter.
Much of the subsequent material has been taken from the materials provided at https://acme.byu.edu/2021-2022-materials
Some ways to break out of a double loop include
Put the loops into a function, and return from the function to break the loops. This is unsatisfying because the loops might not be a natural place to refactor into a new function, and maybe you need access to other locals during the loops. Raise an exception and catch it outside the double loop. This is using exceptions as a form of goto. There's no exceptional condition here, you're just taking advantage of exceptions' action at a distance. Use boolean variables to note that the loop is done, and check the variable in the outer loop to execute a second break. This is a low-tech solution, and may be right for some cases, but is mostly just extra noise and bookkeeping. Turn them into a single loop somehow https://nedbatchelder.com/blog/201608/breaking_out_of_two_loops.html
Python files are called modules and they are identified by the .py file extension. A module can define functions, classes, and variables.
Python if __name__ == __main__ Explained with Code Examples (freecodecamp.org)
The keyword lambda is a shortcut for creating one-line functions. For example, the polynomials f(x) = 6x 3 + 4x 2 − x + 3 and g(x, y, z) = x + y 2 − z 3 can be dened as functions in one line each.
They can be defined as done previously or f = lambda x: 6*x**3 + 4*x**2 - x + 3 g = lambda x, y, z: x + y**2 - z**3
Explanation of the next card
We tag a function with a decorator that takes an argument and returns a decorator. That contained decorator returns a function wrapper, which in this case calls the original function once for each time indicated to the top level decorator. Because the inner function contains the print command, the contents are printed once for each time indicated to the top level decorator
There are two additional useful statements to use inside of loops: 1. break manually exits the loop, regardless of which iteration the loop is on or if the termination condition is met. 2. continue skips the current iteration and returns to the top of the loop block if the termination condition is still not met.
break exits the loop continue skips the current iteration of the loop
Arguments are passed to functions based on position or name, and positional arguments must be defined before named arguments. For example, a and b must come before c in the function definition of pad(). Examine the following code blocks demonstrating how positional and named arguments are used to call a function.
def pad(c=0, a, b): print(a, b, c) SyntaxError: non-default argument follows default argument Parameters not given an explicit value can still be named for example printnumbers(b=5,c=2,a=7) is valid and will output 7,5,2
Function decorators can also be customized with arguments. This requires another level of nesting:
def repeat(times): ...: """Decorator for calling a function several times.""" ...: def decorator(func): ...: def wrapper(*args, **kwargs): ...: for _ in range(times): ...: output = func(*args, **kwargs) ...: return output ...: return wrapper ...: return decorator >>> @repeat(3) ... def hello_world(): ... print("Hello, world!") >>> hello_world() Hello, world! Hello, world! Hello, world!
zip(x,y): Joins multiple sequences so they can be iterated over simultaneously. This is not concatenation, it joins itemwise, and truncates to the length of the shortest iterable being zipped The output is not a tuple, it's the respective data types of the objects form x and y separated by spaces
enumerate(a): Yields both a count and a value from the sequence. Typically used to get both the index of an item and the actual item simultaneously.
A function can return multiple values
example def math(x, y): return x+y, x-y
It is also possible to specify default values for a function's parameters.
example def printnumbers(a,b,c=0): print(a,b,c) prints out the parameters a,b, and c with c defaulting to 0
To define a function, use the def keyword followed by the function name, a parenthesized list of parameters, and a colon. Then indent the function body using exactly four spaces.
example def subtract(x, y) return x-y
Two variables can be assigned at once
example x, y = 2, 4
A Python set is an unordered collection of distinct objects. Objects can be added to or removed from a set after its creation. Initialize a set with curly braces { } and separate the values by commas, or use set() to create an empty set. Like mathematical sets, Python sets have operations such as union, intersection, difference, and symmetric difference
includes methods such as .add .discard .intersection .difference
As far as data access goes, lists are like dictionaries whose keys are the integers 0, 1, . . . , n − 1, where n is the number of items in the list. The keys of a dictionary need not be integers, but they must be immutable, which means that they must be objects that cannot be modied after creation. We will discuss mutability more thoroughly in the Standard Library lab.
integers, strings, and tuples are immutable while lists and sets and dictionaries (iirc) are mutable" Insert commentary about how python sometimes does something pointer-like under the hood in the case of mutable data types
help()
opens the help utility, then type the name of whatever you want help with
In addition, Python has some very useful built-in functions that can be used in conjunction with the for statement:
range(start, stop, step): Produces a sequence of integers, following slicing syntax. If only one argument is specied, it produces a sequence of integers from 0 to the argument, incrementing by one. This function is used very often. range(1,11) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
if condition: elif condition2: else:
sample condition x<2 if x<2 : This space is acceptable, but unnecessary and thus probably shouldn't be there
Casting numbers as other number types x = int(3.0) >>> y = float(3) >>> z = complex(3) >>> print(x, y, z) 3 3.0 (3+0j)
set([1, 2, 3, 4, 4]) {1, 2, 3, 4} >>> list({'a', 'a', 'b', 'b', 'c'}) ['a', 'c', 'b'] Cast other objects as strings. >>> str(['a', str(1), 'b', float(2)]) "['a', '1', 'b', 2.0]" >>>str(list(set([complex(float(3))]))) '[(3+0j)]'
reversed(somelist): Reverses the order of the iteration.
sorted(somelist): Returns a new list of sorted items that can then be used for iteration sorts with in ascending order with python's default ordering
Function decorators are functions that
take a function as input, and return another function, typically the same one that was passed in, but with some "decorations"
if __name__ == "__main__": Do something here
the if is outside a function and will always be run, but the subsequent code will only be run if the file is the "main one being run"
IPython supports object introspection whereas the regular python interpreter doesn't
to see the methods associated with an object type the object type followed immediately by a period and then press tab. To learn more about a specific method add a ? object.method?
Python also supports computations of complex numbers by pairing two numbers as the real and imaginary parts. Use the letter j, not i, for the imaginary part.
x=complex(10,10) y=5+5j