Chapter 4 Error Handling Flashcards
How would you write a code that attempts to work, but if it doesn’t it shows an all encompassing exception?
try:
print(str(8 / 0))
except Exception as e:
print(“sorry, an error occured”)
Our code is crashing due to the following error:
ZeroDivisionError
How do we keep it from crashing and output a text explaining the error?
THIS WILL ONLY WORK FOR THIS SINGLE ERROR AND CRASH FOR EVERYTHING ELSE!
try:
print(str(8 \0))
except ZeroDivisionError as e:
print(“Error”)
remember that e is the variable here, we can also print that variable out to display what the error is at the bottom like this:
print(“Error Details: “ + str(e))
Why must we turn our error variable into a string to print?
str(e)
This is due to it being an EXCEPTION, which is a class.
This term follows exception and will print regardless if an exception happens to help clean up the code
try:
print(str(8 \0))
except ZeroDivisionError as e:
print(“Error”)
finally:
(“fixing the error”)
Create a function and describe what it is doing
def ask(prompt):
return input(prompt + “ “)
print(ask(“How many dogs are there?”)
ask <- function name
prompt <- argument
If we want more than one conditional statement to be needed to pass as true, what should we use?
And
If we want at least on of the conditionals to be true in condistional statement, what do we use?
Or
What does an f-string do? Create one
Turns everything into a string
Print(f”{num} is this)
Create a function that you supplies a variable back to print that takes the input of year and pc/console and the variable tells you that you like pc/console games from that year
def nathan(type, year):
games = “You like “ + type + “ games from “ + year
return games
print(nathan(“pc”, “1990”))
Create a default argument for if you don’t provide one for a defined function
def ask(prompt = “Default answer”):
return print(prompt + “ “)
ask()
Define a function with a default argument.
Give the default argument a space at the end.
create an if statement that returns your input prompt as is if it contains a space.
create an else statement that gives your prompt a space if it doesn’t have one
def ask(prompt = “Please enter a value: “)
if prompt.endswith(“ “):
return input(prompt)
else
return input(prompt + “ “)
Give a defined function that accepts first last and middle names and give them all a default
def ask(first = “first”, middle = “middle”, last = “last”):
name = first + “ “ + middle + “ “ + last
return name
print(ask(“Joshua”, “Nathan”, “Cahoe”))
Can you give only partial default argument in a defined function?
Yes, but it has to be in a way that the interpreter can define it.
ex:
first, middle, last = “last”
first = “first”, middle, last = “last”
These would work because the interpreted can figure out where to put in the arguments you provided
create a function that accepts your first middle and last name and puts them in that order to print
Use keyword arguments to supply the info in any order you want and it will still display in the correct order as specified in the function
def ask(first, middle, last):
name = first + “ “ + middle + “ “ + last
return name
print(ask(last = “Cahoe”, first = “Joshua”, middle = “Nathan”))
print how many values are in a list
this works for strings too
list = [
“jason”,
“derrick”
]
print(len(list))
Create an arbitrary argument for a defined function
def num(*add):
sum = 0
for i in add:
sum += i
return sum
print(num(2, 3, 8))
Define scope
Place where data structures and functions are located
def ask(prompt)
the temp variable here is scoped for this ask function since it can only be used here
yield vs return
return closes your function whenever it is reached whereas yield will remember the last number until it is called again, this happens each time it runs.
This is important because it will save you resources, for example, if you created
Create a generator for the 99 bottles song where it will print on it’s own when using a for loop
def song(bottles = 99):
while bottles > 0:
print(str(bottles) + “ bottles of beer on the wall.”)
print(str(bottles) + “ bottles of beer”)
print(“take one down, pass it around”)
bottles -= 1
print(str(bottles) + “ bottles of beer on the wall”)
yield
return True
for i in song(3):
pass
This will print on its own because we have the print function inside. We use pass here to tell python to do nothing and wait for it to do it’s thing
We use return, since that tells our function to stop all together (remember, yield keeps going until it can’t anymore.
Create a generator for the 99 bottles song where it stores the song lyrics in a “buffer”
def song(bottles = 99):
while bottles > 0:
verse = str(bottles) + “ bottles of beer on the wall. \n”
verse += str(bottles) + “ bottles of beer \n”
verse += “take one down, pass it around \n”
bottles -= 1
verse += str(bottles) + “ bottles of beer on the wall \n”
yield verse
return True
for i in song(3):
print(i)
Strings are immutable in python. When we did the previous iterations, this caused the system to do a lot of work to change it. We can optimize our code by creating the bottle song into a list inside the generator, create that now
def song(bottles = 99):
while bottles > 0:
verse = []
verse.append(str(bottles) + “ bottles of beer on the wall. \n”)
verse.append(str(bottles) + “ bottles of beer \n”)
verse.append(“take one down, pass it around \n”)
bottles -= 1
verse.append(str(bottles) + “ bottles of beer on the wall \n”)
yield ““.join(verse)
return True
for i in song(3):
print(i)
”“.join(verse) combines the lyrics? More on this in chapter 6 I believe
What do you call values in a list?
[“elements”, “elements”]
how would you change “20” in this list to “17” using an index?
list = [1, 19, 20]
list[2] = 17
add 23 to the end of
list = [1, 19, 20]
list.append(23)
Add “this” to the beginning of the below list
list =[“donut”, “raisin”]
list.insert(0, “this”)
Delete the second entry in the below list and then delete the last entry, but store the last entry in a variable to use later
list = [1, 19, 20]
list.pop(1)
thist = list.pop()