Podcast
Questions and Answers
What is the primary purpose of a function in Python?
What is the primary purpose of a function in Python?
- To automatically manage memory allocation.
- To define a new data type.
- To create a named sequence of statements that can be executed. (correct)
- To handle hardware interrupts.
Which of the following is NOT a characteristic of Python functions?
Which of the following is NOT a characteristic of Python functions?
- They facilitate code reusability.
- They can take parameters.
- They can perform computations.
- They cannot return values or objects. (correct)
What does the abs(x)
function in Python return when x
is a complex number?
What does the abs(x)
function in Python return when x
is a complex number?
- The magnitude of the complex number. (correct)
- The real part of the complex number.
- An error, as `abs()` cannot handle complex numbers.
- The imaginary part of the complex number.
What will bool()
return if no argument is provided?
What will bool()
return if no argument is provided?
Which of the following values will evaluate to False
when passed to the bool()
function?
Which of the following values will evaluate to False
when passed to the bool()
function?
What is the purpose of the chr(x)
function in Python?
What is the purpose of the chr(x)
function in Python?
What happens if the integer argument provided to chr(x)
is outside the valid range?
What happens if the integer argument provided to chr(x)
is outside the valid range?
In Python 3.x, what is the recommended alternative to the deprecated cmp(x, y)
function?
In Python 3.x, what is the recommended alternative to the deprecated cmp(x, y)
function?
What does the divmod(x, y)
function return in Python?
What does the divmod(x, y)
function return in Python?
What will happen if y
is equal to 0 when calling the divmod(x, y)
function?
What will happen if y
is equal to 0 when calling the divmod(x, y)
function?
Which data types can the float()
function accept as parameters?
Which data types can the float()
function accept as parameters?
What is the purpose of the id(object)
function in Python?
What is the purpose of the id(object)
function in Python?
What is the return type of the int(x)
function?
What is the return type of the int(x)
function?
What happens if the argument passed to int(x)
cannot be converted to an integer?
What happens if the argument passed to int(x)
cannot be converted to an integer?
What types of arguments can be passed to the len(x)
function?
What types of arguments can be passed to the len(x)
function?
Which of the following represents a valid way to call the range()
function?
Which of the following represents a valid way to call the range()
function?
What does the round(number, ndigits)
function do if the ndigits
argument is omitted?
What does the round(number, ndigits)
function do if the ndigits
argument is omitted?
What is the primary purpose of the str(object)
function?
What is the primary purpose of the str(object)
function?
What happens if an object does not provide its own string version when passed to str(object)
?
What happens if an object does not provide its own string version when passed to str(object)
?
What is the primary purpose of the tuple(iterable)
function?
What is the primary purpose of the tuple(iterable)
function?
What does the function math.floor(x)
do?
What does the function math.floor(x)
do?
Which of the following best describes what the random
module's algorithm is based on?
Which of the following best describes what the random
module's algorithm is based on?
What will always be true when using random.random()
?
What will always be true when using random.random()
?
What is important about the object provided to random.seed()
if you choose to provide an object?
What is important about the object provided to random.seed()
if you choose to provide an object?
How does random.randint(x, y)
differ from other similar random number functions in Python?
How does random.randint(x, y)
differ from other similar random number functions in Python?
What restriction applies when calling random.uniform(x, y)
?
What restriction applies when calling random.uniform(x, y)
?
What statement is true about random.randrange([start], stop, [step])
?
What statement is true about random.randrange([start], stop, [step])
?
What is the purpose of the def
keyword in Python when writing functions?
What is the purpose of the def
keyword in Python when writing functions?
What should all statements inside a function body have?
What should all statements inside a function body have?
What happens if a return statement is without any expression?
What happens if a return statement is without any expression?
What is the flow of execution when a function is called in Python?
What is the flow of execution when a function is called in Python?
What happens to local variables when function call ceases?
What happens to local variables when function call ceases?
What will happen if a local scope and global scope have a variable with the same name?
What will happen if a local scope and global scope have a variable with the same name?
In the context of function calls, what is meant by 'call by value'?
In the context of function calls, what is meant by 'call by value'?
What is the difference between a parameter and an argument?
What is the difference between a parameter and an argument?
If the function caller provides a value for that particular parameter, then what happens?
If the function caller provides a value for that particular parameter, then what happens?
Why use 3rd party libraries and modules?
Why use 3rd party libraries and modules?
How can the Python interpreter determine whether to run or not a module to run due to it being run directly versus imported?
How can the Python interpreter determine whether to run or not a module to run due to it being run directly versus imported?
Flashcards
What is a function?
What is a function?
A named sequence of statements.
What do functions do?
What do functions do?
They take parameters and/or return a result, value, or object.
What does abs(x)
do?
What does abs(x)
do?
Returns the absolute value of a number (positive magnitude).
What does bool([x])
do?
What does bool([x])
do?
Signup and view all the flashcards
Values considered False in Python
Values considered False in Python
Signup and view all the flashcards
What does chr(x)
do?
What does chr(x)
do?
Signup and view all the flashcards
What does divmod(x, y)
do?
What does divmod(x, y)
do?
Signup and view all the flashcards
What does float(x)
do?
What does float(x)
do?
Signup and view all the flashcards
What does id(object)
do?
What does id(object)
do?
Signup and view all the flashcards
What does int(x)
do?
What does int(x)
do?
Signup and view all the flashcards
What does len(x)
do?
What does len(x)
do?
Signup and view all the flashcards
What does range(start, stop[, step])
do?
What does range(start, stop[, step])
do?
Signup and view all the flashcards
What does round(number[, ndigits])
do?
What does round(number[, ndigits])
do?
Signup and view all the flashcards
What does str(object='')
do?
What does str(object='')
do?
Signup and view all the flashcards
What does tuple([iterable])
do?
What does tuple([iterable])
do?
Signup and view all the flashcards
math.ceil(x)
in Python
math.ceil(x)
in Python
Signup and view all the flashcards
math.fabs(x)
in Python
math.fabs(x)
in Python
Signup and view all the flashcards
math.floor(x)
in Python
math.floor(x)
in Python
Signup and view all the flashcards
math.pow(x, y)
in Python
math.pow(x, y)
in Python
Signup and view all the flashcards
random.random()
in Python
random.random()
in Python
Signup and view all the flashcards
random.choice(sequence)
in Python
random.choice(sequence)
in Python
Signup and view all the flashcards
random.uniform(x, y)
in Python
random.uniform(x, y)
in Python
Signup and view all the flashcards
random.randint(x, y)
in Python
random.randint(x, y)
in Python
Signup and view all the flashcards
random.randrange([start], stop, [step])
random.randrange([start], stop, [step])
Signup and view all the flashcards
Keyword def
Keyword def
Signup and view all the flashcards
return statement
return statement
Signup and view all the flashcards
describe parameters
describe parameters
Signup and view all the flashcards
Arguments
Arguments
Signup and view all the flashcards
Rules for default values
Rules for default values
Signup and view all the flashcards
default value
default value
Signup and view all the flashcards
function call
function call
Signup and view all the flashcards
function definition
function definition
Signup and view all the flashcards
keywords
keywords
Signup and view all the flashcards
default values
default values
Signup and view all the flashcards
function definition
function definition
Signup and view all the flashcards
function definition
function definition
Signup and view all the flashcards
format **kwarg
format **kwarg
Signup and view all the flashcards
file
file
Signup and view all the flashcards
recursive function
recursive function
Signup and view all the flashcards
Generator functions
Generator functions
Signup and view all the flashcards
Study Notes
- Functions are named sequences of statements
- Functions contain lines of code executed sequentially from top to bottom
- Functions can perform computations
- A function is executes a block of code
- Functions can be named and reused in a script
- Functions can consist of groups or blocks of statements with a function name
- Functions can take parameters
- Functions can return a result, value, or an object
Some Built-in Functions
abs(x)
- Returns the absolute value of a number
- The argument can be an integer or floating point number
- Returns the magnitude if a complex number is given as the argument
bool([x])
- Square brackets indicate the parameter is optional
- It returns False if an argument isn't given to
bool()
- It converts a value to a Boolean equivalent using the standard truth testing procedure
- If x is False or not given, False is returned, otherwise True is returned
False values List
- Zero (0, 0.0, 0j) is considered false
None
evaluates to FalseFalse
obviously evaluates to False- All empty sequences ([], (), etc.) evaluate to False
- A list containing any element, even a zero, won't evaluate to False
- An empty mapping like an empty dictionary, {}, evaluates to False
chr(x)
- It takes an integer
x
as a parameter - It returns the corresponding "character” to the given integer
- The integer is treated as a Unicode point and the value is the corresponding "character”
chr(x)
maps a Unicode integer number to its corresponding characterchr(97)
returns the string 'a'- Valid values for the argument x are is from 0 through 1,114,111 (0x10FFFF in base 16)
- If the value is outside the valid range it will return a ValueError
cmp(x,y)
- It compares two objects x and y and returns an integer according to the outcome
- It returns -1 if x < y
- It returns 0 if x == y
- It returns +1 if x > y
- The
cmp()
method has been deprecated in Python 3.x ((x > y) - (x < y)
is better to use than using cmp(x,y)- x > y when joined to x < y with a minus sign are implicitly cast into ints
divmod(x, y)
- It takes 2 arguments as numbers x and y
- It returns a tuple of numbers (q, r), where q is the quotient and r is the remainder
- If x and y are integers, the result is the same as (x//y, x% y)
- If either x or y are floats, then q is the whole part of the quotient and r is x - (q*y)
- If y =0, you get Zero Division Error.
- If x = 0, you get (0, 0)
float(x)
- It casts a variable to a floating point number
- It takes as parameters either an integer, long or string
- If the input is a string, it must contain only digits with or without a decimal point and an optional + or - sign
- The parameter can be exponential such as 1.0e6
- The function's return type is a float
id(object)
- It gives the “id” of an object
- The “id” of an integer is unique and constant for this object
- The number returned by the id() function is a unique number for each object
int(x)
- It casts a variable to an integer
- It takes 1 parameter (which may be long, string or float)
- The return type is an integer
- It converts a number or string x to an integer
- It returns 0 if no argument is given to the int() function
- If x can't be converted to an integer, then an error will be thrown
len(x)
- Returns the length of the given object x
- The argument x must either be a sequence (string, range, list or tuple) or a collection (set or a dictionary)
- If the argument s is a string, then len(s) returns the length of the string s
- If the argument is either a sequence or a container, then len(s) gives the number of “items” in the sequence or container
range(start, stop[, step])
- There are 3 versions of this function:
range(stop)
,range(start, stop)
,range(start, stop[, step])
- Only one form of the function, that is, range(n) or range(stop) is discussed for flow control
range(n)
generates a sequence of numbers from 0 to n-1- In Python 2.x on IDLE, inputting
range(5)
will output a list[0,1,2,3,4]
- In Python 3.x, the output is not a list, rather a “range object”
round(number[, ndigits])
- It takes two parameters and returns the "rounded off value” of the given “number”
- The first parameter is the number to be “rounded off”
- The second parameter “ndigits” is optional and denotes the number of digits to which the rounding-off is to be done
- If ndigits is omitted, it defaults to zero
- Square brackets for parameters indicates default values
str(object='')
- It returns a string version of object
- If an object does not provide “its own string version”, then the str(object), returns the empty string
- You can think of it as a “casting” function which creates a cast of the object into a string
- It creates a "string representation” of an object
tuple([iterable])
- Takes an “iterable” as an argument
- Thinks of an iterable as a sequence or a container
tuple([iterable])
, it converts the iterable into a tuple and returns it- When an iterable is converted into a tuple by the
tuple([iterable])
function, the order of items in the tuple is the same as in the iterable - It returns unchanged if the iterable given is already a tuple
Module math
- Has a number of useful functions that need to be imported
math.ceil(x)
returns the “smallest integer not less thanx
."math.fabs(x)
gives the absolute value of x.math.floor(x)
returns the "largest integer not greater thanx
. It gives the "floor" of x.math.exp(x)
: The function exp(x) returns e**x.math.log10(x)
: This method gives the base 10 logarithm of x and is better to use than log(x, 10).math.pow(x, y)
: This function takes two arguments x and y, where x is the “base” and y is the “power” and is like x ** y.
Module random
- The algorithm used to implement a random module in Python is deterministic and based on the initial seed given to the function.
- Deterministic means that when given an initial “seed” the same number is generated every time.
- This is in contrast to a truly random number, such as when a dice is rolled. You can't predict with surety the outcome of a roll of a dice.
- The algorithm used to generate a random number is deterministic; that is it depends on seed.
random.random()
- This is the basic method of the random module
- It generates a random number in semi-open range [0.0, 1.0)
- There is a "square bracket” to the left and a “round parenthesis" to the right in the range [0.0, 1), 0.0 is possible but 1.0 is not.
- You can say that the number generated is 0 ≤ x < 1.0
- Semiopen range here means that the lower limit, that is, 0.0 is included but the upper limit, that is, 1.0 is not.
random.seed([a = None])
:
- The method takes an optional parameter “a” with a default value of None
- You may omit “a”, or if you give a seed of None, then by default, the method uses the current system time as seed value
- You can give an object as value to the optional parameter “a”
- If you give an object as parameter to the seed() method, then this object must be a “hashable” object
- Anything that is immutable can be used as an argument to
random.seed([a])
random.randint(x, y)
- It gives an integer n in the range x ≤ n ≤ y
- The randint function can return the upper limit “y” also, unlike other Python functions
- In Python where other functions in Python exclude the upper limit generally
random.choice(sequence)
- Here the sequence can be any sequence
- The sequence could be a string, list or tuple
- This method returns an item randomly selected from the given sequence
random.uniform(x, y)
- x and y must be numbers
- This method gives a random floating point number f such that x ≤ f ≤ y (or the reverse)
- If x ≥ y, then you get x ≥ f ≥ y
- The upper limit can be included in the range
- Whether "y" will be included or not depends on the rounding in the equation: x + (y - x) * random().
- Suppose you take
range (1,2)
- Suppose that the
random.random()
generates .99999999999999 - Will round off to 1.999
- Suppose that the
random.random()
generates 0.999999999999999999 - Will round off to 2.0
random.randrange([start], stop, [step])
- The function takes 3 parameters
- It requres one mandatory parameter which is "stop" and an optinal
start
andstep
parameters. - “start” parameter is the start point of the range and will be included in the range
- “stop” parameter is the stop point of the range and will not be included in the range
- The "step" parameter indicates the steps to be added in a number to decide a random number.
Defining Functions
- A function definition must have a keyword "def" to indicate the start of the function definition
- Defining a function does not call the function, must make explicit function call
- It must include a function name to uniquely identify it using the same rules as writing identifiers
- Parameters are the optional list of parameters in brackets, separated by commas, can have a function with or without any parameter
- A colon":" marks the end of the function header
- The body of the function has at least one Python statement
- Must have the same indentation level (four spaces)
The return
statement
- Exits function and returns to the function/method call
- Value returned is the "value of the expression" following the return
- Special value
None
is returned without an expression following the return - It can be situated anywhere in the function body
- The body of a function can one or more
return
statements
Flow of Execution
- The order statements in a script are executed is called the flow of execution.
- Program execution beings with the first statement.
- Statements are executed one after the other from top to bottom.
- Function definitions do not affect the flow of execution
- If a function is called, the flow of execution will jump to the function definition and returns to the calling spot after
- You can define one function inside another called nested functions
Variable Scope
- A variable defined inside a function def statement code block is "local” to that function.
- Variables outside the def call code block will always be global
- Both local and global variable will exist when you are inside a function call
- The local variable ceases to exist when outside the function call, and only the global variables exist.
Namespace
- In Python, “names” or “tags” are the code labels with the code
- Each namespace has a “scope”.
- A namespace and the the "scope” determines the "visibility” or “availability”.
- A name is given a “namespace” or a "scope” when it is first assigned
- You have to give a variable name without giving it a value or an object
Call by Value vs Call by Reference
- In most programming languages, there are 2 methods of passing variables between function call and function definition: call by value or call by reference.
Call by Value
- A copy of the variable value is given to the function call.
- No effect to the original value from modification.
Call by Reference
- Both original variable and the variable name point to the same object.
- Modifications to object inside the function call will reflect outside of the function call too
- Python allows both call by value and call by reference
Function Terms
- Function parameters vs Arguments
- Parameters are the variable definitions in the header of function definition or declaration
- Arguments are the values used in the function call, that supply the value to a function's parameter
- There are 3 important function terms: Default, Positional and Keyword arguments
Default Arguments
- Function definition an argument with a default value
- Then an argument doesn't need to be given to the parameter for that function call, but has an option of giving one
- But when a function caller provides a value for a particular parameter, then the default value present in the function will be ignored
- If called without a value passed to that parameter, it defaults to its default value already written in its definition
Rules for default values
- Constant only, you cannot assign a variable
- Only at the end of the list, can be given default values
- Default values parameters start with the "right most” parameter
- To provide a function definition starting from the left, put parameters "without default values" before those with default values
Positional Arguments
- Values provided with the correct amount of arguments in defintion
- Must provide a minimum amount of arguments from definition
Keyword Arguments
- Arguments pass by keyword, must know parameter names
- Use with third party libraries source code to see parameter names
Default vs Keyword Arg
- The default values are always provided in the function definition, not in the function call.
- The 'keyword-argument' pairs are always provided in the function call and not in the function definition.
- The 'keywords' used in the keyword-argument' pairs must be same as defined in the function definition.
Variable number of arguments def f(*arg)
- Defined by
f(*arg)
with arg a variable list - Call functions like any other, but can change the amount of parameters
Kwarg in function definition to pass key worded variable length def (**kwarg)
**kwarg
format use in function definition, not calls- Pass a variable length of arguments during function call
- Pass arguments as “pair" of "variable name” and its "value"
**kwarg
passes 2 values, for key and its value- The key-value pair is being passed to the function as a "dictionary"
- Note that since ‘kwarg' is a dictionary, there is no "order" for the items
Arg & Kwarg Comparison
- Arg acts like a tuple
- Kwarg acts like a dictionary
Additional Note - Python's module search
- The Python interpreter searches for the module in the current directory, then searches in sys path attribute, then checks env variable PYTHONPATH. Returns error if can't find module in defined methods.
Using if name == "main"
- It can be used to test if the script is being run directly or being imported by something else.
- Every file, ending can be executed directly or can be imported.
- Use
if name == "main"
any time to write modules which may either be run independently or imported.
Recursion
- Recursion is when suposing a function calls itself repeatedly and calling “breaks" the problem into simpler steps until it ends
- must “terminate” at some point of time or it will loop infinitely.
- Recursive Function will terminate only if two conditions:
- Problem being solved get's smaller
- A “base case where the call ends and it can not continue
- Recursive always call themselves
- "A base case” has to stop when its at the last step
recursiceFunction(attributes)
is called, tests case, is passes its used if not then call
Finding factorials Recursively
- Example being
- factorals n are
- n =! n*...(321) if greater than one and it calls the facotrila again
Recursion Verus Iteration
- Recursion are clearn, elegant when written correcttly
- Simple code writing
- Can break code down
- Sometimes, they may a difficult
- More recourses than in time
Memoizaiton
- Optimize way that stores functions that are "Cached and called quickly"
- Value are in the "Cache of stored items to return"
- May be usefull
Zip functions
- "Aggeragte more thatn one Iterabl or sqeueqence
- the individuals items are combine
- Returns itterable
- Iterable can consist of list, tuple etc
"Unziip with zip function"
- Uses code where
- If given like iterable it zips, when its has a "Itterable with Start function unzipped list
- Zip to " Un zip list to unzip" can show
Land Function
- Python w/o Name " Anomious Function"
- Normal Function is Called
When landa function " Use
- used with Short calculations called once
- higher order function with function A than fun B
- combine other functios like filter
Mapping
- Function with function
- Iteratotr and and used list
- Mapping functon
filter()
- remove item
- and boolesans " trues and false"
Generator
- Saves values and its able value thru " Itterators or stepping "
- "Yiele Statement returns interpoeter "
- Function turns value " Return function "
- Sees when return
Advangages
- Quickes less memoeryy to used
- can used " state" beetween call too
Studying That Suits You
Use AI to generate personalized quizzes and flashcards to suit your learning preferences.