100% found this document useful (1 vote)
1K views6 pages

Working with Functions in Python

The document discusses functions in Python. It defines a function as a small unit of a program that processes data and may return a value. Functions are useful for easy program handling, reducing size and repeated statements, reducing ambiguity, and improving readability. The key parts of a function are the function header, parameters, body, and indentation. Functions are created using the def keyword and called by writing the function name. Functions make code more organized and reusable.

Uploaded by

ADITIYA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
1K views6 pages

Working with Functions in Python

The document discusses functions in Python. It defines a function as a small unit of a program that processes data and may return a value. Functions are useful for easy program handling, reducing size and repeated statements, reducing ambiguity, and improving readability. The key parts of a function are the function header, parameters, body, and indentation. Functions are created using the def keyword and called by writing the function name. Functions make code more organized and reusable.

Uploaded by

ADITIYA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
  • Function Definition and Structure of Python Program
  • Theory-based Questions
  • Function Components and Usage

Function Definition

A function is a small unit of a program that processes the data and often returns a value.

The need for functions


● Easy program handling
● Reduce the size of the program
● Reduce the repeated statements
● Ambiguity can be reduced
● Make the program more readable and understandable
How to create a function in Python?
To create a function in Python consider the following parts of a function:

Parts of Function

Function Header
Always starts with the “def” keyword followed by the function name and its parameters,
ends with a colon (:)
Parameters
Variables Supplied in brackets of the function header
Function Body
Block of statements/instructions that define the action performed by the function, indentation
must be followed
Indentation
White space at the beginning of every statement with the same block
Function Calling
writing function name including ()

The following five basic steps are used to create and invoke a function.

After writing the function it must be invoked through calling by following these steps:

Save a program and click run or press the F5 button


Now interactive mode will appear with the message RESTART ……
Write a function call statement as shown in the below image
A function call statement is just like a function name with required parameters
Press enter and supply input as per requirements
Structure of Python Program
A Python program is a set of a few statements and blocks. A Python program may have the
following:
Physical line structure: A Python program is divided into no. of logical lines, the logical line
is created from one or more physical lines
Joining two lines: A logical line can be broken into two or more physical lines using a
backslash (\)
Multiple statements on a single line: Semicolon (;) is used to write multiple statements on
a single line
The top-level statement or _main_: Unindented statements
Comments: Begins with a hash symbol (#), python interpreter ignores them, multi-line
comments will be written in “”” (triple-double quotes).
Indentation: White spaces used at the beginning of every line. The indented part is known
as one block.

statement it just executes the function header line and skips all statements in the function
body these statements execute when a function will be called

Theory-based questions

1. What is a function?
Ans.:
A function is a set of instructions or subprograms that are used to fulfil the user’s need.
In other words, a function is a bunch of code which performs a specific task.
A function is used to do a specific task and divide the large program into smaller blocks.
A function is a small unit of a program that processes the data and often returns a value.
2. Why do programmers need functions in python programming?
Ans.:
To make the program easy
Divide the large program into a small block of codes
Reduce the lines of code
Easy to update

3. How to create a function in python? Explain in detail.


Ans.: To create a function in python follow the given steps:
Start the code with def followed by function name and supply input through the parameters.
Write the set of statements to be executed in the program.
Call the function to invoke or execute the statements.

4. What are the parts of functions? Explain with a suitable example.


Ans.: The arts of functions are as follows:
Function header: It starts with def followed by the function name and required parameters.
Parameters are the input variables written into brackets. These parameters are supplied in
the function calling statement.
Function Body: This is the main part of a program. It contains the main block of the
program. The set of instructions such as calculations, logical comparisons etc is written here
in this part. It ends with a return statement. Indentation is very important for the function
body.
Function calling statement: This is the final part of a function. It invokes the function and
returns the output as instructed into the function body.

5. How to call a function? Write steps.


Ans: Calling a function is an easy task. Here are the steps:
Write the function name.
Supply the values of the parameters, if any.
6. What are the comments? What are the role comments in the program? How to write
single-line comments and multi-line comments?
Ans: Comments are the additional explanatory text written in the function to provide some
description or explanation about the statement or block of code.

Comments play an important role in understanding a program. It provides a descriptive


explanation of the written statements. It makes the intention very clear for what the
statement is used or what process is going to be done.

The single-line comment is written by # followed by the text. The multiline comments start
with ”’ and are followed by the text then ends with ”’.

7. Explain the physical line structure of a program. Illustrate with an example.


execution in the function call statement.

Ans.: The physical line structure of a program contains the lines of codes. Physical lines are
the lines which you can see on the screen in a python program.

In other words, a physical line contains a set of characters that ends with an EOL character.
The EOL character is newline generally ‘\n’ in python.

Example:
>>> name=’Chapter 3 Working with functions’
>>> print(name)
Chapter 3 Working with functions

The above statement is same as:


>>> name=’Chapter 3 Working with functions’; print(name)
Ans.:
A function in the python program is called by a function call statement
To call a function, write the function name followed by parameter values in brackets
A block of statements executed in the execution frame
When a function is called, an execution frame is created and controls the transfer
Within the execution frame, the statements written in the function body are executed and
return a value or execute the last statement
Python follows top to bottom approach for executing program
Comments are ignored in execution
If python notices function definition with a def statement it just executes the function header
line and skips all statements in the function body these statements execute when a function
will be called
8. Illustrate the flow of execution in the function call statement.
Ans.:
● A function in the python program is called by a function call statement
● To call a function, write the function name followed by parameter values in brackets A
block of statements executed in the execution frame
● When a function is called, an execution frame is created and controls the transfer
● Within the execution frame, the statements written in the function body are executed
and return a value or execute the last statement
● Python follows top to bottom approach for executing program
● Comments are ignored in execution
● If python notices function definition with a def statement it just executes the function
header line and skips all statements in the function body these statements execute
when a function will be called

9. Write and explain the types of functions supported by python.


Ans.:
Built-in Functions: Pre-defined functions of python such as len(), type(), input() etc.
Functions defined in modules: Functions defined in particular modules, can be used when
the module is imported. A module is a container of functions, variables, constants, and
classes in a separate file which can be reused.
User-Defined Functions: Function created by the programmer

10. Write the ways of import module in the python program.


Ans.:
The module can be imported in two ways
import statement: Used to import the entire module. EX. import math
from statement : import all functions or the selected one. EX. from random import randint
11. Differentiate between parameters and arguments.

Parameters Arguments

These are specified Values passed during


during the function the function call.
definition.

They are also known as They are also known


formal parameters. as actual parameters.
These variables help in These variables are
the complete execution passed to the function
of the function. for execution.

The values contained by The arguments are


these parameters can accessible throughout
only be accessed from the program
function return depending upon the
statements or if the scope of the variable
scope of these assigned.
parameters is made
global.

The values passed as Every argument is


parameters are local assigned to a
variables and are parameter when the
assigned values of the function is defined.
arguments during the
function call.
12. What are the arguments supported by python? Explain each of them with a suitable
example.
Ans.:Python supports four argument types:

Positional Arguments: Arguments passed to a function in correct positional order, no. of


arguments must match with no. of parameters required.
Default Arguments: Assign a default value to a certain parameter, it is used when the user
knows the value of the parameter, default values are specified in the function header. It is
optional in the function call statement. If not provided in the function call statement then the
default value is considered. Default arguments must be provided from right to left.
Key Word Arguments: Keyword arguments are the named arguments with assigned values
being passed in the function call statement, the user can combine any type of argument.
Variable Length Arguments: It allows the user to pass as many arguments as required in the
program. Variable-length arguments are defined with the * symbol.

13. What is the local variable and global variable? Explain with an example.
Ans.:

Global Variable: A variable that is declared in top-level statements is called a global variable.
To access the value of a global variable user need to write a global keyword in front of the
variable in a function.

Local Variable: A name declared in a specific function body is called a local variable.

In the next section of Working with functions Class 12 questions, I will cover some output
and error-based questions. Here we go!
14. What are the rules for combining three types of arguments in a Python function?
Ans.: The following rules need to be followed for combining three types of arguments in a
python function.
1. An argument list must contain positional arguments followed by any keyword argument.

2. Keyword arguments should be taken from the required arguments preferably.

3. Value of the argument can’t be specified more than once.

Ex.:

cal_discount(amt=500,rate=10) or cal_discount(rate=10,amt=500)

Common questions

Powered by AI

Built-in functions are pre-defined functions provided by Python, such as `len()`, `type()`, and `input()`, used frequently for common operations without needing additional import statements. They offer efficient and standardized operations for common tasks like measuring the length of a list, determining a type, or receiving user input. User-defined functions are created by programmers to perform bespoke operations specific to the program's context, encapsulating unique logic and tasks which built-in functions do not cover. They enhance code modularity and readability when standard operations fall short .

Functions play a pivotal role in Python programming by promoting modularity and code reuse. They allow programs to be divided into smaller, manageable blocks, making them easier to handle. Functions reduce code size by avoiding repetition of code blocks, thus simplifying program updates. They also mitigate ambiguity and improve readability and understanding for developers. By organizing tasks into discrete, callable units, functions enhance maintainability and efficiency of code development .

Modules in Python can be imported using the `import` statement, which imports the entire module, or the `from` statement, which imports specific functions or components from a module. Using `import module` loads all components, maintaining the module’s original namespace, requiring calls like `module.function()`. The `from module import component` method imports specific parts directly, allowing direct function calls without module prefix, which can lead to name conflicts if common function names are used, impacting namespace cleanliness and clarity in larger programs .

When a function is called in Python, an execution frame is created. This frame manages the control transfer and execution of the statements within the function body. The function call statement includes the function name followed by the values of the parameters, if any. Python follows a top-to-bottom execution approach, and when a function is defined using the 'def' keyword, only the function header is executed initially. The body of the function is executed upon calling the function, maintaining a clear execution order .

The key components of a function in Python are the function header, parameters, and function body. The function header starts with the 'def' keyword followed by the function name and its parameters in parentheses, which define the inputs the function will process. The function body consists of indented statements that dictate what actions the function performs when executed, ending typically with a return statement. These components allow functions to encapsulate logic and data processing, which simplifies program structure by breaking down complex operations into manageable pieces, improves code reusability, and enhances readability .

Indentation in Python is significant because it defines the structure and block of statements within a program. Unlike other languages that use braces to define scopes, Python uses whitespace indentation. In the context of function definition, indentation is crucial as it distinguishes the function body from the rest of the program. The consistent use of indentation ensures the clarity and proper execution of the code block associated with a function. Incorrect indentation can lead to syntax errors and affect the program's flow, making it a unique and integral part of Python's syntax .

Comments in Python enhance program clarity by providing additional explanations or descriptions about particular code statements or blocks, which helps in understanding the program’s logic and purpose. Single-line comments are introduced with a '#' symbol and are limited to one line, whereas multi-line comments are enclosed within triple quotes, allowing for annotations over several lines. Both types of comments are ignored during code execution by the interpreter, serving solely as documentation within the code .

Global variables are declared outside any function and are accessible throughout the program, whereas local variables are declared within a function and can only be accessed within that function's scope. During function execution, local variables can cause name conflicts if they overshadow global variables with the same name. Accessing or modifying a global variable within a function requires the use of the 'global' keyword to indicate it is not a local variable, ensuring proper data handling and avoiding unwanted side effects in the program's global state .

Python supports positional arguments, default arguments, keyword arguments, and variable-length arguments. Positional arguments must be passed in order during function calls, matching the function's parameters. Default arguments have predefined values in the function definition, used if no corresponding argument is provided in the call. Keyword arguments allow arguments to be passed in any order by specifying their names, enhancing clarity. Variable-length arguments enable functions to accept an arbitrary number of arguments using the * symbol, offering flexibility in function calls .

When combining different types of arguments in a Python function, the following rules must be observed: positional arguments must precede any keyword arguments; keyword arguments should be derived from required arguments; a value cannot be assigned to the same argument more than once. For example, a function can be defined such as `def my_function(amt, rate=0.05, *, discount)`, demonstrating the appropriate sequence. An invocation like `my_function(100, discount=10)` adheres to these rules, illustrating a correct combination of argument types .

Function Definition
A function is a small unit of a program that processes the data and often returns a value.
The need for f
Physical line structure: A Python program is divided into no. of logical lines, the logical line
is created from one or more
Function header: It starts with def followed by the function name and required parameters.
Parameters are the input variables
Within the execution frame, the statements written in the function body are executed and
return a value or execute the last s
These variables help in
the complete execution
of the function.
These variables are
passed to the function
for execution.
The
14. What are the rules for combining three types of arguments in a Python function?
Ans.: The following rules need to be foll

You might also like