part 3 Flashcards

loops and more

1
Q

Create an if statement for if a is not greater than b

a = 33
b = 200

A

if not a > b:
print(‘a is not greater than b’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Show an example of a nested if statement

A

x = 41

if x > 10:
print(“Above ten,”)
if x > 20:
print(“and also above 20!”)
else:
print(“but not above 20.”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

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:

A

if a > b:
pass

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

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)

A

break
continue

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Add an else statement to the end of a while loop stating that 6 is no longer less than 6.

A

i = 1
while i < 6:
print(i)
i += 1
else:
print(“i is no longer less than 6”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

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

A

for x in range(2, 6)
print(x)

for x in range(2, 30, 3)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Using a for loop, iterate from 0 - 5. At the end it should print out ‘finished’

A

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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Break a for loop when x is 3 even if you have the range set to 6

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is an iterator

A

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’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Turn the below tuple into an iterator. Next, cycle through the iterations.

mytuple = (“apple”, “banana”, “cherry”)

A

mytuple = (“apple”, “banana”, “cherry”)
myit = iter(mytuple)

print(next(myit))
print(next(myit))
print(next(myit))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Using classes, create your own iterator. Next, use it.
Make it to where it will stop after 20 iterations

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is polymorphism in terms of a function and class?

A

Basically this is just child classes inheritting their parents methods and using them.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

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?

A

def __str__(self):
print(‘Welcome’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Describe the self parameter

A

Describes the current instance of the class

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

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)

A

print(person.age)
del person.age
del person

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What are two different names for
Parent Class
Child Class

A

parent - base class
child - derived class

17
Q

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”)

A

x.printname()

18
Q

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

A

class Student(Person)

19
Q

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

A

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
20
Q

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

A

class Student(Person):
def __init_(self, fname, lname):
super().__init__(fname, lname)

with super the “self” parameter is not required.

21
Q

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()

A

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

22
Q

In the below code, would x be a local variable for the nested function named ‘myinnerfun():’?

23
Q

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()

A

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

24
Q

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())

A

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

25
Q

In terms of the below code, what would you call word vs ‘nathan’

my_function(word)

me = my_function(‘nathan’)

A

word - this is a parameter
‘nathan’ - this is the argument

basically:
parameter is the variable
argument is the content of that variable

26
Q

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?

A

*kids - Arbitrary argument

def my_function(*kids):
print(‘the youngest child is ‘ + kids[2])

my_function(‘emil’, ‘tobias’, ‘linus)

27
Q

What are keyword arguments?

Show how you would use them

A

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”)

28
Q

Can you pass a list as an argument?

A

YES

def my_function(food):
for x in food:
print(x)

fruits = [“apple”, “banana”, “cherry”]

my_function(fruits)

29
Q

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

A

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)

30
Q

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.

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

31
Q

Create a lambda function that can take two arguments and multiply them

A

x = lambda a, b : a * b
x(12,14)

32
Q

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

A

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))

33
Q

How do you create a module?

A

In the same folder add more python files:
import whatever

34
Q

you have a module named fart. Give fart an Alias of mx

A

import fart as mx

35
Q

Show all function in the platform module

A

import platform
print(dir(platform))

36
Q

only import randint from random

A

from random import randint