Ch 4. Flashcards
How do you write a loop?
letters = [ “a”, “b”, “c”,]
for new_variable in letters:
print(new_variable)
How do you use indentation in a loop?
When you indent, then that line of code will be inside the for loop and run through all the items in the list. If you do not intend, once it is done running it will then proceed to the line of code that was not indented and run it once.
Common types of errors?
- “IndentationError: expected an indented block”
2: Logical error (when your code produces no python error but is not your expected result) - “IndentationError: unexpected indent”
- Forgetting the colon
How do you easily generate a series of numbers?
range()
What is something to remember about range()?
It is “off by one”
How do you covert a series of numbers into a list?
list(range())
How do you specify the increment in a given range?
range(start, stop, increment)
Note: increment must be an integer
How do you find the min, max, and sum of a list of numbers?
min(list_name_), max(list_name), sum(list_name)
What does a list comprehension do?
It combines the for loop and the creation of new elements into one line, and automatically appends each new element.
How do you work with a specific group of items in a list?
list_name[index start:index end:increment]
What do you do if you want to loop through a subset of the elements in a list?
for value in list_name[start:end:increment]
print(value)
How do you copy a list?
new_list = og_list[:]
How do you create a list of items that cannot change?
Tuple
Difference between a list and a tuple?
list uses square brackets and is mutable, tuple uses parantheses and is immutable
How do you write a tuple?
letters = (“a”, “b”, “c”)