part 3 Flashcards
loops and more
Create an if statement for if a is not greater than b
a = 33
b = 200
if not a > b:
print(‘a is not greater than b’)
Show an example of a nested if statement
x = 41
if x > 10:
print(“Above ten,”)
if x > 20:
print(“and also above 20!”)
else:
print(“but not above 20.”)
What should you put if as a marker to come back to code later but make sure it works for the time being not producing anything
like
if a > b:
if a > b:
pass
What statement do you use to stop a while loop if a condition is true
What statement would instead of breaking the loop, continue to the next part of the code in the loop (the next iteration)
break
continue
Add an else statement to the end of a while loop stating that 6 is no longer less than 6.
i = 1
while i < 6:
print(i)
i += 1
else:
print(“i is no longer less than 6”)
Using a for loop, iterate through six numbers printing them all starting with 2
Next, starting from 2, iterate 30 numbers, have them iterate by the number 3 instead of 1
for x in range(2, 6)
print(x)
for x in range(2, 30, 3)
Using a for loop, iterate from 0 - 5. At the end it should print out ‘finished’
for x in range(6):
print(x)
else:
print(‘finished’)
We use else here instead of just print. The reasoning for this is because if we use print, whatever that comes after will always print. With else, it only prints if the loop loops all the way through without issue. For instance, if you made the above loop break after it got to three, the else statement wouldn't produce anything.
Break a for loop when x is 3 even if you have the range set to 6
for x in range(6):
if x == 3: break
print(x)
else:
print(“Finally finished!”)
Else will do nothing here since it never got to that point
What is an iterator
a list is iterable because it has iterable objects packed inside it. To make it into an iterator you’d have to turn it into one with iter(list)
Iterators must implement the __next__() method (which is a dunder method ‘double underscore’)
Turn the below tuple into an iterator. Next, cycle through the iterations.
mytuple = (“apple”, “banana”, “cherry”)
mytuple = (“apple”, “banana”, “cherry”)
myit = iter(mytuple)
print(next(myit))
print(next(myit))
print(next(myit))
Using classes, create your own iterator. Next, use it.
Make it to where it will stop after 20 iterations
class MyNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
if self.a <= 20:
x = self.a
self.a += 1
return x
else:
raise StopIteration
myclass = MyNumbers()
myiter = iter(myclass)
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
BREAKING THIS DOWN
__iter__
is used to start off the first number in the sequence. It’s an instance variable and not an attribute because we want it to be one again for a different instanct using it.
__next__
This just tells the object what to do next in each sequence.
return self: Basically tells the program to return the instance/object so it can manage the iteration process.
Look at it this way, __iter__ basically turns your object into an iterator and returns it back so everyone else can use it in your class
What is polymorphism in terms of a function and class?
Basically this is just child classes inheritting their parents methods and using them.
We have the class MyClass() but we want it to print “Welcome” when print the name of the class on it’s own. What do?
def __str__(self):
print(‘Welcome’)
Describe the self parameter
Describes the current instance of the class
Use the below Class as reference
print the person’s age
delete it
delete the object
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f”{self.name}({self.age})”
p1 = Person(“John”, 36)
print(person.age)
del person.age
del person
What are two different names for
Parent Class
Child Class
parent - base class
child - derived class
Use the Person class to create an object, and then execute the printname method:
Using the below class, return the print statment from the printname method
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
x = Person(“John”, “Doe”)
x.printname()
Say there is a person class and you want to make a child/derived class from it named Student. Show how you would do that so it inherits it methods and instance variables
class Student(Person)
We have created a Student child/derived class from the parent/base class Person. We want to add in the Person’s instance variables as well. Show how you would do that
class Student(Person):
def __init__(self, fname, lname):
person.__init__(self, fname, lname)
if using super().\_\_init\_\_() you don't have to enter self as one of it's parameters
You have the Person class already. Person has the following instance variables:
fname
lname
Create a Student child class from it the uses the super function
class Student(Person):
def __init_(self, fname, lname):
super().__init__(fname, lname)
with super the “self” parameter is not required.
Define MRO
Explain what it would output if you printed the greeting from C
class A:
def greet(self):
print(“Hello from A”)
class B:
def greet(self):
print(“Hello from B”)
class C(A, B):
def greet(self):
super().greet()
print(“Hello from C”)
c = C()
c.greet()
Method Resolution Order
This goes in order of what’s next in relation to (C) since that’s what we’re calling.
Super would go to the next in order:
First printing C’s greet, then A’s, but wouldn’t print B’s. this is because in the MULTIPLE INHERITANCE structure we have here, we’ve listed ‘A’ as the first Parent, so it would be the one called on. To go further and print B’s, we would have to add the super method to A, which would go to the next section of the MRO… which is B
class A:
def greet(self):
print(“Hello from A”)
super().greet() # Continue to the next class in the MRO
In the below code, would x be a local variable for the nested function named ‘myinnerfun():’?
Yes
Define LEGB and describe how it dictates what will be printed in terms of the below code.
def outer():
x = ‘outer x’
def inner():
x = ‘inner x’
print(x)
inner() print(x)
outer()
Local, Enclosing, Global, Built-in
Python checks for variables in this order.
The only thing we do is call the outer() function.
Outer sets its local variable t0 x = ‘outer x’
Next it has the nested function inner() defined which sets it’s own local variable to x = ‘inner x’
inner then has a print command afterword
Next, back to the outer function it references inner() specifying it needs inner() to be done first prior to it printing it’s local x.
So the output would be
inner x
outer x
We have the below code to follow from. What will it output and what does nonlocal mean:
def myfunc1():
x = “Jane”
def myfunc2():
nonlocal x
x = “hello”
myfunc2()
return x
print(myfunc1())
nonlocal is slightly different than global. Basically this is saying it wants to change the ENCLOSED variable. myfunc1 encloses myfunc2, therefore it changes that variable
In terms of the below code, what would you call word vs ‘nathan’
my_function(word)
me = my_function(‘nathan’)
word - this is a parameter
‘nathan’ - this is the argument
basically:
parameter is the variable
argument is the content of that variable
You’ve created a function and you don’t know how many parameters you need. Show how you would do this.
What is this called?
*kids - Arbitrary argument
def my_function(*kids):
print(‘the youngest child is ‘ + kids[2])
my_function(‘emil’, ‘tobias’, ‘linus)
What are keyword arguments?
Show how you would use them
Also called kwargs
Creates a key:value dictionary for you to reference
def my_function(**kid):
print(“His last name is “ + kid[“lname”])
my_function(fname = “Tobias”, lname = “Refsnes”)
Can you pass a list as an argument?
YES
def my_function(food):
for x in food:
print(x)
fruits = [“apple”, “banana”, “cherry”]
my_function(fruits)
A positional argument means that the arguments passed to the function have to be in the order respective of how the function has it’s parameters.
How would we make sure a function could only take in positional arguments?
How about keyword-only arguments?
Show how it would look combining the two
Positional Only
def my_function(x, /):
print(x)
my_function(3)
Keyword Only
def my_function(*, x):
print(x)
my_function(x = 3)
Combination
def my_function(a, b, /, *, c, d):
print(a + b + c + d)
my_function(5, 6, c = 7, d = 8)
What is a lambda function?
Show it’s structure
Create a lambda function that gives you the result of a + 10, where you will provide the value for a.
lambda arguments: expression
x = lambda a : a + 10
print(x(5))
above:
lambda a <- this is the argument
a + 10 < - this is the expression
Create a lambda function that can take two arguments and multiply them
x = lambda a, b : a * b
x(12,14)
lambdas are more suited for functions. We can make some very diverse tools easily.
Let’s say we want to make a function that allows us to double or triple a number, give the function the foundation to do both and utilize a lambda
def myfunc(n):
return lambda a : a * n
below we’re turning doubler into a double function
doubler = myfunc(2)
Now we’re using the doubler to double 5. easy peasy get on your kneesy
print(doubler(5))
How do you create a module?
In the same folder add more python files:
import whatever
you have a module named fart. Give fart an Alias of mx
import fart as mx
Show all function in the platform module
import platform
print(dir(platform))
only import randint from random
from random import randint