KEMBAR78
Python-Mastering python : Tips and techniques | PPTX
Name of the Faculty Dr.G.Paramasivam
Department Computer Science
Designation Associate Professor
Name of the Course Python Programming
Semester V
Subject Code 5EA
Batch 2023
Unit & Course Topic Unit -III: Functions
Syllabus: Unit - III
FUNCTIONS: Definition - Passing parameters
to a Function - Built-in functions- Variable
Number of Arguments - Scope – Type
conversion-Type coercion-Passing Functions to a
Function - Mapping Functions in a Dictionary –
Lambda - Modules - Standard Modules – sys –
math – time - dir - help Function.
Functions
Definition
Passing parameters to a Function
 Built-in functions
 Variable Number of Arguments
 Scope
Introduction
•A function is a block of code to perform a specific
task.
•This provides better modularity and high degree of
reusability.
•As our program grows larger and larger, functions
make it more organizable and manageable.
•Functions in python are defined using the block
keyword “ def ", followed with the function's name as
the block's name.
Function Definition
• Keyword def - marks the start of the function header.
• A function name is used to identify the function.
• Parameters (arguments) can be used to pass values to a function which
are optional.
• colon (:) - to mark the end of the function header.
• Any number of python statements that make up the function body.
Statements should have the same indentation level.
• An optional return statement to return a value from the function.
Example1:
def add( arg1, arg2 ):
total = arg1 + arg2
print "Inside the function : ", total
return total;
EXAMPLE 2:
def fun():
print("")
fun()
Passing parameters to a Function
• The function definition consists of the name, the
parameters needed, the steps that will be carried out by
the function and returning values if any.
• A function in Python is called by using its name
followed by parentheses. In case parameters are present,
these are included in the parentheses.
SYNTAX
Passing Parameters to a Function
Built-in functions
1) Python abs() - returns absolute value of a number
2) Python all() - returns true when all elements in iterable is true
3) Python any() - Checks if any Element of an Iterable is True
4) Python ascii() - Returns String Containing Printable Representation
5) Python bin() - converts integer to binary string
6) Python bool() - Converts a Value to Boolean
BUILT IN FUNCTIONS
7) Python bytearray() - returns array of given byte size.
8) Python bytes() - returns immutable bytes object
9) Python callable() - Checks if the Object is Callable
10) Python chr() - Returns a Character (a string) from an Integer
11) Python classmethod() - returns class method for given function
12) Python compile() - Returns a Python code object
BUILT IN FUNCTIONS
13) Python complex() - Creates a Complex Number
14) Python delattr() - Deletes Attribute From the Object
15) Python dict() - Creates a Dictionary
16) Python dir() - Tries to Return Attributes of Object
17) Python divmod() - Returns a Tuple of Quotient and Remainder
18) Python enumerate() - Returns an Enumerate Object
Link to learn python Functions
• https://www.programiz.com/python-programming/method
s/built-in
• https://data-flair.training/blogs/python-built-in-functions/
Variable number of arguments
An argument is a variable, value, or object passed
to a function or method as input.
In Python, there are two ways to define a function
that can take a variable number of arguments.
Different forms of this type are:
• Positional arguments
• Keyword arguments
Variable number of arguments
Positional arguments are arguments that need to be included in
the proper position or order.
The first positional argument always needs to be listed first
when the function is called.
The second positional argument needs to be listed second, the
third positional argument listed third, etc.
General syntax for positional argument is:
function(*iterable)
EXAMPLE 1
def positional_args(*argv):
for arg in argv:
print (arg)
positional_args ('Hello', ‘All’, ‘Goodmorning’)
The arguments passed by the calling function are received
by *argv. The passed arguments will be unpacked one by
one within the function.
EXAMPLE 2
def positional_args (arg1, *argv):
print ("First argument :", arg1)
for arg in argv:
print("Next argument through *argv :", arg)
positional_args ('Hello', ‘All', ‘Good', ‘Morning’)
Keyword arguments
A keyword argument is an argument passed to a function or
method that is preceded by a keyword and an equal sign.
 The general form is:
function(keyword = value)
Where function is the function name, the keyword is the keyword
argument, and value is the value or object passed as that keyword.
Example
def key_args(**kwargs):
for key, value in kwargs.items():
print ("%s = %s" %(key, value))
key_args (first =‘Hello’, mid =‘all',
last='Goodmorning')
Example2
def var_arg(*args,**kwargs):
print("args: ", args)
print("kwargs: ", kwargs)
var_arg
('Good','for','All',first="Good",mid="for",last=
"all")
Python Variable Scope
The scope of a variable in python is that part of the code where it is
visible.
Local Scope in Python
• The local scope or function scope is a Python scope
created at function calls. Every time you call a function,
you’re also creating a new local scope.
• By default, parameters and names that you assign inside a
function exist only within the function or local scope
associated with the function call. When the function
returns, the local scope is destroyed and the names are
forgotten.
Example for local Scope
• def myfunc():
x = 300
print(x)
myfunc()
Global Scope
• A variable created in the main body of the Python
code is a global variable and belongs to the global
scope.
• Global variables are available from within any
scope, global and local.
Example for Global Scope
• x = 300
def myfunc():
print(x)
myfunc()
print(x)
Global Keyword
• If you need to create a global variable, but are stuck in the local
scope, you can use the global keyword.
• The global keyword makes the variable global.
• Example
def myfunc():
global x
x = 300
myfunc()
print(x)
Built-in Scope
• The built-in scope has all the names that are
loaded into python variable scope when we start
the interpreter.
• For example, we never need to import any module
to access functions like print() and id().
• If a Variable is not defined in local, Enclosed or
global scope, then python looks for it in the built-
in scope.
• # Built-in Scope
from math import pi
def inner():
# pi = 'not defined in
inner pi'
print(pi)
inner()
Enclosing Scope
• Enclosing (or nonlocal) scope is a special scope that only
exists for nested functions. If the local scope is an inner or
nested function, then the enclosing scope is the scope of the
outer or enclosing function. This scope contains the names that
you define in the enclosing function. The names in the
enclosing scope are visible from the code of the inner and
enclosing functions.
EXAMPLE
def red():
a=1
def blue():
print(“INNER BLOCK”)
a=2
b=2
print(a)
print(b)
blue()
print(“OUTER BLOCK”,a)
red()
Type Conversion
• The process of converting the value of one data type (integer, string,
float, etc.) to another data type is called type conversion. Python has
two types of type conversion.
• Implicit Type Conversion
• Explicit Type Conversion
Implicit Type Conversion
In Implicit type conversion, Python automatically converts one data type to
another data type. This process doesn't need any user involvement.
num1= 123
num2 = 1.23
num_new = num1+ num2
print("datatype of num_int:",type(num1))
print("datatype of num_flo:",type(num2))
print("Value of num_new:",num_new)
print("datatype of num_new:",type(num_new))
Explicit Type Conversion
• In Explicit Type Conversion, users convert the data type of an object
to required data type. We use the predefined functions like int(),
float(), str(), etc to perform explicit type conversion.
• This type of conversion is also called typecasting because the user
casts (changes) the data type of the objects.
Syntax :
<required_datatype>(expression)
Properties of Type Conversion
• Type Conversion is the conversion of object from one data type to
another data type.
• Implicit Type Conversion is automatically performed by the Python
interpreter.
• Python avoids the loss of data in Implicit Type Conversion.
• Explicit Type Conversion is also called Type Casting, the data types of
objects are converted using predefined functions by the user.
• In Type Casting, loss of data may occur as we enforce the object to a
specific data type.
Type Coercion
• Python don't have type coercion. Python doesn't ever
implicitly converts one object to another type of object.
For Example:
>>> name = "Trey"
>>> x
2
>>> name + x
Output:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
The reason is that strings in Python don't know how to use the plus operator with numbers and
numbers in Python don't know how to use the plus operator with strings, which means the code
doesn't work.
Passing Functions to a Function
• To pass a function as an argument to another function, write the name
of the function without parenthesis in the function call statement (just
like what we do with variables) and accept the reference of the
function as a parameter in the called function.
Example:
def fun2():
print('This is fun2')
def fun1(x):
print('This is fun1')
x()
#passing fun2 to fun1
fun1(fun2)
'''
This is fun1
This is fun2
'''
To use one function variable in another function parameter in
python
def fun1():
fun1.var = 100
print(fun1.var)
def fun2():
print(fun1.var)
fun1()
fun2()
print(fun1.var)
Mapping functions in a dictionary
• Python map() function applies another function on a given iterable
(List/String/Dictionary, etc.) and returns map object. In simple words,
it traverses the list, calls the function for each element, and returns the
results.
• Python map object is also iterable holding the list of each iteration. We
can also convert it to List or Dictionary or other types using their
constructor functions.
Map Function
• Python provides a function map() to transform the contents of given iterable sequence
based on logic provided by us i.e.
• Syntax:
map(sequence, callback)
• It accepts following arguments:
• sequence : An iterable sequence
• callback : A function that accepts an element as an argument and returns a new
element based on the argument.
• Returns :
Returns a new sequence whose size is equal to passed sequence.
Working of Map function
• It iterates over all the elements in given sequence. While iterating the
sequence it calls the given callback() function on each element and
then stores the returned value in a new sequence. In the end return this
new sequence of transformed elements.
Use map() function with lambda function
• In the map() function along with iterable sequence we can also the lambda function.
• Let’s use lambda function to reverse each string in the list like we did above using global function,
listOfStr = ['hi', 'this' , 'is', 'a', 'very', 'simple', 'string' , 'for', 'us']
• # Reverse each string in the list using lambda function & map()
modifiedList = list(map(lambda x : x[::-1], listOfStr))
print('Modified List : ', modifiedList)
• Output:
Modified List : ['ih', 'siht', 'si', 'a', 'yrev', 'elpmis', 'gnirts', 'rof', 'su']
• It iterates over the list of string and apply lambda function on each string element.
• Then stores the value returned by lambda function to a new sequence for each element.
• Then in last returns the new sequence of reversed string elements.
Using map() function to transform Dictionaries in Python
• Suppose we have a dictionary i.e.
dictOfNames = {
7 : 'sam',
8: 'john',
9: 'mathew',
10: 'riti',
11 : 'aadi',
12 : 'sachin'
}
• Now we want to transform the values in dictionary by appending ‘_’ at the end of each value i.e.
# add an '_' to the value field in each key value pair of dictionary
dictOfNames = dict(map(lambda x: (x[0], x[1] + '_'), dictOfNames.items() ))
print('Modified Dictionary : ')
print(dictOfNames)
• Output:
• Modified Dictionary :
{7: 'sam_', 8: 'john_', 9: 'mathew_', 10: 'riti_', 11: 'aadi_', 12: 'sachin_'}
• map() function iterated over all the items in dictionary and then
applied passed lambda function on each item.
• Which in turn updated the value of each item and returns a copy of
original dictionary with updated contents.
Lambda Function
• A Lambda Function in Python programming is an anonymous
function or a function having no name. It is a small and restricted
function having no more than one line. Just like a normal function, a
Lambda function can have multiple arguments with one expression.
• In Python, lambda expressions are utilized to construct anonymous
functions. Every anonymous function you define in Python will have 3
essential parts:
The lambda keyword.
The parameters (or bound variables), and
The function body.
Lambda Function
• A lambda function can have any number of parameters, but
the function body can only contain one expression.
Moreover, a lambda is written in a single line of code and
can also be invoked immediately.
Syntax
• The formal syntax to write a lambda function is as given below:
lambda p1, p2: expression
• Here, p1 and p2 are the parameters which are passed to the lambda function.
You can add as many or few parameters as you need.
• However, notice that we do not use brackets around the parameters as we do
with regular functions.
• The last part (expression) is any valid python expression that operates on the
parameters you provide to the function.
Example:
adder = lambda x, y: x + y
print (adder (1, 2))
output:
3
Code Explanation
• Here, we define a variable that will hold the result returned by the lambda function.
1. The lambda keyword used to define an anonymous function.
2. x and y are the parameters that we pass to the lambda function.
3. This is the body of the function, which adds the 2 parameters we passed.
Notice that it is a single expression. You cannot write multiple statements in the body of a lambda function.
4. We call the function and print the returned value.
string='some kind of a useless lambda'
print(lambda string : print(string))
The above one is invalid.
x="some kind of a useless lambda"
(lambda x : print(x))(x)
The above one is valid
• Code Explanation
1.Here is the same string we defined in the previous example.
2.In this part, we are defining a lambda and calling it immediately by
passing the string as an argument.
Modules
• A Python module is a file containing Python definitions and
statements. A module can define functions, classes, and variables. A
module can also include runnable code. Grouping related code into a
module makes the code easier to understand and use. It also makes the
code logically organized.
To create a simple module
# A simple module, calc.py
def add(x, y):
return (x+y)
def subtract(x, y):
return (x-y)
Import Module in Python – Import statement
• We can import the functions, classes defined in a module to another module using
the import statement in some other Python source file.
• Syntax:
import module
• When the interpreter encounters an import statement, it imports the module if the module
is present in the search path.
• A search path is a list of directories that the interpreter searches for importing a module.
• For example, to import the module calc.py, we need to put the following command at the
top of the script.
• Note: This does not import the functions or classes directly instead imports
the module only. To access the functions inside the module the dot(.)
operator is used.
Example
# importing module calc.py
import calc
print(calc.add(10, 2))
Output:
12
The from import Statement
• Python’s from statement lets you import specific attributes from a module without
importing the module as a whole.
Example:
from math import sqrt, factorial
print(sqrt(16))
print(factorial(6))
The above code imports sqrt() and factorial from the module math
Output:
4.0
720
Import all Names – From import * Statement
• The * symbol used with the from import statement is used to import
all the names from a module to a current namespace.
Syntax:
from module_name import *
Example:
from math import *
print(sqrt(16))
print(factorial(6))
Locating Modules
• Whenever a module is imported in Python the interpreter looks for
several locations. First, it will check for the built-in module, if not found
then it looks for a list of directories defined in the sys.path. Python
interpreter searches for the module in the following manner –
• First, it searches for the module in the current directory.
• If the module isn’t found in the current directory, Python then searches
each directory in the shell variable PYTHONPATH. The PYTHONPATH
is an environment variable, consisting of a list of directories.
• If that also fails python checks the installation-dependent list of
directories configured at the time Python is installed.
Importing and renaming module
We can rename the module while importing it using the as keyword.
Example:
import math as gfg
print(gfg.sqrt(16))
print(gfg.factorial(6))
Output
4.0
720
Using the dir() Function
• There is a built-in function to list all the function names (or variable names) in a
module. The dir() function:
Example
• List all the defined names belonging to the platform module:
import platform
x = dir(platform)
print(x)
Sys Module in Python
• The sys module in Python provides various functions and variables
that are used to manipulate different parts of the Python runtime
environment. It allows operating on the interpreter as it provides
access to the variables and functions that interact strongly with the
interpreter.
• Let’s consider the below example.
import sys
print(sys.version)
Sys Module
Output:
3.6.9 (default, Oct 8 2020, 12:12:24
[GCC 8.4.0]
• In the above example, sys.version is used which returns a string
containing the version of Python Interpreter with some additional
information.
• This shows how the sys module interacts with the interpreter.
Input and Output using sys
• The sys modules provide variables for better control over input or output.
• We can even redirect the input and output to other devices.
• This can be done using three variables –
stdin
stdout
stderr
• stdin: It can be used to get input from the command line directly.
• It used is for standard input. It internally calls the input() method. It, also,
automatically adds ‘n’ after each sentence.
Example:
import sys
for line in sys.stdin:
if 'q' == line.rstrip():
break
print(f'Input : {line}')
print("Exit")
stdout
• A built-in file object that is analogous to the interpreter’s standard output stream in Python.
• stdout is used to display output directly to the screen console.
• Output can be of any form, it can be output from a print statement, an expression statement,
and even a prompt direct for input.
• By default, streams are in text mode. In fact, wherever a print function is called within the
code, it is first written to sys.stdout and then finally on to the screen.
• Example:
import sys
sys.stdout.write('Hello')
Working with modules
• sys.path is a built-in variable within the sys module that returns the list
of directories that the interpreter will search for the required module.
• When a module is imported within a Python file, the interpreter first
searches for the specified module among its built-in modules.
• If not found it looks through the list of directories defined by sys.path.
Math module
• From doing simple to complex mathematical operations(like trigonometric,
logarithmic operations etc) in python we may need to use the math() module.
• The python math module is used to access mathematical functions.
• All methods of math() function are used for integer or real type objects but not for
complex numbers.
• To use this function, we need to import it in our code
import math
Constants
• We use these constants for calculation in python.
Descriptions
• Pi - Return the value of pi: 3.141592
• E - Return the value of natural base e. e is 0.718282
• tau - Returns the value of tau. tau = 6.283185
• inf - Returns the infinite
• nan - Not a number type
Time module
• There is a popular time module available in Python which provides
functions for working with times and for converting between
representations.
• https://www.programiz.com/python-programming/time
Importing Time module
• Python has a module named time to handle time-related tasks.
• To use functions defined in the module, we need to import the module first. Here's how:
import time
Python time.time()
The time() function returns the number of seconds passed since epoch.
For Unix system, January 1, 1970, 00:00:00 at UTC is epoch (the point where time
begins).
Example:
import time
seconds = time.time()
print("Seconds since epoch =", seconds)
Python time.ctime()
• The time.ctime() function takes seconds passed since epoch as an argument and returns
a string representing local time.
• Example:
import time
# seconds passed since epoch
seconds = 1545925769.9618232
local_time = time.ctime(seconds)
print("Local time:", local_time)
• If you run the program, the output will be something like:
• Local time: Thu Dec 27 15:49:29 2018
Python time.sleep()
• The sleep() function suspends (delays) execution of the current thread
for the given number of seconds.
import time
print("This is printed immediately.")
time.sleep(2.4)
print("This is printed after 2.4 seconds.")
dir() Function Example
• import platform
x = dir(platform)
print(x)
• my_list = [1, 2, 3]
print(dir(my_list))
import math
print(dir(math))
HELP MODULE
The help() method calls the built-in Python help
system.
Syntax
help(object)
help() Parameters
The help() method takes a maximum of one
parameter.
>>> help(list)
>>> help(dict)
>>> help(print)
>>> help([1, 2, 3])
>>> help('random thing')
>>> help('print')
>>> help('def')
>>> from math import * help('math.pow')
SECTION-A
1.Which keyword is used for function?
A) Fun B) Define C) Def D) Function
2) Which of the following functions is not a built-in function in python?
A) Seed() B) Sqrt() C) Factorial() D) Print()
3Which of the following refers to mathematical function?
A) Sqrt B) Rhombus C) Add D) Sub
4) What is the value returned by math.floor(3.4)?
A) 3 B) 4 C) 4.0 D) 3.0
5) Where is function defined?
A) Module B) Class C) Another function D) All of the mentioned
QUESTION BANK
SECTION B
1. Write about functions with an example.
2. Explain how to pass parameters to a function with an example.
3. Write about built-in functions.
4. Explain variable number of arguments.
5. Explain function definition with an example.
6. Write a short notes on scope of functions.
7. Write about type conversion with an example.
8. Write a notes on type coercion with an example.
9. Write about time module with an example.
10. Write about sys module with an example.
11. Explain local scope with an example.
12. Write about global scope with an example.
13. Explain about types of arguments used in function.
14. Write a short notes on lambda functions.
15. Explain the help module in python.
SECTION C
1. Discuss briefly about standard modules in python.
2. Explain about math module in python.
3. Discuss about mapping functions in a dictionary.
4. Discuss about variable number of arguments with an example.
5. Write recursive functions for GCD of two integers.
6. Write about the types of type conversion with an example.
7. Discuss in detail about the scope of functions with an example.
8. Explain about the built in functions in detail.
References
URL References
1. https://www.w3schools.com/python/python_intro.asp
2. https://www.tutorialspoint.com/python/index.htm
3. https://static.realpython.com/python-basics-sample-chapters.pdf
4. https://assets.openstax.org/oscms-prodcms/media/documents/Introduction_to_Python_Programming_-_WEB.pd
f
5. https://www.programiz.com/python-programming
Book References:
1) Mark Summerfield, Programming in Python 3: A Complete introduction to the Python Language, Addison-
Wesley Professional, 2009.
2) Martin C. Brown, PYTHON: The Complete Reference, McGraw-Hill, 2001
Online Tool Used
1. https://www.online-python.com/
2. https://www.python.org/
THANK YOU

Python-Mastering python : Tips and techniques

  • 1.
    Name of theFaculty Dr.G.Paramasivam Department Computer Science Designation Associate Professor Name of the Course Python Programming Semester V Subject Code 5EA Batch 2023 Unit & Course Topic Unit -III: Functions
  • 2.
    Syllabus: Unit -III FUNCTIONS: Definition - Passing parameters to a Function - Built-in functions- Variable Number of Arguments - Scope – Type conversion-Type coercion-Passing Functions to a Function - Mapping Functions in a Dictionary – Lambda - Modules - Standard Modules – sys – math – time - dir - help Function.
  • 3.
    Functions Definition Passing parameters toa Function  Built-in functions  Variable Number of Arguments  Scope
  • 4.
    Introduction •A function isa block of code to perform a specific task. •This provides better modularity and high degree of reusability. •As our program grows larger and larger, functions make it more organizable and manageable. •Functions in python are defined using the block keyword “ def ", followed with the function's name as the block's name.
  • 5.
    Function Definition • Keyworddef - marks the start of the function header. • A function name is used to identify the function. • Parameters (arguments) can be used to pass values to a function which are optional. • colon (:) - to mark the end of the function header. • Any number of python statements that make up the function body. Statements should have the same indentation level. • An optional return statement to return a value from the function.
  • 8.
    Example1: def add( arg1,arg2 ): total = arg1 + arg2 print "Inside the function : ", total return total; EXAMPLE 2: def fun(): print("") fun()
  • 9.
    Passing parameters toa Function • The function definition consists of the name, the parameters needed, the steps that will be carried out by the function and returning values if any. • A function in Python is called by using its name followed by parentheses. In case parameters are present, these are included in the parentheses.
  • 10.
  • 12.
  • 13.
    Built-in functions 1) Pythonabs() - returns absolute value of a number 2) Python all() - returns true when all elements in iterable is true 3) Python any() - Checks if any Element of an Iterable is True 4) Python ascii() - Returns String Containing Printable Representation 5) Python bin() - converts integer to binary string 6) Python bool() - Converts a Value to Boolean
  • 14.
    BUILT IN FUNCTIONS 7)Python bytearray() - returns array of given byte size. 8) Python bytes() - returns immutable bytes object 9) Python callable() - Checks if the Object is Callable 10) Python chr() - Returns a Character (a string) from an Integer 11) Python classmethod() - returns class method for given function 12) Python compile() - Returns a Python code object
  • 15.
    BUILT IN FUNCTIONS 13)Python complex() - Creates a Complex Number 14) Python delattr() - Deletes Attribute From the Object 15) Python dict() - Creates a Dictionary 16) Python dir() - Tries to Return Attributes of Object 17) Python divmod() - Returns a Tuple of Quotient and Remainder 18) Python enumerate() - Returns an Enumerate Object
  • 16.
    Link to learnpython Functions • https://www.programiz.com/python-programming/method s/built-in • https://data-flair.training/blogs/python-built-in-functions/
  • 17.
    Variable number ofarguments An argument is a variable, value, or object passed to a function or method as input. In Python, there are two ways to define a function that can take a variable number of arguments. Different forms of this type are: • Positional arguments • Keyword arguments
  • 18.
    Variable number ofarguments Positional arguments are arguments that need to be included in the proper position or order. The first positional argument always needs to be listed first when the function is called. The second positional argument needs to be listed second, the third positional argument listed third, etc. General syntax for positional argument is: function(*iterable)
  • 19.
    EXAMPLE 1 def positional_args(*argv): forarg in argv: print (arg) positional_args ('Hello', ‘All’, ‘Goodmorning’) The arguments passed by the calling function are received by *argv. The passed arguments will be unpacked one by one within the function.
  • 20.
    EXAMPLE 2 def positional_args(arg1, *argv): print ("First argument :", arg1) for arg in argv: print("Next argument through *argv :", arg) positional_args ('Hello', ‘All', ‘Good', ‘Morning’)
  • 21.
    Keyword arguments A keywordargument is an argument passed to a function or method that is preceded by a keyword and an equal sign.  The general form is: function(keyword = value) Where function is the function name, the keyword is the keyword argument, and value is the value or object passed as that keyword.
  • 22.
    Example def key_args(**kwargs): for key,value in kwargs.items(): print ("%s = %s" %(key, value)) key_args (first =‘Hello’, mid =‘all', last='Goodmorning')
  • 23.
    Example2 def var_arg(*args,**kwargs): print("args: ",args) print("kwargs: ", kwargs) var_arg ('Good','for','All',first="Good",mid="for",last= "all")
  • 24.
    Python Variable Scope Thescope of a variable in python is that part of the code where it is visible.
  • 25.
    Local Scope inPython • The local scope or function scope is a Python scope created at function calls. Every time you call a function, you’re also creating a new local scope. • By default, parameters and names that you assign inside a function exist only within the function or local scope associated with the function call. When the function returns, the local scope is destroyed and the names are forgotten.
  • 26.
    Example for localScope • def myfunc(): x = 300 print(x) myfunc()
  • 27.
    Global Scope • Avariable created in the main body of the Python code is a global variable and belongs to the global scope. • Global variables are available from within any scope, global and local.
  • 28.
    Example for GlobalScope • x = 300 def myfunc(): print(x) myfunc() print(x)
  • 29.
    Global Keyword • Ifyou need to create a global variable, but are stuck in the local scope, you can use the global keyword. • The global keyword makes the variable global. • Example def myfunc(): global x x = 300 myfunc() print(x)
  • 30.
    Built-in Scope • Thebuilt-in scope has all the names that are loaded into python variable scope when we start the interpreter. • For example, we never need to import any module to access functions like print() and id(). • If a Variable is not defined in local, Enclosed or global scope, then python looks for it in the built- in scope.
  • 31.
    • # Built-inScope from math import pi def inner(): # pi = 'not defined in inner pi' print(pi) inner()
  • 32.
    Enclosing Scope • Enclosing(or nonlocal) scope is a special scope that only exists for nested functions. If the local scope is an inner or nested function, then the enclosing scope is the scope of the outer or enclosing function. This scope contains the names that you define in the enclosing function. The names in the enclosing scope are visible from the code of the inner and enclosing functions.
  • 33.
    EXAMPLE def red(): a=1 def blue(): print(“INNERBLOCK”) a=2 b=2 print(a) print(b) blue() print(“OUTER BLOCK”,a) red()
  • 34.
    Type Conversion • Theprocess of converting the value of one data type (integer, string, float, etc.) to another data type is called type conversion. Python has two types of type conversion. • Implicit Type Conversion • Explicit Type Conversion
  • 35.
    Implicit Type Conversion InImplicit type conversion, Python automatically converts one data type to another data type. This process doesn't need any user involvement. num1= 123 num2 = 1.23 num_new = num1+ num2 print("datatype of num_int:",type(num1)) print("datatype of num_flo:",type(num2)) print("Value of num_new:",num_new) print("datatype of num_new:",type(num_new))
  • 36.
    Explicit Type Conversion •In Explicit Type Conversion, users convert the data type of an object to required data type. We use the predefined functions like int(), float(), str(), etc to perform explicit type conversion. • This type of conversion is also called typecasting because the user casts (changes) the data type of the objects. Syntax : <required_datatype>(expression)
  • 37.
    Properties of TypeConversion • Type Conversion is the conversion of object from one data type to another data type. • Implicit Type Conversion is automatically performed by the Python interpreter. • Python avoids the loss of data in Implicit Type Conversion. • Explicit Type Conversion is also called Type Casting, the data types of objects are converted using predefined functions by the user. • In Type Casting, loss of data may occur as we enforce the object to a specific data type.
  • 38.
    Type Coercion • Pythondon't have type coercion. Python doesn't ever implicitly converts one object to another type of object.
  • 39.
    For Example: >>> name= "Trey" >>> x 2 >>> name + x Output: Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can only concatenate str (not "int") to str The reason is that strings in Python don't know how to use the plus operator with numbers and numbers in Python don't know how to use the plus operator with strings, which means the code doesn't work.
  • 40.
    Passing Functions toa Function • To pass a function as an argument to another function, write the name of the function without parenthesis in the function call statement (just like what we do with variables) and accept the reference of the function as a parameter in the called function.
  • 41.
    Example: def fun2(): print('This isfun2') def fun1(x): print('This is fun1') x() #passing fun2 to fun1 fun1(fun2) ''' This is fun1 This is fun2 '''
  • 42.
    To use onefunction variable in another function parameter in python def fun1(): fun1.var = 100 print(fun1.var) def fun2(): print(fun1.var) fun1() fun2() print(fun1.var)
  • 43.
    Mapping functions ina dictionary • Python map() function applies another function on a given iterable (List/String/Dictionary, etc.) and returns map object. In simple words, it traverses the list, calls the function for each element, and returns the results. • Python map object is also iterable holding the list of each iteration. We can also convert it to List or Dictionary or other types using their constructor functions.
  • 44.
    Map Function • Pythonprovides a function map() to transform the contents of given iterable sequence based on logic provided by us i.e. • Syntax: map(sequence, callback) • It accepts following arguments: • sequence : An iterable sequence • callback : A function that accepts an element as an argument and returns a new element based on the argument. • Returns : Returns a new sequence whose size is equal to passed sequence.
  • 45.
    Working of Mapfunction • It iterates over all the elements in given sequence. While iterating the sequence it calls the given callback() function on each element and then stores the returned value in a new sequence. In the end return this new sequence of transformed elements.
  • 46.
    Use map() functionwith lambda function • In the map() function along with iterable sequence we can also the lambda function. • Let’s use lambda function to reverse each string in the list like we did above using global function, listOfStr = ['hi', 'this' , 'is', 'a', 'very', 'simple', 'string' , 'for', 'us'] • # Reverse each string in the list using lambda function & map() modifiedList = list(map(lambda x : x[::-1], listOfStr)) print('Modified List : ', modifiedList) • Output: Modified List : ['ih', 'siht', 'si', 'a', 'yrev', 'elpmis', 'gnirts', 'rof', 'su'] • It iterates over the list of string and apply lambda function on each string element. • Then stores the value returned by lambda function to a new sequence for each element. • Then in last returns the new sequence of reversed string elements.
  • 47.
    Using map() functionto transform Dictionaries in Python • Suppose we have a dictionary i.e. dictOfNames = { 7 : 'sam', 8: 'john', 9: 'mathew', 10: 'riti', 11 : 'aadi', 12 : 'sachin' } • Now we want to transform the values in dictionary by appending ‘_’ at the end of each value i.e. # add an '_' to the value field in each key value pair of dictionary dictOfNames = dict(map(lambda x: (x[0], x[1] + '_'), dictOfNames.items() )) print('Modified Dictionary : ') print(dictOfNames)
  • 48.
    • Output: • ModifiedDictionary : {7: 'sam_', 8: 'john_', 9: 'mathew_', 10: 'riti_', 11: 'aadi_', 12: 'sachin_'} • map() function iterated over all the items in dictionary and then applied passed lambda function on each item. • Which in turn updated the value of each item and returns a copy of original dictionary with updated contents.
  • 49.
    Lambda Function • ALambda Function in Python programming is an anonymous function or a function having no name. It is a small and restricted function having no more than one line. Just like a normal function, a Lambda function can have multiple arguments with one expression. • In Python, lambda expressions are utilized to construct anonymous functions. Every anonymous function you define in Python will have 3 essential parts: The lambda keyword. The parameters (or bound variables), and The function body.
  • 50.
    Lambda Function • Alambda function can have any number of parameters, but the function body can only contain one expression. Moreover, a lambda is written in a single line of code and can also be invoked immediately.
  • 51.
    Syntax • The formalsyntax to write a lambda function is as given below: lambda p1, p2: expression • Here, p1 and p2 are the parameters which are passed to the lambda function. You can add as many or few parameters as you need. • However, notice that we do not use brackets around the parameters as we do with regular functions. • The last part (expression) is any valid python expression that operates on the parameters you provide to the function.
  • 52.
    Example: adder = lambdax, y: x + y print (adder (1, 2)) output: 3 Code Explanation • Here, we define a variable that will hold the result returned by the lambda function. 1. The lambda keyword used to define an anonymous function. 2. x and y are the parameters that we pass to the lambda function. 3. This is the body of the function, which adds the 2 parameters we passed. Notice that it is a single expression. You cannot write multiple statements in the body of a lambda function. 4. We call the function and print the returned value.
  • 53.
    string='some kind ofa useless lambda' print(lambda string : print(string)) The above one is invalid. x="some kind of a useless lambda" (lambda x : print(x))(x) The above one is valid • Code Explanation 1.Here is the same string we defined in the previous example. 2.In this part, we are defining a lambda and calling it immediately by passing the string as an argument.
  • 54.
    Modules • A Pythonmodule is a file containing Python definitions and statements. A module can define functions, classes, and variables. A module can also include runnable code. Grouping related code into a module makes the code easier to understand and use. It also makes the code logically organized.
  • 55.
    To create asimple module # A simple module, calc.py def add(x, y): return (x+y) def subtract(x, y): return (x-y)
  • 56.
    Import Module inPython – Import statement • We can import the functions, classes defined in a module to another module using the import statement in some other Python source file. • Syntax: import module • When the interpreter encounters an import statement, it imports the module if the module is present in the search path. • A search path is a list of directories that the interpreter searches for importing a module. • For example, to import the module calc.py, we need to put the following command at the top of the script. • Note: This does not import the functions or classes directly instead imports the module only. To access the functions inside the module the dot(.) operator is used.
  • 57.
    Example # importing modulecalc.py import calc print(calc.add(10, 2)) Output: 12
  • 58.
    The from importStatement • Python’s from statement lets you import specific attributes from a module without importing the module as a whole. Example: from math import sqrt, factorial print(sqrt(16)) print(factorial(6)) The above code imports sqrt() and factorial from the module math Output: 4.0 720
  • 59.
    Import all Names– From import * Statement • The * symbol used with the from import statement is used to import all the names from a module to a current namespace. Syntax: from module_name import * Example: from math import * print(sqrt(16)) print(factorial(6))
  • 60.
    Locating Modules • Whenevera module is imported in Python the interpreter looks for several locations. First, it will check for the built-in module, if not found then it looks for a list of directories defined in the sys.path. Python interpreter searches for the module in the following manner – • First, it searches for the module in the current directory. • If the module isn’t found in the current directory, Python then searches each directory in the shell variable PYTHONPATH. The PYTHONPATH is an environment variable, consisting of a list of directories. • If that also fails python checks the installation-dependent list of directories configured at the time Python is installed.
  • 61.
    Importing and renamingmodule We can rename the module while importing it using the as keyword. Example: import math as gfg print(gfg.sqrt(16)) print(gfg.factorial(6)) Output 4.0 720
  • 62.
    Using the dir()Function • There is a built-in function to list all the function names (or variable names) in a module. The dir() function: Example • List all the defined names belonging to the platform module: import platform x = dir(platform) print(x)
  • 63.
    Sys Module inPython • The sys module in Python provides various functions and variables that are used to manipulate different parts of the Python runtime environment. It allows operating on the interpreter as it provides access to the variables and functions that interact strongly with the interpreter. • Let’s consider the below example. import sys print(sys.version)
  • 64.
    Sys Module Output: 3.6.9 (default,Oct 8 2020, 12:12:24 [GCC 8.4.0] • In the above example, sys.version is used which returns a string containing the version of Python Interpreter with some additional information. • This shows how the sys module interacts with the interpreter.
  • 65.
    Input and Outputusing sys • The sys modules provide variables for better control over input or output. • We can even redirect the input and output to other devices. • This can be done using three variables – stdin stdout stderr • stdin: It can be used to get input from the command line directly. • It used is for standard input. It internally calls the input() method. It, also, automatically adds ‘n’ after each sentence.
  • 66.
    Example: import sys for linein sys.stdin: if 'q' == line.rstrip(): break print(f'Input : {line}') print("Exit")
  • 67.
    stdout • A built-infile object that is analogous to the interpreter’s standard output stream in Python. • stdout is used to display output directly to the screen console. • Output can be of any form, it can be output from a print statement, an expression statement, and even a prompt direct for input. • By default, streams are in text mode. In fact, wherever a print function is called within the code, it is first written to sys.stdout and then finally on to the screen. • Example: import sys sys.stdout.write('Hello')
  • 68.
    Working with modules •sys.path is a built-in variable within the sys module that returns the list of directories that the interpreter will search for the required module. • When a module is imported within a Python file, the interpreter first searches for the specified module among its built-in modules. • If not found it looks through the list of directories defined by sys.path.
  • 69.
    Math module • Fromdoing simple to complex mathematical operations(like trigonometric, logarithmic operations etc) in python we may need to use the math() module. • The python math module is used to access mathematical functions. • All methods of math() function are used for integer or real type objects but not for complex numbers. • To use this function, we need to import it in our code import math
  • 70.
    Constants • We usethese constants for calculation in python. Descriptions • Pi - Return the value of pi: 3.141592 • E - Return the value of natural base e. e is 0.718282 • tau - Returns the value of tau. tau = 6.283185 • inf - Returns the infinite • nan - Not a number type
  • 71.
    Time module • Thereis a popular time module available in Python which provides functions for working with times and for converting between representations. • https://www.programiz.com/python-programming/time
  • 72.
    Importing Time module •Python has a module named time to handle time-related tasks. • To use functions defined in the module, we need to import the module first. Here's how: import time Python time.time() The time() function returns the number of seconds passed since epoch. For Unix system, January 1, 1970, 00:00:00 at UTC is epoch (the point where time begins). Example: import time seconds = time.time() print("Seconds since epoch =", seconds)
  • 73.
    Python time.ctime() • Thetime.ctime() function takes seconds passed since epoch as an argument and returns a string representing local time. • Example: import time # seconds passed since epoch seconds = 1545925769.9618232 local_time = time.ctime(seconds) print("Local time:", local_time) • If you run the program, the output will be something like: • Local time: Thu Dec 27 15:49:29 2018
  • 74.
    Python time.sleep() • Thesleep() function suspends (delays) execution of the current thread for the given number of seconds. import time print("This is printed immediately.") time.sleep(2.4) print("This is printed after 2.4 seconds.")
  • 76.
    dir() Function Example •import platform x = dir(platform) print(x) • my_list = [1, 2, 3] print(dir(my_list)) import math print(dir(math))
  • 77.
    HELP MODULE The help()method calls the built-in Python help system. Syntax help(object) help() Parameters The help() method takes a maximum of one parameter.
  • 78.
    >>> help(list) >>> help(dict) >>>help(print) >>> help([1, 2, 3]) >>> help('random thing') >>> help('print') >>> help('def') >>> from math import * help('math.pow')
  • 79.
    SECTION-A 1.Which keyword isused for function? A) Fun B) Define C) Def D) Function 2) Which of the following functions is not a built-in function in python? A) Seed() B) Sqrt() C) Factorial() D) Print() 3Which of the following refers to mathematical function? A) Sqrt B) Rhombus C) Add D) Sub 4) What is the value returned by math.floor(3.4)? A) 3 B) 4 C) 4.0 D) 3.0 5) Where is function defined? A) Module B) Class C) Another function D) All of the mentioned QUESTION BANK
  • 80.
    SECTION B 1. Writeabout functions with an example. 2. Explain how to pass parameters to a function with an example. 3. Write about built-in functions. 4. Explain variable number of arguments. 5. Explain function definition with an example. 6. Write a short notes on scope of functions. 7. Write about type conversion with an example. 8. Write a notes on type coercion with an example. 9. Write about time module with an example. 10. Write about sys module with an example. 11. Explain local scope with an example. 12. Write about global scope with an example. 13. Explain about types of arguments used in function. 14. Write a short notes on lambda functions. 15. Explain the help module in python.
  • 81.
    SECTION C 1. Discussbriefly about standard modules in python. 2. Explain about math module in python. 3. Discuss about mapping functions in a dictionary. 4. Discuss about variable number of arguments with an example. 5. Write recursive functions for GCD of two integers. 6. Write about the types of type conversion with an example. 7. Discuss in detail about the scope of functions with an example. 8. Explain about the built in functions in detail.
  • 82.
    References URL References 1. https://www.w3schools.com/python/python_intro.asp 2.https://www.tutorialspoint.com/python/index.htm 3. https://static.realpython.com/python-basics-sample-chapters.pdf 4. https://assets.openstax.org/oscms-prodcms/media/documents/Introduction_to_Python_Programming_-_WEB.pd f 5. https://www.programiz.com/python-programming Book References: 1) Mark Summerfield, Programming in Python 3: A Complete introduction to the Python Language, Addison- Wesley Professional, 2009. 2) Martin C. Brown, PYTHON: The Complete Reference, McGraw-Hill, 2001 Online Tool Used 1. https://www.online-python.com/ 2. https://www.python.org/
  • 83.