1/90
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced | Call with Kai |
|---|
No analytics yet
Send a link to your students to track their progress
#Comment
What is the syntax of a single line comment?
“““Comment”””
What is the syntax of a multi-line comment?
The variable must be cast to a string
str()
What must be done to a variable to be used in string concatenation?
It seemed like a good idea at the time... It seemed like a good idea at the time... It seemed like a good idea at the time... ?
The comma will provide a space between whatever is printed.
The question mark is a string.
The \n moves the cursor to next line.
lyric = 'It seemed like a good idea at the time...'
print(lyric,lyric,lyric,end ='?\n')
What will this output?
Strings are immutable in Python. Once a string is created it cannot be modified, but it can be replaced.
Are string mutable or immutable in Python?
x, y = y, x
What is the syntax of swapping the value of 2 variables?
len(string)
“len” starts counting at 1 not zero
What is the syntax of checking the length of a string in python?
10 // 3
Output = 3
What is the syntax of integer division in python?
In Python integer division (also known as floor division) rounds down.
For negative numbers, it still rounds down (towards negative infinity):
print(-7 // 2)
Output: -4
In Python does integer division round up or down?
empty_list = []
or
empty_list = list()
What is the syntax of creating an empty list in python?
In the console
Where does the output of the code display?
print(f"|{123:10}|")How do I achieve the following output?
# Output: | 123| (right-justified by default)print(f"|{myNum:10}|")How do I achieve the following output?
myNum = 123# Output: | 123| (right-justified by default)print(f"|{myNum:<10}|")How do I achieve the following output?
myNum = 123# Output: |123 |print(f"|{myNum:^10}|")How do I achieve the following output?
myNum = 123# Output: | 123 |print(f"|{myNum:>10}|")How do I achieve the following output?
myNum = 123# Output: | 123|print(f"|{myNum:05}|")How do I achieve the following output?
myNum = 123# Output: |00123| ( zero padding )import math
print(f"|{math.pi:.2f}|") How do I achieve the following output?
# Output: |3.14| ( precision)print(f"|{255:x}|")How do I achieve the following output?
# Output: |ff| ( hexadecimal)print(f"|{0.75:.2%}|")How do I achieve the following output?
# Output: |75.00%| ( percentage conversion)1 2
2 1
x, y = 1, 2
print(x, y)
x, y = y, x
print(x, y)
What will this output?
This is short for Local->Enclosed->Global->Builtin and defines the path the interpreter searches for variables for resolution. If the variable doesn't exist locally, it looks in the enclosing scope ( within the function ), then global space, and finally built-in environment variables.
What is the LEGB rule?
1
2
2
x = 1
print(x)
def change():
global x
x = 2
print(x)
change()
print(x)
What will this output?
1
2
1
x = 1
print(x)
def change():
x = 2
print(x)
change()
print(x)
What will this output?
A local variable can be read in a nested function, but it cannot be modified in a nested function.
Why does the following code throw an error in python?
def func():
x = 1
def nested_func():
x += 1
// is floor division
5 // 3 = 1
5.0 // 3 = 1.0
What is the result of x = 5 // 3?
x**y
What is python’s equivalent of C#’s Math.Pow(x, y)
var = expression_true if condition else expression_false
Example: x = y if r < 0 else z
What is python’s equivalent of C#’s ternary expression?
Example: x = r < 0 ? y : z;
x = 1
match x:
case 1:
print("x is 1")
case 2:
print("x is 2")
What is the syntax of a match?
match
What is the equivalent of C#’s switch?
Underscore
case _:
Can be used in a tuple: case (300, _):
What represents the wildcard in match?
flag = False
match(x, y):
case (100, 200) if flag:
What is the syntax of using an if statement within a case of a match statement?
match(x, y):
case (100 | 200 | 300, 200) :
What is the syntax of using an or within a case of a match statement?
squares = [x**2 for x in numbers]
Using comprehensions how would one store the squared values from a list into a new list “squares”?
numbers = [1,2,3,4,5]
[expression for item in iterable if condition]
Here, 'expression' is applied to each 'item' in the 'iterable', and 'condition' (optional) filters the items
What is the basic syntax for a list comprehension?
new = [x for x in numbers if x % 2 == 0]
Using comprehensions how would one create a new list containing only the even numbers from the original list?
numbers = [1,2,3,4,5]
new = [x for i,x in enumerate(numbers) if i % 2 != 0]
or
new = [t[1] for t in enumerate(numbers) if t[0] % 2 != 0]
enumerate returns index, value
i & t[0] = index x & t[1] = value
Using comprehensions how would one create a new list containing only the elements of the original list located in the odd indices?
numbers = [1,2,3,4,5]
list = [num for row in matrix for num in row]
exterior = for row in matrix
interior = for num in row
Which is the inner for loop and which is the outer for loop?
list = [num for row in matrix for num in row]
import random
random.shuffle(list)
How do you use random to mix up a collection or sequence?
import random
random.choice(list)
How does one use random to make a random selection from a collection or sequence?
The random.random() function in Python produces a random floating-point number between 0.0 and 1.0, inclusive of 0.0 but not 1.0
What does random.random() produce?
s.index(‘x’, i, j)
collection.index(searched element, starting index(inclusive), end of search(exclusive))
What is the syntax of finding the index of the first occurrence of x in s (at or after index i and before index j)?
s.count(x)
What is the syntax of finding the total number of occurrences of x in s?
The for loop automatically stops when the generator is done.
Why is it convenient to use a for loop to call a generator?
import time
start = time.perf_counter()
“code to be evaluated”
end = time.perf_counter()
print(end-start)
What is the syntax of capturing the time it takes to run a selection of code?
PEP 8, or Python Enhancement Proposal 8, is the official style guide for Python code. Created in 2001 by Guido van Rossum, Barry Warsaw, and Nick Coghlan, PEP 8 provides comprehensive guidelines for writing clean, readable, and consistent Python code. The main goals of PEP 8 are:
To improve code readability
To make Python code consistent across different projects and developers
To reduce bugs and errors by promoting clear and understandable code
What is PEP 8?
The 'f' stands for "fixed-point notation", which is a way of writing floating-point numbers with a specific number of digits after the decimal point.
The .2 specifies the precision (number of decimal places), while the f indicates that it should be formatted as a float
pi = 3.14159
print(f"|{pi:.2f}|")
What does the “f” that follows the 2 stand for?
if value in collection
What is the syntax of checking if a collection contains a specific element?
if value not in collection
What is the syntax of checking if a collection does not contain a specific element?
slice of s from i to j with step k
i is the start index (inclusive)
j is the end index (exclusive)
k is the step or stride
What does the following do?
s[i:j:k]
min(collection)
What is the syntax of retrieving the smallest item of a collection?
max(collection)
What is the syntax of retrieving the largest item of a collection?
collection.index(x, i, j)
i & j are optional
j is exclusive(it will not compare the element at j)
What is the syntax of finding the index of the first occurrence of x in collection (at or after index i and before index j)
def function(*args)
One asterisk
What comes before the args variable?
def function(**kwargs)
Two asterisks
Nothing comes in front when inside the function
What comes before the kwargs variable?
key word arguments
What is kwargs an abbreviation of?
list = string.split(‘,’)
The string method split() will split the string every time it encounters the delimiter in the string and adds all the portions to a list.
If no delimiter is assigned, the default is ‘ ‘(a space).
What is split() used for and what is it’s syntax?
import string
alphabet = string.ascii_letters
string.ascii_lowercase and string.ascii_uppercase if you don’t want both.
What is the easiest method of obtaining a string of the alphabet, lowercase and uppercase?
import string
numbers = string.digits
What is the easiest way of getting a string of numbers 0 - 9?
iterable = iterable.reverse()
What is the syntax of reversing an iterable?
listy = [1,2,3,4,5]
def squared(nums):
return num**2
listy_squared = map(squared, listy, …)
map(function, iterable, ...)
function: This is the function that will be applied to each item in the iterable(s).
iterable: This is the sequence, collection, or iterator object that you want to map.
...: You can provide multiple iterables as arguments. If multiple iterables are provided, the function must accept as many arguments as there are iterables
listy = [1,2,3,4,5]
listy_squared = []
def squared(nums):
return num**2
What is the syntax of using the map() method to do the same thing as the following code?
for num in listy:
listy_squared.append(squared(num))
When the top level elements are altered in a shallow copy the original is unchanged. But when any nested element is altered in a shallow copy the original is altered.
When any part of a deep copy is altered the original does not change.
What type of copy affects the original when nested elements are altered in the copy and what type does not?
A deep copy
What type of copy recursively copies the entire object tree including all nested structures? Modifications to the copy or its nested objects do not affect the original
Shallow copy
What type of copy only copies the top level structure, not the nested objects. Changes to the nested objects in the copy will affect the original, and vice versa
copied = copy.copy(original)
How does one perform a shallow copy?
deep_copied = copy.deepcopy(original)
How does one perform a deep copy?
a_list.extend(b_list)
print(a_list)
Outputs: [1,2,3,4,5,6]
a_list = [1,2,3]
b_list = [4,5,6]
What python built in function performs the same function as
a_list += b_list
collection.pop(2)
Pop retrieves the item at index 2 and also removes it from the collection
If the index is not populated an ValueError will be thrown
How does the built in “pop()” function work?
collection.remove(“q”)
Removes the first item from collection where the value equals “q”
If the item does not exist in the collection an IndexError is thrown
How does the built in function “remove()” work?
reversed_collection = sorted(original_collection, reverse=True)
How does one use a built in function to sort a collection in reverse order?
help(function)
example:
help(random.choice)
How do you access the built in help from Python?
It produces a shallow copy and that means that any changes to nested items in the copy will alter the items in the original as well. The top level items will not change in the original.
copyList = copyList + copyList + copyListDoes the preceding produce a deep copy or shallow copy and what does that mean?
It produces a shallow copy and that means that any changes to nested items in the copy will alter the items in the original as well. The top level items will not change in the original.
List copy operations are all shallow-copy.
copyList = intList.copy()Does the preceding produce a deep copy or shallow copy and what does that mean?
Neither, when you make a copy using assignment, it is called a reference or an alias. This method does not create a new object but instead creates a new reference to the same object in memory.
This type of assignment is neither a shallow copy nor a deep copy. It simply creates a new name that points to the same object. As a result, any changes made to copy1 will affect original_list and vice versa, because they are referring to the same object in memory
When one makes a copy by assignment (ex. copy1 = original_list) is it a shallow copy or a deep copy?
A slice of a list is a shallow copy. Changes at the top level will not change the original but changes to a nested item will change the original.
What type of copy is a slice of a list?
Sets are unordered.
How are sets ordered?
If you run random.seed() repeatedly with the same value in the brackets you will always output the same sequence of random numbers.
What does random.seed() do?
def function_name(argument1=default1, argument2= defualt2):
def add(num1=5, num2=10):
What is the syntax of defining defaults for arguments in functions?
‘::’.join(iterable)
What is the syntax of concatenating an iterable into a single string with :: between each item?
In Python, the .sort() method can only be used on lists. It is a built-in method of the list object that sorts the elements in-place, meaning it modifies the original list.
What collections can the .sort() method be used on in python? Does it return the original collection or a new collection?
The sorted() function can be used on any iterable, including lists, tuples, dictionaries, and sets
What collections can the sorted() method be used on in python? Does it return the original collection or a new collection?
class Person:
def __init__(self,name,age):
self.name = name
self.age = ageThe init method in Python is a special method, also known as a constructor, that is automatically called when a new instance of a class is created.
It's important to note that init is not the actual constructor in Python. The new method is responsible for creating the instance, while init focuses on initializing that instance
What is the syntax of a constructor in python?
def __str__(self):
return self.name + " " + str(self.age)
or
def __str__(self):
return f'{self.name} {self.age}'What is the syntax of using the __str__ method in python?
filter(function, iterable)
The filter() function returns an iterator object.
What is the syntax of the filter() function?
What does the filter function return?
lambda arguments: expression
Example:
to_upper = lambda text: text.upper()
print(to_upper("Hello World!"))
What is the syntax of a lambda in python?
The >>> is called a REPL, short for Read-Evaluate-Print-Loop, and is meant for interactive use within an existing environment
What is >>> ?
Verbose mode
What doctest mode provides detailed output about the tests being run, including the code being tested, its expected output, and whether the test passed or failed. It is particularly useful for debugging and understanding the behavior of your doctests.
raise
What keyword is used to manually trigger an exception. This allows developers to signal an error condition when a specific condition occurs in their code, enabling more controlled error handling.
with
What statement in Python is primarily used for resource management, ensuring that resources such as files, connections, or locks are properly cleaned up after use, regardless of whether an exception occurs or not. It works by using a context manager, which is an object that implements the context management protocol. This protocol consists of two special methods: __enter__() and __exit__()
Printing without an automatic newline uses a named argument end
print( myString, end="" ) #end is a named parameter which defaults to newline, substitute an empty string to override the newline
How does one prevent a print statement from automatically moving to a new line?
Python enforces this strict parameter order in function definitions:
Positional-or-keyword parameters (required first)
Positional-or-keyword parameters with defaults
*args (variable positional arguments)
Keyword-only parameters (after a lone *)
**kwargs (variable keyword arguments)
What is the required order of args, kwargs, positional-or-keyword parameters and positional-or-keyword parameters with default values?