SECTION C
1. Write some of the Python Built-in Functions
The Python built-in functions are defined as the functions whose functionality is pre-defined in Python. The python interpreter has several functions that are always present for use. These functions are known as Built-in Functions. There are several built-in functions in Python which are listed below:
Python abs() Function
The python abs() function is used to return the absolute value of a number. It takes only one argument, a number whose absolute value is to be returned. The argument can be an integer and floating-point number. If the argument is a complex number, then, abs() returns its magnitude.
Python abs() Function Example
- # integer number
- Integer = -20
- Print('Absolute value of -40 is:', abs(integer))
- # floating number
- Floating = -20.83
- Print('Absolute value of -40.83 is:', abs(floating))
Output:
Absolute value of -20 is: 20
Absolute value of -20.83 is: 20.83
Python all() Function
The python all() function accepts an iterable object (such as list, dictionary, etc.). It returns true if all items in passed iterable are true. Otherwise, it returns False. If the iterable object is empty, the all() function returns True.
Python all() Function Example
- # all values true
- k = [1, 3, 4, 6]
- Print(all(k))
- # all values false
- k = [0, False]
- Print(all(k))
- # one false value
- k = [1, 3, 7, 0]
- Print(all(k))
- # one true value
- k = [0, False, 5]
- Print(all(k))
- # empty iterable
- k = []
- Print(all(k))
Output:
True
False
False
False
True
Python bin() Function
The python bin() function is used to return the binary representation of a specified integer. A result always starts with the prefix 0b.
Python bin() Function Example
- x = 10
- y = bin(x)
- Print (y)
Output:
0b1010
Python bool()
The python bool() converts a value to boolean(True or False) using the standard truth testing procedure.
Python bool() Example
- Test1 = []
- Print(test1,'is',bool(test1))
- Test1 = [0]
- Print(test1,'is',bool(test1))
- Test1 = 0.0
- Print(test1,'is',bool(test1))
- Test1 = None
- Print(test1,'is',bool(test1))
- Test1 = True
- Print(test1,'is',bool(test1))
- Test1 = 'Easy string'
- Print(test1,'is',bool(test1))
Output:
[] is False
[0] is True
0.0 is False
None is False
True is True
Easy string is True
Python bytes()
The python bytes() in Python is used for returning a bytes object. It is an immutable version of the bytearray() function.
It can create empty bytes object of the specified size.
Python bytes() Example
- String = "Hello World."
- Array = bytes(string, 'utf-8')
- Print(array)
Output:
b ' Hello World.'
Python callable() Function
A python callable() function in Python is something that can be called. This built-in function checks and returns true if the object passed appears to be callable, otherwise false.
Python callable() Function Example
- x = 8
- Print(callable(x))
Output:
False
Python compile() Function
The python compile() function takes source code as input and returns a code object which can later be executed by exec() function.
Python compile() Function Example
- # compile string source to code
- Code_str = 'x=5\ny=10\nprint("sum =",x+y)'
- Code = compile(code_str, 'sum.py', 'exec')
- Print(type(code))
- Exec(code)
- Exec(x)
Output:
<class 'code'>
Sum = 15
Python exec() Function
The python exec() function is used for the dynamic execution of Python program which can either be a string or object code and it accepts large blocks of code, unlike the eval() function which only accepts a single expression.
Python exec() Function Example
- x = 8
- Exec('print(x==8)')
- Exec('print(x+4)')
Output:
True
12
Python sum() Function
As the name says, python sum() function is used to get the sum of numbers of an iterable, i.e., list.
Python sum() Function Example
- s = sum([1, 2,4 ])
- Print(s)
- s = sum([1, 2, 4], 10)
- Print(s)
Output:
7
17
2. What are the modules in python explain with examples?
A module allows you to logically organize your Python code. Grouping related code into a module makes the code easier to understand and use. A module is a Python object with arbitrarily named attributes that you can bind and reference.
Simply, a module is a file consisting of Python code. A module can define functions, classes and variables. A module can also include runnable code.
Example
The Python code for a module named aname normally resides in a file named aname.py. Here's an example of a simple module, support.py
Defprint_func( par ):
Print "Hello : ", par
Return
The import Statement
You can use any Python source file as a module by executing an import statement in some other Python source file. The import has the following syntax −
Import module1[, module2[,... ModuleN]
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 before importing a module. For example, to import the module support.py, you need to put the following command at the top of the script −
#!/usr/bin/python
# Import module support
Import support
# Now you can call defined function that module as follows
Support.print_func("Zara")
When the above code is executed, it produces the following result −
Hello : Zara
A module is loaded only once, regardless of the number of times it is imported. This prevents the module execution from happening over and over again if multiple imports occur.
The from...import Statement
Python's from statement lets you import specific attributes from a module into the current namespace. The from...import has the following syntax −
Frommodname import name1[, name2[, ... NameN]]
For example, to import the function fibonacci from the module fib, use the following statement −
From fib import fibonacci
This statement does not import the entire module fib into the current namespace; it just introduces the item fibonacci from the module fib into the global symbol table of the importing module.
The from...import * Statement
It is also possible to import all names from a module into the current namespace by using the following import statement −
Frommodname import *
This provides an easy way to import all the items from a module into the current namespace; however, this statement should be used sparingly.
Locating Modules
When you import a module, the Python interpreter searches for the module in the following sequences −
- The current directory.
- If the module isn't found, Python then searches each directory in the shell variable PYTHONPATH.
- If all else fails, Python checks the default path. On UNIX, this default path is normally /usr/local/lib/python/.
The module search path is stored in the system module sys as the sys.path variable. The sys.path variable contains the current directory, PYTHONPATH, and the installation-dependent default.
3. Explain the PYTHONPATH Variable with examples
The PYTHONPATH is an environment variable, consisting of a list of directories. The syntax of PYTHONPATH is the same as that of the shell variable PATH.
Here is a typical PYTHONPATH from a Windows system −
Set PYTHONPATH = c:\python20\lib;
And here is a typical PYTHONPATH from a UNIX system −
Set PYTHONPATH = /usr/local/lib/python
Namespaces and Scoping
Variables are names (identifiers) that map to objects. A namespace is a dictionary of variable names (keys) and their corresponding objects (values).
A Python statement can access variables in a local namespace and in the global namespace. If a local and a global variable have the same name, the local variable shadows the global variable.
Each function has its own local namespace. Class methods follow the same scoping rule as ordinary functions.
Python makes educated guesses on whether variables are local or global. It assumes that any variable assigned a value in a function is local.
Therefore, in order to assign a value to a global variable within a function, you must first use the global statement.
The statement global VarName tells Python that VarName is a global variable. Python stops searching the local namespace for the variable.
For example, we define a variable Money in the global namespace. Within the function Money, we assign Money a value, therefore Python assumes Money as a local variable. However, we accessed the value of the local variable Money before setting it, so an UnboundLocalError is the result. Uncommenting the global statement fixes the problem.
#!/usr/bin/python
Money = 2000
DefAddMoney():
# Uncomment the following line to fix the code:
# global Money
Money = Money + 1
Print Money
AddMoney()
Print Money
4. What is the dir( ) Function?
The dir() built-in function returns a sorted list of strings containing the names defined by a module.
The list contains the names of all the modules, variables and functions that are defined in a module. Following is a simple example −
#!/usr/bin/python
# Import built-in module math
Import math
Content = dir(math)
Print content
When the above code is executed, it produces the following result −
['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan',
'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp',
'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log',
'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh',
'sqrt', 'tan', 'tanh']
Here, the special string variable __name__ is the module's name, and __file__ is the filename from which the module was loaded.
5. What are the packages in Python?
A package is a hierarchical file directory structure that defines a single Python application environment that consists of modules and subpackages and sub-subpackages, and so on.
Consider a file Pots.py available in Phone directory. This file has following line of source code −
#!/usr/bin/python
Def Pots():
Print "I'm Pots Phone"
Similar way, we have another two files having different functions with the same name as above −
- Phone/Isdn.py file having function Isdn()
- Phone/G3.py file having function G3()
Now, create one more file __init__.py in Phone directory −
- Phone/__init__.py
To make all of your functions available when you've imported Phone, you need to put explicit import statements in __init__.py as follows −
From Pots import Pots
FromIsdn import Isdn
From G3 import G3
After you add these lines to __init__.py, you have all of these classes available when you import the Phone package.
#!/usr/bin/python
# Now import your Phone Package.
Import Phone
Phone.Pots()
Phone.Isdn()
Phone.G3()
When the above code is executed, it produces the following result −
I'm Pots Phone
I'm 3G Phone
I'm ISDN Phone
In the above example, we have taken example of a single functions in each file, but you can keep multiple functions in your files. You can also define different Python classes in those files and then you can create your packages out of those classes.
6. Explain User defined functions
Functions ar the foremost necessary side of associate application. A perform may be outlined because the organized block of reusable code, which may be known as whenever needed.
Python permits United States of America to divide an oversized program into the fundamental building blocks referred to as a perform. The perform contains the set of programming statements fencelike by . A perform may be known as multiple times to supply reusability and modularity to the Python program.
The perform helps to software engineer to interrupt the program into the smaller half. It organizes the code terribly effectively and avoids the repetition of the code. Because the program grows, perform makes the program a lot of organized.
Python offer United States of America varied constitutional functions like range() or print(). Although, the user will produce its functions, which may be known as user-defined functions.
There ar primarily 2 forms of functions.
•User-define functions - The user-defined functions ar those outline by the user to perform the precise task.
•Built-in functions - The constitutional functions ar those functions that ar pre-defined in Python.
In this tutorial, we'll discuss the user outline functions.
Advantage of Functions in Python
There ar the subsequent blessings of Python functions.
•Using functions, we will avoid revising constant logic/code title of respectin and once more in a very program.
•We will decision Python functions multiple times in a very program and anyplace in a very program.
•We will track an oversized Python program simply once it's divided into multiple functions.
•Reusability is that the main action of Python functions.
•However, perform vocation is usually overhead in a very Python program.
Creating a perform
Python provides the def keyword to outline the perform. The syntax of the outline perform is given below.
Syntax:
1.defmy_function(parameters):
2.function_block
3.come back expression
Let's perceive the syntax of functions definition.
•The def keyword, together with the perform name is employed to outline the perform.
•The symbol rule should follow the perform name.
•A perform accepts the parameter (argument), and that they may be facultative.
•The perform block is started with the colon (:), and block statements should be at constant indentation.
•The come back statement is employed to come back the worth. A perform will have only 1 come back
7. Creating function without return statement
- # Defining function
- Def sum():
- a = 10
- b = 20
- c = a+b
- # calling sum() function in print statement
- Print(sum())
Output:
None
In the above code, we have defined the same function without the return statement as we can see that the sum() function returned the None object to the caller function.
8. What is Arguments in function explain with examples?
The arguments are types of information which can be passed into the function. The arguments are specified in the parentheses. We can pass any number of arguments, but they must be separate them with a comma.
Consider the following example, which contains a function that accepts a string as the argument.
Example 1
- #defining the function
- Def func (name):
- Print("Hi ",name)
- #calling the function
- Func("Devansh")
Output:
Hi Devansh
Example 2
- #Python function to calculate the sum of two variables
- #defining the function
- Def sum (a,b):
- Return a+b;
- #taking values from the user
- a = int(input("Enter a: "))
- b = int(input("Enter b: "))
- #printing the sum of a and b
- Print("Sum = ",sum(a,b))
Output:
Enter a: 10
Enter b: 20
Sum = 30
9. Explain Call by reference in Python with examples
In Python, call by reference means passing the actual value as an argument in the function. All the functions are called by reference, i.e., all the changes made to the reference inside the function revert back to the original value referred by the reference.
Example 1 Passing Immutable Object (List)
- #defining the function
- Def change_list(list1):
- List1.append(20)
- List1.append(30)
- Print("list inside function = ",list1)
- #defining the list
- List1 = [10,30,40,50]
- #calling the function
- Change_list(list1)
- Print("list outside function = ",list1)
Output:
List inside function = [10, 30, 40, 50, 20, 30]
List outside function = [10, 30, 40, 50, 20, 30]
Example 2 Passing Mutable Object (String)
- #defining the function
- Def change_string (str):
- Str = str + " Hows you "
- Print("printing the string inside function :",str)
- String1 = "Hi I am there"
- #calling the function
- Change_string(string1)
- Print("printing the string outside function :",string1)
Output:
Printing the string inside function : Hi I am there Hows you
Printing the string outside function : Hi I am there
10. Explain Types of arguments in python
There may be several types of arguments which can be passed at the time of function call.
- Required arguments
- Keyword arguments
- Default arguments
- Variable-length arguments
Required Arguments
Till now, we have learned about function calling in Python. However, we can provide the arguments at the time of the function call. As far as the required arguments are concerned, these are the arguments which are required to be passed at the time of function calling with the exact match of their positions in the function call and function definition. If either of the arguments is not provided in the function call, or the position of the arguments is changed, the Python interpreter will show the error.
Consider the following example.
Example 1
- Def func(name):
- Message = "Hi "+name
- Return message
- Name = input("Enter the name:")
- Print(func(name))
Output:
Enter the name: John
Hi John
Example 2
- #the function simple_interest accepts three arguments and returns the simple interest accordingly
- Def simple_interest(p,t,r):
- Return (p*t*r)/100
- p = float(input("Enter the principle amount? "))
- r = float(input("Enter the rate of interest? "))
- t = float(input("Enter the time in years? "))
- Print("Simple Interest: ",simple_interest(p,r,t))
Output:
Enter the principle amount: 5000
Enter the rate of interest: 5
Enter the time in years: 3
Simple Interest: 750.0
Example 3
- #the function calculate returns the sum of two arguments a and b
- Def calculate(a,b):
- Return a+b
- Calculate(10) # this causes an error as we are missing a required arguments b.
Output:
TypeError: calculate() missing 1 required positional argument: 'b'
Default Arguments
Python allows us to initialize the arguments at the function definition. If the value of any of the arguments is not provided at the time of function call, then that argument can be initialized with the value given in the definition even if the argument is not specified at the function call.
Example 1
- Def printme(name,age=22):
- Print("My name is",name,"and age is",age)
- Printme(name = "john")
Output:
My name is John and age is 22
Example 2
- Def printme(name,age=22):
- Print("My name is",name,"and age is",age)
- Printme(name = "john") #the variable age is not passed into the function however the default value of age is considered in the function
- Printme(age = 10,name="David") #the value of age is overwritten here, 10 will be printed as age
Output:
My name is john and age is 22
My name is David and age is 10