Python Functions and Built-in Functions

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson
Download our mobile app to listen on the go
Get App

Questions and Answers

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?

  • 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?

  • 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?

<p><code>False</code> (C)</p> Signup and view all the answers

Which of the following values will evaluate to False when passed to the bool() function?

<p><code>()</code> (A)</p> Signup and view all the answers

What is the purpose of the chr(x) function in Python?

<p>To convert an integer to its corresponding Unicode character. (D)</p> Signup and view all the answers

What happens if the integer argument provided to chr(x) is outside the valid range?

<p>The function raises a <code>ValueError</code>. (A)</p> Signup and view all the answers

In Python 3.x, what is the recommended alternative to the deprecated cmp(x, y) function?

<p>Using the expression <code>(x &gt; y) - (x &lt; y)</code>. (D)</p> Signup and view all the answers

What does the divmod(x, y) function return in Python?

<p>A tuple containing the quotient and remainder of <code>x</code> divided by <code>y</code>. (B)</p> Signup and view all the answers

What will happen if y is equal to 0 when calling the divmod(x, y) function?

<p>The function will raise a <code>ZeroDivisionError</code>. (B)</p> Signup and view all the answers

Which data types can the float() function accept as parameters?

<p>Integers, long integers, and strings. (C)</p> Signup and view all the answers

What is the purpose of the id(object) function in Python?

<p>To return a unique integer identifier for the object. (C)</p> Signup and view all the answers

What is the return type of the int(x) function?

<p>An integer. (B)</p> Signup and view all the answers

What happens if the argument passed to int(x) cannot be converted to an integer?

<p>The function raises a <code>ValueError</code>. (C)</p> Signup and view all the answers

What types of arguments can be passed to the len(x) function?

<p>Sequences (strings, ranges, lists, tuples) or collections (sets, dictionaries). (B)</p> Signup and view all the answers

Which of the following represents a valid way to call the range() function?

<p><code>range(start, stop, step)</code> (B)</p> Signup and view all the answers

What does the round(number, ndigits) function do if the ndigits argument is omitted?

<p>Rounds the number to the nearest integer. (B)</p> Signup and view all the answers

What is the primary purpose of the str(object) function?

<p>To create a string representation of an object. (C)</p> Signup and view all the answers

What happens if an object does not provide its own string version when passed to str(object)?

<p>The function returns an empty string. (C)</p> Signup and view all the answers

What is the primary purpose of the tuple(iterable) function?

<p>To convert an iterable into a tuple. (C)</p> Signup and view all the answers

What does the function math.floor(x) do?

<p>Returns the largest integer not greater than <code>x</code>. (B)</p> Signup and view all the answers

Which of the following best describes what the random module's algorithm is based on?

<p>Deterministic functions and an initial 'seed'. (C)</p> Signup and view all the answers

What will always be true when using random.random()?

<p>The return value will be in the range of <code>0.0 &lt;= x &lt; 1.0</code>. (C)</p> Signup and view all the answers

What is important about the object provided to random.seed() if you choose to provide an object?

<p>It must be a 'hashable' object. (D)</p> Signup and view all the answers

How does random.randint(x, y) differ from other similar random number functions in Python?

<p>It includes the upper limit 'y' in the possible return values, while others typically exclude it. (D)</p> Signup and view all the answers

What restriction applies when calling random.uniform(x, y)?

<p><code>x</code> and <code>y</code> must be numbers. (D)</p> Signup and view all the answers

What statement is true about random.randrange([start], stop, [step])?

<p>Only <code>stop</code> is mandatory. (D)</p> Signup and view all the answers

What is the purpose of the def keyword in Python when writing functions?

<p>It marks the start of the function header. (A)</p> Signup and view all the answers

What should all statements inside a function body have?

<p>The same indentation level. (D)</p> Signup and view all the answers

What happens if a return statement is without any expression?

<p>Returns the special value None. (D)</p> Signup and view all the answers

What is the flow of execution when a function is called in Python?

<p>The execution jumps to the function definition, executes the statements within it, and returns to the point where the function was called. (A)</p> Signup and view all the answers

What happens to local variables when function call ceases?

<p>They cease to exist. (A)</p> Signup and view all the answers

What will happen if a local scope and global scope have a variable with the same name?

<p>The local name will prevail over the global scope. (A)</p> Signup and view all the answers

In the context of function calls, what is meant by 'call by value'?

<p>A copy of the variable's value is passed to the function. (C)</p> Signup and view all the answers

What is the difference between a parameter and an argument?

<p>A parameter is a variable in the function declaration, whereas an argument is the actual value passed to the function. (B)</p> Signup and view all the answers

If the function caller provides a value for that particular parameter, then what happens?

<p>The default value present in the function definition is ignored and instead the value provided by the function caller is used. (C)</p> Signup and view all the answers

Why use 3rd party libraries and modules?

<p>To see the names of the parameters. (C)</p> Signup and view all the answers

How can the Python interpreter determine whether to run or not a module to run due to it being run directly versus imported?

<p>If name == 'main' (C)</p> Signup and view all the answers

Flashcards

What is a function?

A named sequence of statements.

What do functions do?

They take parameters and/or return a result, value, or object.

What does abs(x) do?

Returns the absolute value of a number (positive magnitude).

What does bool([x]) do?

Converts a value to its Boolean equivalent (True or False). Returns False if no argument.

Signup and view all the flashcards

Values considered False in Python

Zero, None, False, or empty sequences/mappings.

Signup and view all the flashcards

What does chr(x) do?

Treats an integer as a Unicode point, Returns corresponding character.

Signup and view all the flashcards

What does divmod(x, y) do?

Takes two numbers and returns a tuple of (quotient, remainder).

Signup and view all the flashcards

What does float(x) do?

Converts a variable to a floating-point number.

Signup and view all the flashcards

What does id(object) do?

Returns the unique 'identity' of an object (an integer).

Signup and view all the flashcards

What does int(x) do?

Converts a variable to an integer. if no argument is given, it returns 0.

Signup and view all the flashcards

What does len(x) do?

Returns the length of an object (string, list, tuple, etc.).

Signup and view all the flashcards

What does range(start, stop[, step]) do?

Generates a sequence of numbers; often used in loops.

Signup and view all the flashcards

What does round(number[, ndigits]) do?

Rounds a number to a specified number of digits (defaults to 0).

Signup and view all the flashcards

What does str(object='') do?

Returns the ‘string’ version of object.

Signup and view all the flashcards

What does tuple([iterable]) do?

Converts an iterable (list, string, etc.) into a tuple.

Signup and view all the flashcards

math.ceil(x) in Python

Returns the smallest integer not less than x.

Signup and view all the flashcards

math.fabs(x) in Python

Returns the absolute value of x.

Signup and view all the flashcards

math.floor(x) in Python

Returns the largest integer not greater than x; the ‘floor’ of x.

Signup and view all the flashcards

math.pow(x, y) in Python

x and y must be numbers. Returns x to the power of y.

Signup and view all the flashcards

random.random() in Python

This is the basic method for generating a random number.

Signup and view all the flashcards

random.choice(sequence) in Python

Selects a random item from any sequence.

Signup and view all the flashcards

random.uniform(x, y) in Python

Returns a random floating point number

Signup and view all the flashcards

random.randint(x, y) in Python

random integer

Signup and view all the flashcards

random.randrange([start], stop, [step])

Takes three parameters out of which two, namely “start” and “stop” are optional and only one, that is, “stop” is mandatory.

Signup and view all the flashcards

Keyword def

This is the start of the function header. Does not call the function

Signup and view all the flashcards

return statement

Returns a value to the method call.

Signup and view all the flashcards

describe parameters

They are the name within the function or function declaration

Signup and view all the flashcards

Arguments

Value passed to the function

Signup and view all the flashcards

Rules for default values

Parameter should be a constant only, cannot assign a variable.

Signup and view all the flashcards

default value

An argument which may be provided a default value

Signup and view all the flashcards

function call

Where you use or call the function

Signup and view all the flashcards

function definition

Where the scrip defines the function

Signup and view all the flashcards

keywords

Each argument is given a 'label or a name'

Signup and view all the flashcards

default values

default values are always provided in the function definition, not in the function call

Signup and view all the flashcards

function definition

function call expect

Signup and view all the flashcards

function definition

where f is the name of the function that are being defined.

Signup and view all the flashcards

format **kwarg

is used in the function definition and not in the function call

Signup and view all the flashcards

file

can be executed directly or can be imported

Signup and view all the flashcards

recursive function

algorithm must call itself recursively; There is another additional requirement

Signup and view all the flashcards

Generator functions

functions use less memory and consume less time

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 False
  • False 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 character
  • chr(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 than x."
  • math.fabs(x) gives the absolute value of x.
  • math.floor(x) returns the "largest integer not greater than x. 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 and step 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
  • 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.

Quiz Team

Related Documents

More Like This

Python Functions: A Comprehensive Guide
10 questions
Python Installation and Keywords Quiz
18 questions
Python 内置函数
64 questions

Python 内置函数

HandsomeCentaur7126 avatar
HandsomeCentaur7126
Use Quizgecko on...
Browser
Browser