Automate the Boring Stuff with Python Ch.1 - Ch.5
Local Scope
Where parameters and variables that are assigned in a called function are said to exist
What does the following code do to spam? spam = ['cat', 'dog', 'bat'] spam.insert(1, 'chicken')
spam = ['cat', 'chicken', 'dog', 'bat']
What does the following code do to spam? spam = ['cat', 'dog', 'bat'] spam.append('moose')
spam = ['cat', 'dog', 'bat', 'moose']
If a dictionary is stored in spam, what is the difference between the expressions 'cat' in spam & 'cat' in spam.values()?
'cat' in spam checks whether there is a 'cat' key in the dictionary, while 'cat' in spam.values() checks whether there is a value 'cat' for one of the keys in spam
String Replication Operator
*
Operators
** (Exponent) * (Multiplication) / (Division) // (Integer division/Floored quotient) % (Modulus/Remainder) + (Addition) - (Subtraction)
String Concatenation Operator
+
What operator can combine two lists to create a new list value?
+
What are the augmented assignment operators?
+= (spam = spam + 1), -=(spam = spam - 1), *=(spam = spam * 1), /=(spam = spam / 1), %=(spam = spam % 1)
What are the 3 rules for blocks?
- Begin when the indentation increases - Can contain other blocks - End when the indentation decreases to zero or to a containing block's indentation
What are some reasons scopes matter?
- Code in the global scope cannot use any local variables - However, a local scope can access global variables - Code in a function's local scope cannot use variables in any other local scope - You can use the same name for different variables if they are in different scopes
Expression
- Consist of values(such as 2) and operators(such as +) - The most basic kind of programming instruction in python - 2 + 2 is an example
What are some benefits of using a tuple instead of a list?
- If you need an ordered sequence of values that never changes - Because they are immutable and their contents don't change, Python can implement some optimizations that make code using tuples slightly faster than code using lists
What are the 3 rules of naming a variable?
- It can be only one word - It can use only letters, numbers, and the underscore (_) character - It can't begin with a number
What does an elif statement consist of?
- The elif keyword - A condition (an expression that evaluates to True or False) - A colon - Starting on the next line, and indented block of code (called the elif clause)
What does an else statement consist of?
- The else keyword - A colon - Starting on the next line, and indented block of code (call the else clause)
What does a for statement consist of?
- The for keyword - A variable name - The in keyword - A call to the range() method with up to three integers passed to it - A colon - Starting on the next line, and indented block of code (called the for clause)
What does an if statement consist of?
- The if keyword - A condition (that is, an expression that evaluates to True or False) - A colon - Starting on the next line, an indented block of code (called the if clause)
What does an import statement consist of?
- The import keyword - The name of the module - Optionally, more module names, as long as they are separated by commas
What are the two arguments that the get() method takes?
- The key of the value to retrieve - A fallback value to return if that key does not exist
What does a return statement consist of?
- The return keyword - The value or expression that the function should return
What does a while statement consist of?
- The while keyword - A condition (an expression that evaluates to True or False) - A colon - Starting on the next line, and indented block of code (called the while clause)
What are the only two values associated with the Boolean data type?
- True - False
The tuple data type is almost identical to the list data type, except in what two ways?
- Tuples are typed with parentheses, (and), instead of square brackets, [and] - Tuples, like strings, are immutable. Tuples cannot have their values modified, appended, or removed
Assignment Statement
- Used to store values in variables - Consists of a variable name, an equal sign (called the assignment operator), and the value to be stored
What are the 3 Boolean Operators?
- and - or - not
What are the three dictionary methods that will return list-like values of the dictionary's keys, values, or both keys and values?
- keys() - values() - items()
What are the four rules to tell whether a variable is in a local scope or global scope?
1. If a variable is being used in the global scope (that is, outside of all functions), then it is always a global variable 2. If there is a global statement for that variable in a function, it is a global variable 3. Otherwise, if the variable is used in an assignment statement in the function, it is a local variable 4. But if the variable is not used in an assignment statement, it is a global variable
What are the comparison operators?
== (Equal to) != (Not equal to) < (Less than) > (Greater than) <= (Less than or equal to) >= (Greater than or equal to)
What do the "in" and "not in" operators evaluate to?
A Boolean value
What is the difference between a function and a function call?
A function consists of the def statement and the code in its def clause. A function call is what moves the program execution into the function, and the function call evaluates to the function's return value.
Key-Value Pair
A key with its associated value
How are lists and strings different?
A list value is a mutable data type: It can have values added, removed, or changed. However, a string is immutable: It cannot be changed.
What does a slice evaluate to?
A new list value
Multiple Assignment Trick
A shortcut that lets you assign multiple variables with the values in a list in one line of code
Break Statement
A shortcut to getting the program execution to break out of a while loop's clause early
Blank String
A string with no characters in it (' ')
Program Execution (or simply, execution)
A term for the current instruction being executed
What determines if an if statement's clause (the block following the if statement) will or will not execute?
An if statement's clause will execute if the statement's condition is True. The clause is skipped if the condition is False.
What is a good way to think of scope?
As a container for variables, when a scope is destroyed, all the values stored in the scope's variables are forgotten
List values have an index() method that can do what?
Be passed a value, and if that value exists in the list, the index of the value is returned. If the value isn't in the list, the Python produces a ValueError error.
Why are dictionaries useful?
Because you can map one item (the key) to another (the value), as opposed to lists, which simply contain a series of values in order
How is a slice denoted?
Between square brackets, like an index, but it has two integers separated by a colon. For example: spam[0:4]
How can you create representations of real-world objects in Python?
By organizing a program's values into data structures
How can you indicate that you only have one value in your tuple?
By placing a trailing comma after the value inside the parentheses. Otherwise, Python will think you've just typed a value inside regular parentheses. For example: type(('hello',)) <class 'tuple'> vs. type(('hello')) <class 'str'>
How are keyword arguments identified?
By the keyword put before them in the function call
copy.copy()
Can be used to make a duplicate copy of a mutable value like a list or dictionary, not just a copy of a reference
Flow Control Statements
Can decide which Python instructions to execute under which conditions
Slice
Can get several values from a list, in the form of a new list
insert() method
Can insert a value at any index in the list
Def Statement
Defines/creates a new function that you can call later in the program
What does the random.randint() function call do?
Evaluates to a random integer between the two integers that you pass it
When do Python variables store the value itself as opposed to using a reference?
For values of immutable data types such as strings, integers, or tuples
Why are functions advantageous to have in your programs?
Functions reduce the need for duplicate code. This makes programs shorter, easier to read, and easier to update.
Methods
Functions that are tied to values of a certain data type
pprint() & pformat()
Functions that will "pretty print" a dictionary's values if you import the pprint module
Deduplicating Code
Getting rid of duplicated or copy-and-pasted code
What is the most common type of flow control statement?
If statement
If a function does not have a return statement, what is the return value of a call to that function?
If there is no return statement for a function, its return value is None
When is the following code used? spam.sort(key=str.lower)
If you need to sort the values in regular alphabetical order
Keys
Indexes for dictionaries
What can you do with both strings and lists?
Indexing, slicing; and using them with for loops, with len(), and with the in and not operators
Indexes can only be what type of values?
Integer
Variable
Is like a box in the computer's memory where you can store a single value
What happens when you try to access a key that does not exist in a dictionary?
It results in a KeyError message
What does the del statement do?
It will delete values at an index in a list
Can a return value be part of an expression?
Like any value, a return value can be used as part of an expression
Blocks
Lines of Python code that are grouped together
sort() method
Lists of number values or lists of strings can be stored using this method
What is the return value of append() and insert()?
None. Rather, the list is modified in place.
What is the data type of None?
NoneType
Floating-point Numbers (or floats)
Numbers with a decimal point
When using keys(), values(), or items(), what do you do if you want a true list from one of these methods?
Pass its list-like return value to the list function
remove() method
Passed the value to be removed from the list it is called on
What happens when you attempt to delete a value that does not exist in a list?
Python gives you a ValueError error
What is happening when Python executes the following line of code: print('Hello world!')
Python is calling the print() function and the string value is being passed to the function
What happens if you use an index that exceeds the number of values in your list value?
Python will give you an IndexError message
What problem does the get() method help avoid?
Receiving an error message if a key does not exist within a dictionary
Evaluate
Reduce down to a single value
CTRL + C
Sends a KeyboardInterrupt error to your program and causes it to stop immediately
Why does Python have different scopes instead of making everything a global variable?
So that when variables are modified by the code in a particular call to a function, the function interacts with the rest of the program only through its parameters and the return value. This narrows down the list code that may be causing a bug
What is one special thing to note about parameters?
That the value stored in a parameter is forgotten when the function returns
What is the difference between a while statement and an if statement?
The difference is how they behave. At the end of an if clause, the program execution continues after the if statement. But at the end of a while clause, the program execution jumps back to the start of the while statement.
What happens when the program execution reaches the end of a function?
The execution returns to the line that called the function and continues moving through the code as before
In list[#][#], what do the first and second indexes dictates?
The first index dictates which list value to use, and the second index indicates the value within the list value
What do the first and second integers in a slice represent?
The first integer in the index where the slice starts. The second integer is the index where the slice ends. A slice goes up to, but will not include, the value at the second index.
When is a variable initialized (or created)?
The first time a value is stored in it
If you had a function named bacon() in a module named spam, how would you call it after importing spam?
The function can be called with spam.bacon()
What happens when you pass multiple string values to print()?
The function will automatically separate them with a single space
Function Call
The function's name followed by parentheses, possibly with some number of arguments in between the parentheses
What happens to the global scope when your program terminates?
The global scope is destroyed and these variables are forgotten
What happens when there are duplicates of a value in a list?
The index of its first appearance is returned
Index
The integer inside the square brackets that follows the list
What is the main difference between a dictionary and a list?
The items stored in a dictionary are unordered, while the items in a list are ordered
What does the integer value -1 refer to?
The list index in a list
What does the term "list value" refer to?
The list itself (which is a value that can be stored in a variable or passed to a function like any other value), not the values inside the list value
What happens to the local scope when the function returns?
The local scope is destroyed and these variables are forgotten
What does the len() function return when referring to a list?
The number of values that are in a list value passed to it
Method
The same thing as a function, except it is "called on" a value
Return Value
The value that a function call evaluates to
What happens when a function containing a reference is called?
The values of the arguments are copied to the parameter variables. For lists and dictionaries, this means a copy of the reference is used for the parameter.
Explain the values returned by the keys(), values(), and items() methods
The values returned by these methods are not true lists: They cannot be modified and do not have an append() method. But these data types (dict_keys, dict_values, and dict_items, respectively) can be used in for loops.
Why can you think of functions as black boxes?
They have inputs in the form of parameters and outputs in the form of return values, and the code in them doesn't affect variables in other functions
What is happening when I type the following into the interactive shell? myCat = {'size': 'fat', 'color': 'gray', 'disposition': 'loud'}
This assigns a dictionary to the myCat variable. This dictionary's keys are 'size', 'color', and 'disposition'. The values for the keys are 'fat', 'gray', and 'loud', respectively.
input()
This function call can be thought of as an expression that evaluates to whatever string the user typed in
What is a major function of functions?
To group code that gets executed multiple times
What is the proper way to "mutate" a string?
To use slicing and concatenation to build a new string by copying from parts of the old string
The code in a while clause will be executed as long as the while statement's condition is ____
True
How can errors be handled in Python?
Try & Except Statements
What data type are the values returned by the items() method?
Tuple
How do indexes for dictionaries differ from indexes for lists?
Unlike indexes for lists, indexes for dictionaries can use many different data types (including integers, floats, strings, or tuples), not just integers
When using dictionaries, how can you assign the key and value to separate variables?
Use the multiple assignment trick in a for loop
copy.deepcopy()
Used if the list you need to copy contains lists
Global Statement
Used if you need to modify a global variable from within a function
For Statement
Used when you want to execute a block of code only a certain number of times
How can the values in lists of lists be accessed?
Using multiple indexes, like so: spam = [['cat', 'bat'], [10, 20, 30, 40, 50]] spam[0] ['cat', 'bat'] spam[0][1] 'bat'
What is a common Python technique to iterate over the indexes of a list and why is it handy?
Using range(len(someList)) with a for loop and it is handy because the code in the loop can access the index (as the variable i) and the value at that index (as someList[i])
How are values inside a dictionary accessed?
Using square brackets just as with lists
How can you split up a single instruction across multiple lines?
Using the \ line continuation character at the end
How can a for loop iterate over the keys, values, or key-value pairs in a dictionary?
Using the keys(), values(), and items() methods
Items
Values inside a list
Global Scope
Variables that are assigned outside all functions are said to exist here
When is a function's code execued?
When the function is called, not when the function is first defined
Continue Statement
When the program execution reaches this, the program execution immediately jumps back to the start of the loop and reevaluates the loop's condition
When does a Python program terminate?
When there are no more lines of code to execute
When is using the None value helpful?
When you need to store something that won't be confused for a real value in a variable
When are pprint() & pformat() helpful?
When you want a cleaner display of the items in a dictionary than what print() provides. The pprint.pprint() function is especially helpful when the dictionary itself contains nested lists or dictionaries. If you want to obtain the prettified text as a string value instead of displaying it on the screen, call pprint.pformat() instead.
When is a local scope created?
Whenever a function is called
When does Python use references?
Whenever variables must store values of mutable data types, such as lists or dictionaries
What is the while clause often called?
While loop / Loop
In code, how is a dictionary typed?
With braces {}
How are items separated in a list?
With commas (that is, they are comma-delimited)
Can lists also contain other list values?
Yes
Can you use negative integers for the index?
Yes
What happens when you assign a list to a variable?
You are actually assigning a list reference to the variable
What is happening when you are changing a value of a mutable data type?
You are changing the value in place, since the variable's value is not replaced with a new list value
len()
You can pass this function a string value (or a variable containing a string), and the function evaluates to the integer value of the number of characters in that string
What happens when you call the print() or len() functions?
You pass it values, called arguments, by typing them between the parentheses
How do you denote a list?
[]
What methods are used to add new values to a list?
append() & insert()
Flow control statements often start with a part called the _________, and all are followed by a block of code called the ______
condition, clause
What two functions can you use if you want to make changes to a list in one variable without modifying the original list?
copy.copy() or copy.deepcopy()
What is an example of how a for statement looks?
for i in range(5):
What operators are used to determine whether a value is or isn't in a list?
in & not in
What can you use to see whether a certain key or value exists in a dictionary?
in & not in operators
What does the following code do to spam? spam = ['cat', 'rat', 'bat', 'elephant'] spam[1] = 'aardvark'
spam = ['cat', 'aardvark', 'bat', 'elephant']
You can make a block of code execute over and over again with a _____ statement
while
How do you comment out code?
#
If spam = ['cat', 'bat', 'rat,' 'elephant']: What would spam[0] be? What would spam[2] be?
'cat' & 'rat'
What are the three things you should know about the sort() method?
1. The sort() method sorts the list in place 2. You cannot sort lists that have both number values and string values in them, since Python doesn't know how to compare these values 3. sort() uses "ASCIIbetical order" rather than actual alphabetical order for sorting strings. This means uppercase letters come before lowercase letters. Therefore, the lowercase a is sorted so that it comes after uppercaseZ.
Data Type
A category for values, and every value belongs to exactly one data type
Dictionary
A collection of many values, like a list
List
A value that contains multiple values in an ordered sequence
Argument
A value that is passed to a function call
List Reference
A value that points to a list
Reference
A value that points to some bit of data
What two values do the "in" & "not in" operators connect?
A value to look for in a list and the list where it may be found
Parameter
A variable that an argument is stored in when a function is called
Local Variable
A variable that exists in a local scope
Global Variable
A variable that exists in the global scope
Infinite Loop
A while loop whose condition is always True
append() method
Adds the argument to the end of the list
Conditions
Always evaluate down to a Boolean value, True or False
elif statement
An "else-if" statement that always follows an if or another elif statement & it provides another condition that is checked only if all of the previous conditions were False
What does the value [ ] represent?
An empty list that contains no values, similar to ' ', the empty string
What is the difference between an expression and a statement?
An expression evaluates to a single value. A statement does not.
Comparison Operators
Compare two values and evaluate down to a single Boolean value
Strings (or strs)
Data type indicating text values (pronounced "stirs")
Integer (or int)
Data type indicating values that are whole numbers
When are keyword arguments often used?
For optional parameters
What happens when the program execution reaches a function call?
It will jump to the top line of the function and begin executing the code there
setdefault() method
Offers a way to set a value in a dictionary for a certain key only if that key does not already have a value in one line of code
How many global scopes are there? When is it created?
One, When your program begins
When can you use break and continue statements?
Only inside while and for loops
If a value appears multiple times in a list, what happens when the remove() method is being used?
Only the first instance of the value will be removed
When is an else clause executed?
Only when the if statement's condition is False
not Operator
Operates on only one Boolean value (or expression) and simply evaluates to the opposite Boolean value
How can you prevent a program from crashing when it gets an error?
Place the line of code that might cause an error in a try clause
What is one benefit of using a list?
That your data is now in a structure, so your program is much more flexible in processing the data than it would be with several repetitive variables
What is None?
The absence of a value
Binary Operators
The and & or operators always take two Boolean values (or expressions)
What goes in a try clause?
The code that could potentially cause an error
What goes in an except clause?
The code that executes if an error happens
When is it good to use a del statement vs. the remove() method?
The del statement is good to use when you know the index of the value you want to remove from the list. The remove() method is good when you know the value you want to remove from the list.
What are the first and second arguments for the index() method?
The first argument is the index for the new value, and the second argument is the new value to be inserted
What are the two arguments passed to the setdefault() method?
The first argument passed to the method is the key to check for, and the second argument is the value to set at that key if the key does not exist. If the key does exist, the setdefault() method returns the key's value.
Range() Function Arguments
The first argument will be where the for loop's variable starts, and the second argument will be up to, but not including, the number to stop at. The third argument is the step argument, which is the amount that the variable is increased by after each iteration