UNIT 3 Flashcards

1
Q

Recursion and how to exit the function

recursion is implemented using _________ , ISA example of recursion

A

a function calls itself to solve smaller instances of the same problem. This process continues until it reaches a stopping condition known as the base case.

Base Case: the simplest subproblem can be the problem can be reduced to

Recursive case: the part of the recurssion function where function calls itself to solve a simpler program

recursive step: performs repeating action until the subproblem cant be broken down anymore

it breaks down the prob ex factorial if input is 5 is goes in reverse until base condition and finds 0! then
then uses the value returned and then adds it from ex 0 or other functions like 1!… till 4!*5 =120, possible to iterate each value (Fibonacci series)

if value is added outside the recurring function it adds that value to lets say the returned value of 0 or u can directly input function values it will start from first and go to end

calling the function inside the function until it repeatedly until it reaches base case, else goes into an infinite loop
where is it use:

Solving problems with repeated patterns

simplify complex problems into smaller, easier problems

Handling unknown levels of depth (number of steps to a problem) to exit a function u can press return

using stack because activation records are
to be stored in LIFO order (last in first out).

activation record: arguments, return
address and local variables of the function

Stack is a linear data structure in which elements are inserted to the bottom and deleted from the top.

STACK MEMORY ALLOCATION:
contiguous blocks of memory (Function call Stack)

size of memory known to compiler, and memory is allocated when function is called

local memory such as variable intil. inside functions are stored as temp on function call stack and deleted once function returns

allocation of memory is handled by compiler using predefined routines

example of recursion:

def fact(n): #Recursive Function
if n == 0 : #BASE CASE
res = 1
else:
res = n * fact(n - 1)
return res

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

Recursion V Iteration

A

Recursion
Function calls itself

Implemented using Function calls

Termination condition is defined within
the recursive function

Leads to infinite recursion, if does not
meet termination condition

It is slower than iteration

Uses more memory than iteration

ITERATION

Set of program statements executed
repeatedly

Implemented using Loops

Termination condition is defined in the
definition of the loop

Leads to infinite loop, if the condition in
the loop never becomes false

It is faster than recursion

Uses less memory compared to recursion

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

callback function, and code example adv and dis and built in function, and calling multiple functions

A

a function passed to another function as an argument

Calling function (outer function) can call the callback function as many times as required
* Calling function can pass appropriate parameters according to the task to the called functions. This allows information hiding.
* Improves code modularity and reusability
* Allows you to dynamically change the working of a function without changing its core implementation

example code

def add(a,b):
print(a+b)
def mul(a,b):
print(a+b)
def divide(a,b)
print(a/b)
def compute(func, a,b)
func(a,b)
compute(add, 5,3)

the func can be any name

function is called inside an other function and its calculation is done

EXAMPLE built in function= li.sort(key=len)

MULTIPLE FUNCTIONS CALLED ONCE USING LIST
similar to function of decorator

def function(func_list, x, y):
print(“Inside function”)
for func in func_list:
def add(x,y):
z = x+y
print(‘Sum =’,z)
def divide(x,y):
z = x/y
print(‘Quotient =’,z)
cb_list=[add, divide]
function(cb_list, 10, 5)

the func is called into function and then for loop is used to go throu all the functions, and then cb_list is used to add all the funcs into a list and then call the function which has all the funcs with values

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

what is closure with example

A

a nested function which has access to a free variable from an enclosing function that has finished its execution.

a nested function which
inner function is defined inside another function,

the inner function has access to variables and of the outer function

  • It has access to a free variable in outer scope
  • It is returned from the enclosing function
  • A free variable - a variable that is not bound in the local scope.

Closures with immutable variables such as numbers and strings - use the nonlocal keyword.

even if u del the outer fun u can still do the same function using the inner function

python example:
def outer(msg): #outer function
def inner(): # This is the nested function
print(msg) msg=free var
return inner # returns the nested function
another example:

def division(y): #outer function
def divide(x): #inner function
return x/y
return divide
Output:
10.0
32.0
return divide
d1=division(2) #refers to divide
d2=division(3) #refers to divide
print(d1(20))
print(d2(96))

free var is accessed by outer hence thats used
THUS,
IMP: ID of both outer function and inner function is the same

Not all nested functions are closures

for it to be closure:
The inner function has access to the non-local variables or local
variables of the outer function.
2. The outer function must return the inner function.

NON LOCAL VARIABLE
def f1(): #outer function
x=0
def f2(): #inner function
nonlocal x # x - that belongs to scope of outer function is made non-local
x=x+1
return x
return f2

when when var is not declared on the outside variable, u have to use non local, to describe the var so that its non local and can be used in the outer function

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

Decorators

A

it allows to modify the behavior of function or class. without modifying the base function/source code or When we need to run the same code on multiple functions. This avoids writing duplicate code.

Eg: logging, test performance, verify permissions and so on

A Decorator is just a function that takes another function as an
argument and extends its behavior without explicitly modifying
it.

Decorators wrap a function and modify its behavior in one or the other way, without changing the source code of the function being decorated.

functions are taken as the argument into another function and then called inside the wrapper function.

multiple decorators can be used in a single function= chaining

example code

def add_sprinkles(func):
def wrapper():
print(“*You add sprinkles *”)
func()
return wrapper
@add_sprinkles
def get_ice_cream():
print(“Here is your ice cream”)

Normal code without @
def func_decorator(func):
def inner_func():
print(“Hello, before the function is called”)
func()
print(“Hello, after the function is called”)
return inner_func
def func_hello():
print(“Inside Hello function”)
hello = func_decorator(func_hello)
hello()

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

what is a generator

A

Code to check above generator function

is a function that returns an iterator that produces a sequence of values when iterated over

Iterator - an object that can be iterated upon, like a list
it returns an iterator object with a sequence of values.

A yield statement is used instead of the return statement. the function doesn’t immediately execute and print the value. Instead, it pauses execution and produces a value that can be accessed later.

When the generator function is called, it does not execute the function body immediately. Instead, it returns a generator object that can be iterated over to produce the values.

Generator functions return a generator object that is iterable (used as an iterator).

Generator objects are accessed
* by calling the next method of the generator object
* using the generator object in a “for” loop(generator expression)

def generator_function_name(arg): ………………………
………………………
………………………
yield statement

FOR LOOP

Generator function
def generator_func():
yield 1
yield 2
yield 3
for value in generator_func():
print(value)

CALLING THE NEXT METHOD

Generator function
def generator_func():
yield 10
yield 20
Output:
10
yield 30
#obj is a generator object
obj=generator_func()
when u print obj u get:
<generator object gen at 0x7f43eda29170>
# Iterating over the generator object using next
print(next(obj))
print(next(obj))
print(next(obj))

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

Generator expression aka for loops and pipeline

A

Generator function - square

  • is another way of writing the generator function.
    *Similar to list comprehension technique but instead instead of storing the elements in a list in memory, it creates generator objects.
  • Syntax:
    for element in iterable)

allows for the declaration of a function that behaves like an iterator, making it a faster, cleaner ,easier way to create an iterator.
* are useful to produce a large sequence of values, but don’t want to store all of them in memory at once.
* The simplification of code is a result of generator function and generator expression support provided by Python.

EXAMPLE CODE

generator_exp=(i**2 for i in range(5) if i%2==0)
for i in generator_exp:
print(i)

Pipe line Generators:
Multiple generators can be used to pipeline a series of operations

Generator function - fibonacci_numbers
def fibonacci_numbers(nums):
x,y=0,1
for i in range(nums):
x,y=y,x+y
yield x
def square(nums):
for num in nums:
yield num**2
print(sum(square(fibonacci_numbers(3))))

here

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

multiple decorators chaining decorators

A

Chaining Decorators - Decorating a function with multiple decorators.
def decorator_x(func):
def inner_func():
print(“X”20) #Printing X 20 times
func()
print(“X”
20) #Printing X 20 times

return inner_func
def decorator_y(func):
def inner_func():
print(“Y”20) #Printing Y 20 times
func()
print(“Y”
20) #Printing Y 20 times
return inner_func

def func_hello():
print(“Hello”)
hello = decorator_y(decorator_x(func_hello)) #Chaining Decorators
hello()
Output:
YYYYYYYYYYYYYYYYYYYY
XXXXXXXXXXXXXXXXXXXX
Hello
XXXXXXXXXXXXXXXXXXXX
YYYYYYYYYYYYYYYYYYYY

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

yield vs return

A

YIELD
Returns a value and pauses the execution
while maintaining the internal states

Used to convert a regular Python function into a generator

Used when the generator returns an
intermediate result to the caller

Code written after yield statement
execute in next function call

It can run multiple times

RETURN

Returns a value and terminates the
execution of the function

Used to return the result to the caller statement

Used when a function is ready to send a
value

Code written after return statement
won’t execute

It only runs a single time

We can’t include return inside a generator function. If we do, it will terminate the
function.

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

what are GUI and tkinter
syntax GUI

A

provide an intuitive and visual method of interacting with software applications.

import tkinter
root = tkinter.Tk() #creates window
root.mainloop() #loops continuously until we close the window

mainloop()
* A function that continuously loops and displays the window till we
close it or an action closes the window.

until the user exits
the program by closing the window, or by terminating the program

can track the movements of the mouse on the window because it
constantly loops

syntax of GUI

import tkinter —> imports tkinter
root.tkinter.Tk() —> creates a new window
root.title(“ “) —>used for writes title
root.geometry(‘ ‘) —> used for defining dimensions of the window

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

what are widgets

A

After creating window, we need to add elements to make it more
interactive.
Those are called widgets
Each element in tkinter is a widget

Each separate widget is a Python object.

in widget, we must pass its parent as a parameter to the widget creation function.
* The ‘root’ window is an exception as it is the top-level window that will
contain everything else and does not have a parent.

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

types of widgets and basic syntax

A

Steps to add widget to the Window
1. Create widget
2. Add it to the Window

To display it we need:
pack() - packs widgets in rows or columns (stacking layout)
2. grid() - position widgets using rows and column table like layout
3. place() - explicitly set the position and size of a window, either in
absolute terms, or relative to another window. can place anywhere unlike grid and pack() and grid()

button
cavnas —> To draw a complex layout and pictures (like graphics, text etc.)
Checkbutton—> To display a number of options as checkboxes
Entry—-> To display a single-line text field that accepts values from the user
Frame —> To group and organize other widgets
Label —> To provide a single-line caption, can contain images also.
Listbox —> To provide a user with a list of options
Menu —> Creates all kinds of menus required in the application
Menubutton —> To display the menu items to the user
Spinbox->“entry” widget in which value can be input just by selecting a fixed value of numbers

Panned window: A container widget that is mainly used to handle different panes

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

button

A

b=Button(parent,options)

from tkinter import *
win =Tk() => button syntax
win.title(“TITLE”)
win.geometry(‘300x200’)
b=Button(win, text=’Submit’)
b.pack()
=> adds the button to the window
win.mainloop()

BUTTON FUNCTIONS
from tkinter import messagebox
#message box
def click():
messagebox.showinfo(“Message”, “Green”)
(message box appears)

=> pady = height of button
activeforeground=”yellow”
@color of text when clicked
activebackground=”orange
@color of button when u clicked

=>side=LEFT direction of side

=> command=click
when u click action can happen, its a function name, can be any name

EXAMPLE OF BUTTON SYNTAX
c=Button(win,text=”Green”, command=click,
activeforeground = “green”,activebackground=”orange”, pady=10)

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

CANVAS

A

W=Canvas(parent,option
=value)

cv=Canvas(win, bg = “red”, height =”300”)
=> win= parent name
cv.pack()
win.mainloop()

creating arcs
coord = 10, 10, 300, 300
#boundary of circle
x1,y1,x2,y2
arc1=cv.create_arc(coord, start=0, extent=150, fill=”pink”)
arc2=cv.create_arc(coord, start=150, extent=215, fill=”green”)

IMPORT PICTURE
filename=PhotoImage(file=”nature.png”)
image=cv.create_image(20, 20, anchor=NW, image=filename)

This creates an image on the canvas cv at the coordinates (20, 20),
anchor=NW: This means the top-left corner of the image will be anchored at the coordinates (20, 20). NW stands for the “North-West” corner (top-left).
image=filename: specifies the image

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

functions of checkbutton, and radio button

A

W = Checkbutton(parent,option=value)

from tkinter import *

cb1=Checkbutton(win,text=”Yes”, varible=1)
cb1.pack()

k= IntVar() print the boolean val, with the help of a button, when checked(1), unchecked(0)
String(var) also used

.get(): Retrieves the current value stored in the var or IntVar().

onvalue= can be int or string use String(var)
offvalue=same thing normal OUT=bool

RADIO BUTTON:
allows u to click only one option

Radiobutton(funcname, option)

1)deselect() – to turn off the checkbutton
2) flash(): The checkbutton is flashed between the active and normal colors.
3) invoke(): invoke the method associated with the checkbutton.
4) select(): to turn on the checkbutton.
5) toggle(): to toggle between the different Checkbuttons.

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

syntax and functions of entry widgets

tkinter message box dialog
syntax for message box

A

W = Entry(parent,options)
1. get() – Returns the entry’s current text as a string
2. delete(): Deletes characters from the widget
3. insert(index,name): Inserts string ‘name’ before the character at the given index

e2 = Entry(f1, width=20, show=”*”) field
e2.place(x=100, y=90)
*show function displays the what entry box text should be shown as

FOR PASSWORD EX

result.config(text=”Login Success!”, fg=”green”)
.config used to update the config of widget

Provide messages to the user consists of text and image data.
messagebox.function_name(Title, Message, [,options] )

17
Q

syntax for custom message when button is pressed after checkbox is selected

A

chk1=StringVar()

def clk():
print(chk1.get())

variable=chk1

this FUNCTION clk(), is called in button
b1=Button(win,text=”check”,command=clk)

Vars to hold the state of the checkbuttons
ckb1_var = tk.IntVar()

18
Q

combos(drop down list)

A

combo=Combobox(win)
combo[‘values’]=(1,2,3,4,5,’Text’)
combo.current(1)
combo.pack()

19
Q

LABEL WIDGET

A

=Label(parent, value = “”).place(x = 30,y = 50 )

.place = position of where i should be

ENTRY
Entry(parent,options)

to enter or display single line of text

20
Q

message box

A

messagebox.function_name(Title, Message, [,options] )
from tkinter import messagebox

showinfo() important information

showwarning() some type of warning

showerror() error message

askquestion() a dialog box that asks a question with two options: YES or NO

askokcancel() a dialog box that asks a question with two
options: OK or CANCEL

askretrycancel() asks a question with two
options: RETRY or CANCEL

askyesnocancel() a question with three
options: YES or NO or CANCEL

messagebox.showinfo(“Warning”,”why!”)

21
Q

Frames

A

A frame - rectangular region on the screen.
* Used to implement complex widgets.
* Organize a group of widgets.

W = frame(parent,options)

frame=Frame(parent) #main frame

frame.pack() #positions the frame in the default location (top-center).

bottomframe=Frame(win)
bottomframe.pack(side = BOTTOM )
or (side=”bottom”)
#for bottom frame
relative to the main frame

dimensions of FRAMES
frame1=Frame(win,bg=
“black”,width=500,height=300)

NESTED FRAME
from tkinter import *
root = Tk()

Outer frame
f1 = Frame(root, height=420, width=420, bg=”black”)
f1.pack()

Nested frame inside f1
f2 = Frame(f1, height=269, width=269, bg=”gray”)
f2.pack(pady=20, padx=20)
root.mainloop()

22
Q

Module

A

.py only

  • reduced redundancy, maintains uniformity in code
  • increases readability and bug reporting

Code Organization: reusable and clear components.
Namespace Management: prevent conflicts between var and func names by separating different parts of the program.

Dependency Management: Python’s package management (e.g., pip) uses modules to install and manage external libraries

IMPORT MECHANISM

Source Code Compilation:

When module is imported, Py checks if there is a .pyc (compiled) file in the __pycache__ DIR.
else, it compiles the source code (.py file) into bytecode.

Byte Code Storage:
stored in the __pycache__ directory.
it can be reused on different systems. (Platform independent)

Subsequent Imports:

a. If the source code remains unchanged, it uses the existing .pyc file for subsequent imports, skipping compilation step for improved performance.

b. If the source code is changed, .pyc must be created again, and __pycache__ directory will be updated.

when u import a py file 1st time and 2nd time why no output?
.pyc is the recent in pycache. even if we modify the file, wont work as it creates the .pyc in the same interpreter session. doesn’t check the time stamp of module.
use reload()

23
Q

Loop of colors to create rainbow colors

A

import tkinter as tk

root = tk.Tk()

Loop through the colors and create frames
for color in [“black”, “gray”, “green”, “white”, “black”, “yellow”, “red”]:
frame = tk.Frame(root, height=50, width=200, bg=color)
frame.pack() # Add some vertical spacing between frames

root.mainloop()

24
Q

WAYS OF IMPORTING MODULES

A

TIP:

when u import a py file after changes it wont be made as it creates the .pyc in the same interpreter session. doesn’t check the time stamp of module.
use reload() try restarting your Python interpreter session.

it checks the timestamp of module imported and the .pyc file. If the timestamp of the module is the recent one, it builds the .pyc and runs again. Else, simply runs again.

import importlib
import new#new=filename
importlib.reload(new)

in CMD
import FILENAME
dir() to see module name
in symbol table

DOT OPERATOR
allows you to access functions, variables, or classes defined in a module.
ex:
import filename
filename.func()
filename.a #for vars

USING ALIAS
import module1 as m
m.f1()
print(“value is”,m.a)
m.a=m.a+2 #allowed
print(“value is”,m.a)

BUT CANT DO SELECTIVE IMPORTS, here identifier name added directly into symbol table

USING FROM
from filename import var/func in ANOTHER file

when u use dir() on the module or the functions, it will show the function names, not module name!

USING import*, identifiers with underscores_ (are not IMPORTED!)

when funcs are imported, u must call them

25
Q

BUILT in FUCTIONS IMPORT

A

Usage of built-in module-
to print current working directory
import os
cwd=os.getcwd()
print(“CWD:”, cwd)

USING BUILTIN functions module os to list the files and directories

import os
path = “/”
dir_list= os.listdir(path)
print(dir_list)

26
Q

modules from diff directories

A

module in directory MyLib

When we import modules, python interpreter locates from :
⮚ The directory from the program is getting executed.
⮚ The directory specified in the PYTHONPATH variable
⮚ The default directory

sys provides access to some objects used or maintained by the interpreter and to functions that interact strongly with the
interpreter

sys.path is a list that gets interpreter’s search path for modules. When import a module, Python looks for it in directories listed in sys.path. The sys.path list can be modified during runtime to add or remove directories. to modify:
append and insert.

append:
adds a dir to the end of the sys.path list.

will search for modules in this dir only after checking the directories already present in the list.

import sys
print(“Original sys.path:”, sys.path)
#sys.path:contains the directories where the interpreter looks for modules.
sys.path.append(“/path/to/new/directory”)
#adds the specified directory
print(“Modified sys.path:”, sys.path)
append:
adds a directory to the end of the sys.path list.

INSERT:
can add a dir at a specific position in the sys.path list.
takes: The index and dir

import sys
print(“Original sys.path:”, sys.path)
new_dir = “/path/to/new/directory”
sys.path.insert(0, new_dir)
print(“Modified sys.path:”, sys.path)

=> print(sys.path), can verify path is added

27
Q

change modules path to diff dir using insert function

A

import MyLib.module# error, as py cant find this dir

MyLib/module.py

module in directory MyLib

def func():
print(“hello”)
#filename: ex_module.py

import sys
sys.path.insert(0, ‘/home/csestaff/rbs/python/Mylib’)
print(sys.path)
import module
module.func()

28
Q

What happens if user defined module name is same as built in module name?

__name__

A

Special Vars/attributes
__name__

inbuilt global var:
has name of the module. the var = main if you run the code in script mode.

This var gets its value depending on how we execute the containing script. It returns the name of the module(excluding .py) if the module is the imported. Else, it returns main

SYNTAX:
filename.__name__

name attribute is set to main on the interpreter
»>_name
‘__ main__’

any py script its name attribute is also set to main, ↑ else if a script is imported to another script instead of main its set to file name itself

can be if statements like
if __name__==’__main__’

29
Q

Testing-Pytest

A

a robust testing framework

allows users to write test codes

can write from simple unit to complex functional tests.

framework=> set of tools and libraries designed to streamline development

ADV:
Free, open source
* Simple syntax
* multiple tests in parallel, less execution time of test suite
* Automatically detect test file and test functions, if not mentioned
* Allows to skip a subset of the tests during execution
* Allows to run a subset of the entire test suite

FEATURES
no need of API to use
2. gives useful plugins
3. Can be written as a function or method
4. Gives useful failure info without debuggers
5. Can be used to run doc tests and unit tests

-to use pytest = put pytest -in cmd
-put dir of file
-pytest filename.py

Passed test: test ran sucessfully, no errors

Failed Test: Test did not pass

Warnings: Non-critical issues, such as deprecations, bad practices. wont case test to fail

30
Q

assertion

A

assertion: expression tested for truth else=> AssertionError

31
Q

doctest

A

module in py

easy generation of tests on output from standard Py interpreter shell.

finds patterns in docstring.
* Docstrings - description of a class/function to provide better understanding of code. Used for testing using
doctest

Need for Doctest
* To check that a module’s docstrings are up-to-date (to ensure code still
work as documented).
* To perform regression testing (verifying the changes made to the code

will not impact the existing functionalities of the Software).

32
Q
A