def scope_test():
def do_local(): # nested function --- only available inside scope_test()
spam = "local spam"
def do_nonlocal():
nonlocal spam
spam = "nonlocal spam"
def do_global():
global spam
spam = "global spam"
spam = "test spam"
do_local()
print("After local assignment:", spam)
do_nonlocal()
print("After nonlocal assignment:", spam)
do_global()
print("After global assignment:", spam)
nonlocal turns the name spam into a local name inside the function scope_test
global turns the name spam into a global name in the entire module.
As for our lab, we worked on more recursion. I was happy that I was able to finish both of the required functions as well as one of the bonus ones. Here is the code if anyone is interested.
def find_num(SL: 'SearchList', n: int) -> bool:
if n < SL[0]:
return (find_num(SL[1], n) if isinstance(SL[1], list) else False)
elif n > SL[0]:
return (find_num(SL[2], n) if isinstance(SL[2], list) else False)
elif n == SL[0]:
return True
def freeze(x: object) -> object:
if isinstance(x, list):
return [freeze(item) if isinstance(item, list) else item for\
item in x]
else:
return x
def rev_string(s):
if n < SL[0]:
return (find_num(SL[1], n) if isinstance(SL[1], list) else False)
elif n > SL[0]:
return (find_num(SL[2], n) if isinstance(SL[2], list) else False)
elif n == SL[0]:
return True
def freeze(x: object) -> object:
if isinstance(x, list):
return [freeze(item) if isinstance(item, list) else item for\
item in x]
else:
return x
def rev_string(s):
string = ''
for x in range(len(s) - 1, -1, -1):
string += s[x]
return string
p.s. we touched on methods a little bit more.
class a:
def b():
return 2
if I did a.b(), it would return 2.
however, if I did this:
c = a()
c.b()
I would get an error because now the class a has an argument now, which is the name c.
No comments:
Post a Comment