Untitled Quiz
27 Questions
0 Views

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to lesson

Podcast

Play an AI-generated podcast conversation about this lesson

Questions and Answers

What is the name of the approach used to break a large program into functions?

Divide and conquer approach

Which of the following are benefits of using functions?

  • Easier facilitation of teamwork (correct)
  • Code reuse (correct)
  • Simpler code (correct)
  • Better testing and debugging (correct)
  • Faster development (correct)
  • A void function returns a value after executing its statements.

    False

    What is the purpose of the pass keyword in Python?

    <p>To create empty functions</p> Signup and view all the answers

    What is the difference between an argument and a parameter in Python?

    <p>An argument is a value passed to a function when it is called. A parameter is a variable that receives the argument inside the function.</p> Signup and view all the answers

    A local variable declared inside a function can be accessed by statements in other functions.

    <p>False</p> Signup and view all the answers

    Global variables declared outside all functions can be accessed from any statement within the program file.

    <p>True</p> Signup and view all the answers

    What is the general format for declaring a global variable in Python?

    <p>global variable_name</p> Signup and view all the answers

    A global constant is a global name that references a value, and it can be changed during program execution.

    <p>False</p> Signup and view all the answers

    What is the purpose of the random module in Python?

    <p>To work with random numbers.</p> Signup and view all the answers

    The randint function returns a randomly selected integer from the sequence generated by the range function.

    <p>True</p> Signup and view all the answers

    What is the output of the expression random.randint(1, 10)?

    <p>A random integer between 1 and 10.</p> Signup and view all the answers

    What is the purpose of the seed value in the context of random numbers?

    <p>To initialize the formula that generates random numbers.</p> Signup and view all the answers

    The randrange function returns a randomly selected integer from the sequence generated by the range function, but excludes the end value.

    <p>True</p> Signup and view all the answers

    What is the range of values returned by the random function?

    <p>Between 0.0 and 1.0</p> Signup and view all the answers

    What is the output of the expression random.uniform(1.0, 10.0)?

    <p>A random floating-point number within the range of 1.0 and 10.0 (inclusive).</p> Signup and view all the answers

    The math module offers functions essential for performing mathematical computations.

    <p>True</p> Signup and view all the answers

    What is the purpose of modularization in large, complex programming projects?

    <p>To keep code organized and maintainable.</p> Signup and view all the answers

    What is a menu-driven program?

    <p>A program that presents a list of operations to the user, allowing them to choose the desired action.</p> Signup and view all the answers

    The variable __name__ is automatically created when a Python source code file is loaded into the interpreter.

    <p>True</p> Signup and view all the answers

    How do you ensure that the main function of a module only executes when the file is run directly and not when it is imported?

    <p>Use the <code>if __name__ == '__main__':</code> block to conditionally execute <code>main</code>.</p> Signup and view all the answers

    You can use the turtle module for working with turtle graphical operations.

    <p>True</p> Signup and view all the answers

    The square function takes ______ arguments to draw a square.

    <p>four</p> Signup and view all the answers

    The circle function requires arguments specifying the starting and ending locations of the circle.

    <p>False</p> Signup and view all the answers

    The line function draws a line between the two points defined by its arguments.

    <p>True</p> Signup and view all the answers

    What are the key advantages of modularizing turtle graphics code using functions?

    <p>It allows you to reuse the code for drawing different shapes and patterns, as well as simplify the overall logic of your turtle graphics program.</p> Signup and view all the answers

    Functions stored in modules can only be called by the same program that it was defined in.

    <p>False</p> Signup and view all the answers

    Study Notes

    Introduction to Functions

    • Function: a group of statements within a program that performs a specific task
    • Functions in a large program allow breaking down complex tasks into smaller, more manageable sub-tasks
    • This is known as the divide and conquer approach
    • A modularized program breaks down each task into its own function

    Topics

    • Introduction to Functions
    • Defining and Calling a Void Function
    • Designing a Program to Use Functions
    • Local Variables
    • Passing Arguments to Functions
    • Global Variables and Global Constants
    • Turtle Graphics: Modularizing Code with Functions
    • Introduction to Value-Returning Functions: Generating Random Numbers
    • Writing Your Own Value-Returning Functions
    • The math Module
    • Storing Functions in Modules

    Benefits of Modularizing a Program with Functions

    • Simpler code
    • Code reuse (write the code once and call it multiple times)
    • Better testing and debugging (can test and debug each function individually)
    • Faster development
    • Easier facilitation of teamwork (different team members can write different functions)

    Void Functions and Value-Returning Functions

    • Void function: simply executes the statements it contains and then terminates
    • Value-returning function: executes statements, returns a value to the statement that called it
    • Examples of value-returning functions include input, int, float

    Defining and Calling a Void Function

    • Functions are given names
    • Function naming rules: cannot use keywords as a function name, cannot contain spaces, first character must be a letter or underscore, all other characters must be a letter, number, or underscore, uppercase and lowercase characters are distinct
    • Function name should be descriptive of the task carried out by the function
    • Function definition: specifies what the function does (e.g., def function_name():)

    Defining and Calling a Void Function (Continued)

    • Function header: first line of the function (e.g., def function_name(): )
    • Block: set of statements that belong together in a function
    • Calling the function: causes the interpreter to jump to the function and execute its statements; the interpreter then returns to the part of the program that called the function
    • Function return: the interpreter jumps back to the program's location

    Example of Defining and Calling a Function

    • A function, called "message," is created in memory, containing the statements in the definition.
    • Calling the function causes the program to execute these statements.

    Defining and Calling a Void Function (Continued)

    • Main function: the function called when the program starts; it calls other functions as needed to accomplish its tasks. It also contains the mainline logic of the program.

    Indentation in Python

    • Each block within a function must be indented the same number of spaces
    • Use tabs or spaces to indent lines in a block, but not both in a single block
    • IDLE and PyCharm indent lines in blocks automatically
    • Blank lines within a block of code are ignored

    Designing a Program to Use Functions

    • Flowcharts show function calls, with vertical bars on either side of the rectangle that contains the function name
    • Hierarchy charts (also called structure charts) show the relationships between functions in the form of boxes (where each function is a box), and lines that connect the boxes to illustrate how functions in the program call each other

    Designing a Program to Use Functions (Continued)

    • Flowcharts show the flow of logic; hierarchy charts show the relationship between functions
    • IPO charts describe the input, processing, and output for each function

    Local Variables

    • Local variable: a variable being assigned a value within a function; it belongs only to that function
    • Only code within the function can access the variable
    • Trying to access the variable outside the function results in an error

    Local Variables (Continued)

    • Scope: the part of a program in which a variable can be accessed
    • Local variables cannot be accessed prior to their definition
    • Different functions can have local variables with the same name

    Passing Arguments to Functions

    • Argument: data passed into a function when it is called
    • Parameter: variable that receives an argument passed into a function
    • Arguments are placed in parentheses following the function's name
    • Functions can use arguments in calculations

    Passing Arguments to Functions (Continued)

    • Parameter variable: variable that is assigned the value of an argument when the function is called
    • Parameter and argument reference the same value

    Passing Multiple Arguments

    • Python allows writing a function to accept multiple arguments
    • Parameter list replaces a single parameter
    • Parameters in the list are separated by commas
    • Arguments are passed by position to the corresponding parameters (first argument to first parameter, second to second, etc.)

    Making Changes to Parameters

    • Changes made to a parameter value within a function do not affect the argument
    • This is known as pass-by-value
    • Provides one-way communication between functions

    Keyword Arguments

    • Keyword argument: argument that specifies which parameter the value should be passed to
    • Position of the argument in the function call is irrelevant when using keyword arguments
    • Positional arguments must appear first in a function call that mixes positional and keyword arguments

    Global Variables

    • Global variable: a variable created by an assignment statement written outside of all functions
    • The variable can be accessed from any statement in the program file (including inside functions)
    • If a function needs to assign a value to a global variable, the global variable must be explicitly redeclared within the function

    Global Variables (Continued)

    • Reasons to avoid global variables: can make debugging difficult, functions that use global variables are usually dependent on those variables, makes functions harder to transfer to other programs, makes programs hard to understand

    Global Constants

    • Global constant: global name that references a value that cannot be changed
    • Permissible to use global constants
    • Simulate global constants in Python by creating a global variable and not re-declaring it within functions

    Introduction to Value-Returning Functions: Generating Random Numbers

    • Void function: a group of statements performing a specific task
    • Call the void function when needed
    • Value-returning function: similar to a void function, but it returns a value
    • Value is returned to the part of the program that called the function
    • If the function finishes executing with a return value, it's returned to the statement that called it

    Standard Library Functions and the import Statement

    • Standard library: pre-written functions that come with Python
    • Library functions perform tasks programmers commonly need
    • Viewed as a "black box"
    • Some library functions built directly into Python interpreter
    • To use, just call the function (e.g. print())

    Standard Library Functions and the import Statement (Continued)

    • Modules: files storing standard library functions; they organize functions not built into the interpreter
    • Modules are copied to the computer when Python is installed

    Generating Random Numbers

    • Random numbers are useful in many programming tasks
    • The random module includes functions to work with random numbers
    • Dot notation is used to call functions belonging to a module (e.g. module_name.function_name())

    Generating Random Numbers (Continued)

    • randint function: generates a random integer in a specified range
    • Returns the random integer
    • Used anywhere in the program needing an integer

    Generating Random Numbers (Continued)

    • randrange: similar to range, but returns a randomly selected integer from a sequence
    • random: returns a random float between 0.0 and 1.0
    • uniform: returns a random float in a specified range

    Random Number Seeds

    • Random numbers are pseudo-random, generated by a formula
    • Seed value initializes the formula
    • Different series are generated by different seed values
    • System time is used by default for a seed value
    • Use random.seed() to specify a seed.

    Writing Your Own Value-Returning Functions

    • To create a value-returning function, write a standard function but add return statements
    • Return an expression (e.g, a sum of values or a result of another value-returning function)
    • Values are returned to the part of the program that called the function

    Example: How to Use the Return Value of a Function

    • Example of function sum that accepts two arguments, and returns their sum; the main function calls sum and stores the result in a variable

    How to Use Value-Returning Functions

    • Value-returning functions can be used in specific situations
    • Example: prompt users for input
    • Simplify complex mathematical expressions

    Using IPO Charts

    • IPO charts describe a function's input, processing, and output
    • Tool for designing and documenting functions
    • Lay outs functions in columns
    • Briefly describes input, processing, and output

    Returning Strings

    • Functions can return strings (e.g., a user's name)

    Returning Boolean Values

    • Boolean functions return either True or False
    • Used in decision and repetition structures
    • Used to simplify input validation

    Returning Multiple Values

    • Functions can return multiple values using a comma-separated list after the return statement
    • Calling a multi-returning function requires assigning each returned value to a separate variable

    The math Module

    • Part of the standard library
    • Contains functions useful for performing mathematical calculations
    • Typically accepts one or more values as arguments and returns the result
    • Requires import math statement at the top of the program

    The math Module (Continued)

    • Contains constants such as math.pi and math.e
    • These are used in math calculations (e.g., for circle area) using dot notation

    Storing Functions in Modules

    • Organize code in large and complex programs
    • Modularization: grouping related functions in modules
    • Easier to understand, test, maintain, and reuse
    • Import the module that contains the necessary functions
    • Menu-driven programs display a list of operations to a user
    • Users select an operation from a menu
    • The program uses a decision structure to determine the chosen option and executes the corresponding operations.
    • This usually repeats until the user decides to quit.

    Conditionally Executing the main Function

    • Modules can be run standalone or imported into other programs
    • The program has a main() function (this is different from the main code block)
    • The if name main block is conditionally executed to control actions that only occur when the program runs as a standalone script, but not when it is imported into another program.

    Turtle Graphics: Modularizing Code with Functions

    • Functions can store commonly used turtle graphics operations
    • Example: Draw a square with a specified location, width, and color.
    • Parameter values define location, width, and color
    • Example uses: Draw a square, draw a circle, draw a line

    Studying That Suits You

    Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

    Quiz Team

    Related Documents

    CSM2170 Chapter 5 Functions PDF

    More Like This

    Untitled Quiz
    6 questions

    Untitled Quiz

    AdoredHealing avatar
    AdoredHealing
    Untitled Quiz
    37 questions

    Untitled Quiz

    WellReceivedSquirrel7948 avatar
    WellReceivedSquirrel7948
    Untitled Quiz
    50 questions

    Untitled Quiz

    JoyousSulfur avatar
    JoyousSulfur
    Untitled Quiz
    48 questions

    Untitled Quiz

    StraightforwardStatueOfLiberty avatar
    StraightforwardStatueOfLiberty
    Use Quizgecko on...
    Browser
    Browser