Python Flashcards
Boolean Values?
Assesses the truth value of something. It has only two values: True and False
what are tuples?
A type of data that is immutable (can’t be modified after its creation) and can hold a group of values. Tuples can contain mixed data types.
what are Lists?
A type of data that is mutable and can hold a group of values. Usually meant to store a collection of related data.
what are Dictionaries?
A group of key-value pairs. Dictionary elements are indexed by unique keys which are used to access values.
One of the most important aspects of Python is….
indentation. Python has no brackets, braces, or keywords to indicate the start and end of certain code blocks such as functions, if statements, and loops. The only delimiter is the colon (:) and the indentation of the code itself.
While loops are often used when…
we don't know how many times we have to repeat a block of code but we know we have to do it until a certain condition is met. For loop example: for count in range(0,5): print("looping - ", count) While loop comparison of above: count = 0 while count < 5: # notice the colon! print("looping - ", count) count += 1
What does the break statement do?
exits the current loop prematurely, resuming execution at the first post-loop statement, just like the traditional break found in C or JavaScript.
What does the continue statement do?
returns the control to the beginning of the loop. The continue statement rejects – or skips – all the remaining statements in the current iteration of the loop, and continues normal execution at the top of the loop.
What does the pass statement do?
is used when a statement is required syntactically but you do not want any command or code to execute. The pass statement is a null operation; nothing happens when it executes. The pass is almost never seen in final production, but can be useful in places where your code has not been completed yet.
What are the comparison and logic operators for: is equal is not equal greater than less than greater than or equal less than or equal and or not
== != > < >= <= and or not
What is a function?
a named block of code that we can execute to perform a specific task.
How do you define a function?
def add(a,b): x= a+b return x
What does def add(a,b): x= a+b return x do?
it defines the function
How do you invoke a function?
by using the () after the function name. eg:
add(8,9)
What’s the difference between a parameter and an argument?
in the following example: def add(a,b): x= a+b return x add(8,9)
a and b are the parameters and 8 and 9 are arguments. We define parameters. We pass in arguments into functions.
Why is it important to return a value in a function?
So we can use the returned value later in our program.
What are common string methods?
string.upper()
string.lower()
string.count(substring) returns the # of occurences
string.split(char) splits the string by default at every space or at specified delimiter
string.isalnum() returns boolean depending on whether the string’s length is > 0 and all characters are alphanumeric. Strings that contain anything other than alphanumeric characrers return False
similar methods include .isalpha(), isdigit()
string.join(list) returns a string that is concatenated
string.endswith(substring) returns a boolean
What are built-in functions for lists and tuples?
max(sequence) returns the largest value in the sequence
sum(sequence) return the sum of all values in sequence
map(function, sequence) applies the function to every item in the sequence you pass in. Returns a list of the results.
min(sequence) returns the lowest value in a sequence.
sorted(sequence) returns a sorted sequence
What are built-in functions and methods for dictionaries?
Python includes the following standalone functions for dictionaries:
len() - give the total length of the dictionary.
str() - produces a string representation of a dictionary.
type() - returns the type of the passed variable. If passed variable is a dictionary, it will then return a dictionary type.
Python includes the following dictionary methods (either dict.method(yourDictionary) or yourDictionary.method() will work):
.clear() - removes all elements from the dictionary
.copy() - returns a shallow copy dictionary
.fromkeys(sequence, [value]) - create a new dictionary with keys from sequence and values set to value.
.get(key, default=None) - for key key, returns value or default if key is not in dictionary.
.items() - returns a view object of dictionary’s (key, value) tuple pairs.
.keys() - return a view object of dictionary keys.
.pop(key) - returns the value associated with the key and removes the key-value pair from the dictionary.
.setdefault(key, default=None) - similar to get(), but will set dict[key]=default if key is not already in dictionary.
.update(dict2) - adds dictionary dict2’s key-values pairs to an existing dictionary.
.values() - returns a view object of dictionary values.
What is an anonymous function?
a function without a name. They are created with the lambda keyword. They are good for:
~when we need to use the function once
~when we need to break down complex tasks into small, specific task
~convenient as arguments to functions that require functions as parameters
Give an example of a lambda functions.
def square(num): x = num ** 2 return x
lambda method: def square(num): lambda num: num ** 2 or lambda num1, num2: num1+num2
Use a lambda to create an element in a list
# create a new list, with a lambda as an element my_list = ['test_string', 99, lambda x : x ** 2] # access the value in the list print(my_list[2]) # will print a lambda object stored in memory # invoke the lambda function, passing in 5 as the argument my_list[2](5)
Pass a lambda to another function as a callback
# define a function that takes one input that is a function def invoker(callback): # invoke the input pass the argument 2 print(callback(2)) invoker(lambda x: 2 * x) invoker(lambda y: 5 + y)
Store a lambda in a variable.
add10 = lambda x: x + 10 # store lambda expression in a variable
add10(2) # returns 12
add10(98) # returns 108
Return a lambda by another function.
def incrementor(num): start = num return lambda x: num + x
What is a closure function?
A function object that remembers values in enclosing scopes even if they are not present in memory. eg: # Python program to illustrate # closures def outerFunction(text): text = text
def innerFunction(): print(text)
return innerFunction # Note we are returning function WITHOUT parenthesis
if \_\_name\_\_ == '\_\_main\_\_': myFunction = outerFunction('Hey!') myFunction() Run on IDE Output: Hey!
What is a Python module?
Python files with the .py extension which implement a set of functions.
How do we bring modules into our code?
Modules are imported using the import command.
import arithmetic
How do we make our own modules?
To create a module, we first create a new .py file with the module name in the same directory as the file that will import the module. Then we import it using the import command and the Python file name (without the .py extension)
What is a Python package?
a collection of modules in directories that give a package hierarchy.
from my_package.subdirectory import my_functions
What is the purpose of having a file called __init__.py in a directory?
Each package in Python is a folder which MUST contain a special file called __init__.py. This file can be empty, and it indicates that the directory containing it is a Python package, so it can be imported the same way a module can be imported.
The __init__.py file can also decide which modules this package will export as an API, while keeping other modules internal, by overriding the __all__ variable, like so:
#file \_\_init\_\_.py: \_\_all\_\_ = ["test_module"]
What is OOP?
It allows us to create a blueprint for the purpose of reproducing objects.
What does instantiate mean?
Once we’ve created a blueprint for an object, we have to create an instance of the object. In other words create the object using the blueprint provided.
What is class?
It is how we define our blueprint and are instructions on how to build many objects that share characteristics. class User: pass
How do we instantiate our blueprint class User: pass?
michael = User()
What two things do classes include?
Attributes: Characteristics shared by all instances of the class type. Think about what we want to know about our users, for example. We may decide that all users should have a name and an email. We’ll show you how to handle this in the next module.
Methods: Actions that an object can perform. A user, for example, might be able to make a purchase. A method is like a function that belongs to a class. It’s some instructions that will only work when called on an object that has been created from that class. We’ll show you how shortly.
Objects can store 2 different types of information. What are they?
Attributes are characteristics of an object while methods are things an object can do. eg:
class User: # the \_\_init\_\_ method is called every time a new object is created def \_\_init\_\_(self, name, email): # the following are the object's attributes self.name = name self.email = email self.logged = False # this is a method we created to help a user login def login(self): self.logged = True print(self.name + " is logged in.") return self #now create an instance of the class new_user = User("Anna","anna@anna.com") print(new_user.email)
What is the __init__() method and when is it called?
It is called every time a new object is created. Python’s __init__() method is something that’s known as a magic method. Magic methods are automatically created and sometimes invoked when a new instance of a class is created. __init__() is useful because it allows us to set some attributes when a new instance is created. Because we know that the __init__() method will run immediately, we can pass in some arguments to that __init__() method upon object creation. We do not have to explicitly call this method. All we do is create our instance and provide the arguments we like, and the rest is done for us. The arguments we provide will be passed on to the __init__() method.
What is an object or instance?
A data type built according to specifications provided by the class definition.
What is an attribute?
A value. Think of an attribute as a variable that is stored within an object.
What is a method?
A set of instructions. Methods are functions that are associated with an object. Any function included in the parent class definition can be called by an object of that class.
What does the self parameter do?
The self parameter includes all the information about the individual object that has called the method. Without self, every time we changed one object’s attributes, we’d change the attribute for all the items of that type.
What is the benefit of being able to chain methods?
It avoids DRY. eg:
user1.login().show().logout()
If we wanted to define a new class we would start with which line
class ClassName:
How can we set attributes to an instance of a class
Initializing our attributes with the __init__() function
We can set individual attributes to each instance - one by one
The __init__() function gets called while the object is being constructed?
False
Can you define an __init__() function that has parameters?
No
How do you pass arguments to the __init__() function?
When creating an object instance you pass the arguments to the specified class you are creating an instance of