Functions And Modules Flashcards

1
Q

Function arguments?

A
Required
Keyword
Default
Variable-Length
(Positional Argument assigned based on its position and keyword: based on parameter name)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Keyword arguments

A

PRO:
1. change the order of parameters when calling than while defining.

The argument should not receive value more than once and no argument should be left behind.

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

Default arguments

A
Assumes a default value if no value assigned when calling. c is an example.
Default arguments should not be followed by non-default while declaring the function.
Syntax
def func(a,b,c= 'value'):
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Variable-length Arguments

A
Syntax:
def func(a,*b):
  1. The arbitrary no. of arguments passed, form a tuple.
  2. Should be last in the list of a formal parameter only keyword arguments can be after it.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Lambda Functions

A
  • can take any no. of args.
  • no explicit return statement but always returns an expression.
  • can be passed as arg to a func.
    (also look at example 5.28, 204)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Nested lambda functions

A
name = lambda args: exp
name2 = lambda x,y,z: x*(name(y,z))

print ( ( lambda x,y,z : x*(lambda x,y: x+y)(y,z) ) (1,2,3))

The occurrence of recursion and runtime error of recursion depth may occur.

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

The number of expressions in lambda functions.

A

1

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

Use of lambda function?

A

usually when created only, hence called thrown away.

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

Syntax of lambda

A

lambda arguments: expression

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

passing args to lambda

A

(lambda x:x2) (9) # 9 being the arg passed.
OR
twice = lambda x:x
2
print ( twice(9) )

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

Documentation Strings

A

Explain code, same as a comment but are retained throughout the runtime of the program. So users can inspect during program execution.

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

Docstring declaration

A
def func():
    "Func \_\_docdtring\_\_"
  • triple quotes to extend it to multiline.
  • in case of multiline second line should be blank.
  • first non blank line after first line of docstring determines indentation’s amt for rest of docstring.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Docstring good rules

A
  • First line: short n concise highlighting summary n purpose.
  • objects name n type info NOT needed.
  • begin with capital letter n end with period.
  • describe objects calling conventions, its side effects.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

how to know what a function does?

A

functionName.__doc__

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

Recursive function

A

A function that calls itself to solve a smaller version of its task until a final call is made which does not require a call to itself.

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

parts of recursive function:

A
  1. A base case: here problem in its simplest to solve without calling itself.
  2. Recursive Case: Problem here divided into subparts and calls itself with subparts and then the result is obtained by combining the result from simpler subparts.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

what error if no base case in recursive function?

A

infinite stack.

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

The technique utilisez by recursion?

A

Divide n conquer.

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

Base case significance:

A

It acts as a terminating condition so it doesn’t call itself infinitely.

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

factorial by recursive:

A

Base case: if n==0 or n ==1:
return 1
Recursive case: factorial = n * factorial (n-1)

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

Greatest common denominator by recursive:

A

return b, if a%b==0

GCD( b , a%b )

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

Exponent ( x, y ) by recursive:

A

if n == 0, return 1
else:
x*exp(x,y-1)

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

The Fibonacci Series:

A
if n <2: return 1
return fib(n-1)+fib(n-2)

then use for i in range: print fib(i) to print out the series.

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

Recursion Vs Iteration

approach type:

A

R is a top-down, original problem divided in smaller problems.
Itr is bottom-up.

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

Recursion economics

A
  1. require substantial amt of run-time overload.
  2. In recursive function during execution before moving to smaller parameter, all the information ( original parameters, local variables, return address of calling function ) are stored on the SYSTEM STACK.
  3. So time is required to first push the information on the stack and then again to retrieve the stored information on the stack when control passes back to calling function.
26
Q

Recursive Pros

A
  1. recursive solutions tend to be simpler.
  2. The code is neat to use.
  3. uses the original formula to solve.
  4. follows divide n conquer.
  5. some (limited) instances recursion may be more efficient.
27
Q

Recursion Cons:

A
  1. Some programmes find it hard to grasp.
  2. System stack is used which is limited and deeper level recursion will be difficult to implement.
  3. Aborting it in midstream slow and nasty.
  4. difficult to find bugs particularly when using global variables.
28
Q

Good programming practices:

A
  1. 4 spaces instead of tabs.
  2. insert blank lines to separate functions and classes, and statements blocks inside functions.
  3. Wherever required, use comments to explain the function.
  4. use docstrings that explain the purpose of the function.
  5. use spaces around operators and commas.
  6. name of the class should be like ‘ ClassName ‘
  7. name of the function should be lowercase with underscores to separate words.
  8. Don’t use non-ASCII chars in function names or any other identifier.
29
Q

Module

A

a file with .py extension, that has definitions of all functions and variables that might be used in other programs.
pre-written pieces of code that are used to perform common tasks like generating random numbers..etc.

30
Q

How to use the module and access its functions?

A

add in ur first line of the program:
import module_name
to access var:
module_name.var

31
Q

sys significance:

A

functionality related to its interpreter and its environment.

32
Q

sys.path and where to save modules?

A
directories ka address, python first checks in current working directory and then in these directories to import module.
If u want the module to be available to other programs as well then save it in the directory specified by PYTHONPATH, or store in python installation lib directory.
33
Q

.pyc and ways to make it

A

compiled version of the module, created after loading once.

reload() function can force to create new .pyc

34
Q

the from.. import statement

A

to import >1 item from module_name use ‘ , ‘.

from module_name import item1, item2

to import all:
from sys import*
- * does not include private identifiers ( ones starting with ' \_\_ ' )
(this use creates confusion in variables in ur code with vars in external module so void it)
35
Q

import item1 but give it diff name to use:

A

from math import sqrt as square_root

36
Q

Pass command line arguments:

A

import sys
print(sys.argv)

go to the command prompt
C:\Python34> python main.py Hello World

Output
[‘main.py’ , ‘Hello’, ‘World’]
——————————————————————–
a = int( sys.argv[1] ); b = int( sys.argv [2] )

37
Q

Exit python using sys module:

A

sys.exit()

the argument is optional, can be int giving exit status or another type of object. zero implies successful termination and non zero doesn’t.

38
Q

Name of Module

A

print(__name__)
to get the name of the current module, usually, __main__ is the name for every standalone program written by user.
and they named by lowercase and _ to separate

39
Q

Making your own Modules

A

Every python program ( file tht u save as .py ) is a module.

recall storing modules to avoid ImportError.

40
Q

dir() function:

A

A built-in function that lists the identifiers defined in a module. identifiers include : function, classes, variables.
Synatax:
»>dir(Module_name)
if used in a file and no argument passed then works on file. ( u get __doc__ , __file__ , __package__ , __builtins__ , __name__ along with the one defined in module. )

41
Q

The python Module:

A

Main module has a special name __main__ which imports any number of modules but it cannot be imported to other modules.

42
Q

Modules and Namespaces:

A

A namespace is a container that provides a named context for identifiers.
- Avoid potential name clashes by associating identifiers with namespace from which it origins.
——————————————————–
module_name.identifierName

43
Q

how many Namespaces are there and who are they and describe them?

A

3
Local : currently executing function.
Global : Identifiers of currently executing module.
Built-in : Contains names of all builtin functions, constants..etc already defined in python.

44
Q

Module private variables:

A

All identifiers are public by default ( accessed by importing modules).
(__): Identifiers who start with 2 underscores are private, not accessed from outside module.

45
Q

Advantages of Module:

A
  • benefits of modular design
  • Reusability of code
  • std lib which contains a set of modules allows u to logically organize the code so that it becomes easier to use and understand.
46
Q

module keypoints:

A
  1. loaded once even if imported more.
  2. module can import other modules.
  3. not mandatory to place all import statements on top.
47
Q

Packages are what? its rules?

A

A hierarchical file directory structure tht has modules and other packages in it.
Every package is a directory which must have a special file called __init__.py
that file may not have a single line of code, but its there to indicate its not ordinary and contains python package.

48
Q

what makes a directory diff from package?

A

Every package is a directory which must have a special file called __init__.py
that file may not have a single line of code, but its there to indicate its not ordinary and contains python package.

49
Q

Importing package:

A

import Package.Module

OR

from Package import Module

50
Q

__init__.py file

A
  • It may be used to execute initialisation.
  • ## Determines which modules the package exports as the API ( application program interface ), while keeping other modules internal, by overriding the __all__ variables__init__.py
    __all__ = [“Module”]
51
Q

Where to store package?

A

in paths specified by sys.path

52
Q

__path__ attribute associated with package:

A

Initialised with a list having name of directory holding the package. Can be modified to change the future searches for modules and sub-packages stored in it.
Allows package in multiple directories.

53
Q

import item.subitem.subitem

A

item : package
on its right can be a subpackage or submodules
on its right the function name (optional)

54
Q

__all__

A

A list defined in package, it is taken to be the list of module names that should be imported when from package import * is encountered.

55
Q

Standard library Modules:

A

Pre-Installed modules. Some written in python and some written in C.
string, re, datetime, math, random, os, multiprocessing, subprocess, socket, email, json, doctest, unitest, pdb, argparse, sys.

56
Q

3 types of modules:

A
  1. Written by user.
  2. Installed from external sources.
  3. pre-installed in python.
57
Q

locals()

A

called within a function, returns names tht can be accessed locally from that function.

Returns names using dictionary, names can be extracted using keys() function.

58
Q

globals()

A

called within a function, return all the names accessed globally from that function.

Returns names using dictionary, names can be extracted using keys() function.

59
Q

Reload()

A

reload ( module_name)

to re execute top level code in module, as module is executed only once.
- Imports a module that was previously imported.
60
Q

Function Redefinition:

A

x = 5.6
:
x = ‘Hello’
Just like we redefine variables, functions can be redefined as well.

61
Q

Scope of variable

A

Part of program in which var is accessible

62
Q

Lifetime of variable:

A

Duration for which it is accessible.