0% found this document useful (0 votes)
2 views

Python Functions_Unit3 1

This document provides an overview of functions in Python programming, covering their definition, syntax, and various types of arguments such as required, keyword, default, and variable-length arguments. It also explains built-in functions, the concept of passing parameters by reference or value, and introduces anonymous functions using the lambda keyword. Additionally, it discusses variable scope, type conversion, and provides examples to illustrate these concepts.

Uploaded by

kalaikarthi879
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
0% found this document useful (0 votes)
2 views

Python Functions_Unit3 1

This document provides an overview of functions in Python programming, covering their definition, syntax, and various types of arguments such as required, keyword, default, and variable-length arguments. It also explains built-in functions, the concept of passing parameters by reference or value, and introduces anonymous functions using the lambda keyword. Additionally, it discusses variable scope, type conversion, and provides examples to illustrate these concepts.

Uploaded by

kalaikarthi879
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
You are on page 1/ 25

Unit – III

Subject Handled: Mr.M.Mathiyalagan


Name of the Subject: PYTHON Programming
Class: III B.Sc IT

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.

Python -Functions

A function is a block of organized, reusable code that is used to perform a single, related action. Functions
provide better modularity for your application and a high degree of code reusing.

As you already know, Python gives you many built-in functions like print(), etc. but you can alsocreate
your own functions. These functions are called user-defined functions.

Defining a Function
You can define functions to provide the required functionality. Here are simple rules to define afunction
in Python.

Function blocks begin with the keyword def followed by the function name and parentheses ( ( )).

Any input parameters or arguments should be placed within these parentheses. You can alsodefine
parameters inside these parentheses.

The first statement of a function can be an optional statement - the documentation string of thefunction
or docstring.

The code block within every function starts with a colon (:) and is indented.

The statement return [expression] exits a function, optionally passing back an expression to thecaller. A
return statement with no arguments is the same as return None.

Syntax

def functionname( parameters ):


"function_docstring"
function_suite
return [expression]

By default, parameters have a positional behavior and you need to inform them in the same orderthat they
were defined.

Example
The following function takes a string as input parameter and prints it on standard screen.
1/9
def printme( str ):
"This prints a passed string into this function"
print str
return

Calling a Function
Defining a function only gives it a name, specifies the parameters that are to be included in the function and
structures the blocks of code.

Once the basic structure of a function is finalized, you can execute it by calling it from another function or
directly from the Python prompt. Following is the example to call printme() function −

#!/usr/bin/python
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;

# Now you can call printme function


printme("I'm first call to user defined function!")printme("Again second call
to the same function")

When the above code is executed, it produces the following result −

I'm first call to user defined function!Again


second call to the same function

Pass by reference vs value


All parameters (arguments) in the Python language are passed by reference. It means if you change what a
parameter refers to within a function, the change also reflects back in the calling function. For example −

#!/usr/bin/python
# Function definition is here
def changeme( mylist ):

2/9
"This changes a passed list into this function"mylist.append([1,2,3,4]);
print "Values inside the function: ", mylist
return

# Now you can call changeme function


mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist

Here, we are maintaining reference of the passed object and appending values in the same object.So, this
would produce the following result −

Values inside the function: [10, 20, 30, [1, 2, 3, 4]]


Values outside the function: [10, 20, 30, [1, 2, 3, 4]]

There is one more example where argument is being passed by reference and the reference isbeing
overwritten inside the called function.

#!/usr/bin/python
# Function definition is here
def changeme( mylist ):
"This changes a passed list into this function"
mylist = [1,2,3,4]; # This would assig new reference in mylist
print "Values inside the function: ", mylist
return

# Now you can call changeme function


mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist

The parameter mylist is local to the function changeme. Changing mylist within the function does notaffect
mylist. The function accomplishes nothing and finally this would produce the following result −

Values inside the function: [1, 2, 3, 4]


Values outside the function: [10, 20, 30]

3/9
Built-in Functions
The Python interpreter has a number of functions and types built into it that are always available. They are
listed here in alphabetical order.
Built-in Functions
A E L R
abs() enumerate() len() range()
aiter() eval() list() repr()
all() exec() locals() reversed()
anext() round()
any() F M
ascii() filter() map() S
float() max() set()
B format() memoryview() setattr()
bin() frozenset() min() slice()
bool() sorted()
breakpoint() G N staticmethod()
bytearray() getattr() next() str()
bytes() globals() sum()
O super()
C H object()
callable() hasattr() oct() T
chr() hash() open() tuple()
classmethod() help() ord() type()
compile() hex()
complex() P V
I pow() vars()
D id() print()
delattr() input() property() Z
dict() int() zip()
dir() isinstance()
divmod() issubclass() _
iter() __import__()

 abs(x)
Return the absolute value of a number. The argument may be an integer, a floating point number, or an
object implementing __abs__(). If the argument is a complex number, its magnitude is returned.
 aiter(async_iterable)
Return an asynchronous iterator for an asynchronous iterable. Equivalent to calling x.__aiter__().

Note: Unlike iter(), aiter() has no 2-argument variant.

 all(iterable)
Return True if all elements of the iterable are true (or if the iterable is empty). Equivalent to:

def all(iterable):
for element in iterable:
if not element:
return False
return True

4/9
 any(iterable)
Return True if any element of the iterable is true. If the iterable is empty, return False. Equivalent to:

def any(iterable):
for element in iterable:
if element:
return True
return False

 ascii(object)
As repr(), return a string containing a printable representation of an object, but escape the non-ASCII
characters in the string returned by repr() using \x, \u, or \U escapes. This generates a string similar to that
returned by repr() in Python 2.

 bin(x)
Convert an integer number to a binary string prefixed with “0b”. The result is a valid Python expression.
If x is not a Python int object, it has to define an __index__() method that returns an integer. Some
examples:

>>>
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'

 Chr(i)
Return the string representing a character whose Unicode code point is the integer i. For
example, chr(97) returns the string 'a', while chr(8364) returns the string '€'. This is the inverse of ord().

The valid range for the argument is from 0 through 1,114,111 (0x10FFFF in base 16). ValueError will be
raised if i is outside that range.

Function Arguments
You can call a function by using the following types of formal arguments −

Required arguments
Keyword arguments
Default arguments
Variable-length arguments

Required arguments

Required arguments are the arguments passed to a function in correct positional order. Here, the number of
arguments in the function call should match exactly with the function definition.

To call the function printme(), you definitely need to pass one argument, otherwise it gives a syntax error as
follows −
5/9
#!/usr/bin/python
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;

# Now you can call printme function


printme()

When the above code is executed, it produces the following result −

Traceback (most recent call last):


File "test.py", line 11, in <module>
printme();
TypeError: printme() takes exactly 1 argument (0 given)

Keyword arguments
Keyword arguments are related to the function calls. When you use keyword arguments in a function
call, the caller identifies the arguments by the parameter name.

This allows you to skip arguments or place them out of order because the Python interpreter is able to use the
keywords provided to match the values with parameters. You can also make keyword calls to the printme()
function in the following ways −

6/9
#!/usr/bin/python
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;

# Now you can call printme function


printme( str = "My string")

When the above code is executed, it produces the following result −

My string

The following example gives more clear picture. Note that the order of parameters does not matter.

#!/usr/bin/python
# Function definition is here
def printinfo( name, age ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;

# Now you can call printinfo function


printinfo( age=50, name="miki" )

When the above code is executed, it produces the following result −

Name: miki
Age 50

Default arguments
A default argument is an argument that assumes a default value if a value is not provided in the function call
for that argument. The following example gives an idea on default arguments, it prints default age if it is not
passed −

7/9
#!/usr/bin/python
# Function definition is here
def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;

# Now you can call printinfo function


printinfo( age=50, name="miki" )printinfo(
name="miki" )

When the above code is executed, it produces the following result −

Name: miki
Age 50
Name: miki
Age 35

Variable-length arguments
You may need to process a function for more arguments than you specified while defining the function. These
arguments are called variable-length arguments and are not named in the function definition, unlike required
and default arguments.

Syntax for a function with non-keyword variable arguments is this −

def functionname([formal_args,] *var_args_tuple ):"function_docstring"


function_suite
return [expression]

An asterisk (*) is placed before the variable name that holds the values of all nonkeyword variable arguments.
This tuple remains empty if no additional arguments are specified during the function call. Following is a
simple example −

#!/usr/bin/python
# Function definition is here
def printinfo( arg1, *vartuple ):

8/9
"This prints a variable passed arguments"
print "Output is: "
print arg1
for var in vartuple:
print varreturn;

# Now you can call printinfo function


printinfo( 10 )
printinfo( 70, 60, 50 )

When the above code is executed, it produces the following result −

Output is:
10
Output is:
70
60
50

The Anonymous Functions


These functions are called anonymous because they are not declared in the standard manner byusing the
def keyword. You can use the lambda keyword to create small anonymous functions.

Lambda forms can take any number of arguments but return just one value in the form of an
expression. They cannot contain commands or multiple expressions.

An anonymous function cannot be a direct call to print because lambda requires an expression

Lambda functions have their own local namespace and cannot access variables other than those in their
parameter list and those in the global namespace.

Although it appears that lambda's are a one-line version of a function, they are not equivalent to inline
statements in C or C++, whose purpose is by passing function stack allocation during invocation for
performance reasons.

Syntax
The syntax of lambda functions contains only a single statement, which is as follows −

lambda [arg1 [,arg2,. ............. argn]]:expression

Following is the example to show how lambda form of function works −


#!/usr/bin/python

# Function definition is here


sum = lambda arg1, arg2: arg1 + arg2;
# Now you can call sum as a function
print "Value of total : ", sum( 10, 20 )
print "Value of total : ", sum( 20, 20 )

When the above code is executed, it produces the following result −

Value of total : 30Value of


total : 40

The return Statement


The statement return [expression] exits a function, optionally passing back an expression to thecaller. A
return statement with no arguments is the same as return None.

All the above examples are not returning any value. You can return a value from a function asfollows −
#!/usr/bin/python
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2
print "Inside the function : ", total
return total;

# Now you can call sum function


total = sum( 10, 20 );
print "Outside the function : ", total

When the above code is executed, it produces the following result −

Inside the function : 30 Outside the


function : 30
Scope of Variables
All variables in a program may not be accessible at all locations in that program. This depends onwhere
you have declared a variable.

The scope of a variable determines the portion of the program where you can access a particular identifier.
There are two basic scopes of variables in Python −

Global variables
Local variables

Global vs. Local variables


Variables that are defined inside a function body have a local scope, and those defined outside have a global
scope.

This means that local variables can be accessed only inside the function in which they are declared, whereas
global variables can be accessed throughout the program body by all functions. When you call a function, the
variables declared inside it are brought into scope. Following is a simple example

#!/usr/bin/python
total = 0; # This is global variable.# Function
definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2; # Here total is local variable.
print "Inside the function local total : ", total
return total;

# Now you can call sum function


sum( 10, 20 );
print "Outside the function global total : ", total

When the above code is executed, it produces the following result −

Inside the function local total : 30 Outside the


function global total : 0

Type Conversion in Python


Python defines type conversion functions to directly convert one data type to another which is useful in day-
to-day and competitive programming. This article is aimed at providing information about certain conversion
functions.
There are two types of Type Conversion in Python:
1. Python Implicit Type Conversion
2. Python Explicit Type Conversion
Implicit Type Conversion in Python
In Implicit type conversion of data types in Python, the Python interpreter automatically converts one data
type to another without any user involvement. To get a more clear view of the topic see the below examples.

x = 10

print("x is of type:",type(x))

y = 10.6
print("y is of type:",type(y))

z = x + y

print(z)
print("z is of type:",type(z))

Output
x is of type: <class 'int'>
y is of type: <class 'float'>
20.6
z is of type: <class 'float'>

Explicit Type Conversion in Python


In Explicit Type Conversion in Python, the data type is manually changed by the user as per their requirement.
With explicit type conversion, there is a risk of data loss since we are forcing an expression to be changed in
some specific data type. Various forms of explicit type conversion are explained below: .

Converting integer to float


int(a, base): This function converts any data type to an integer. ‘Base’ specifies the base in which the
string is if the data type is a string.
float(): This function is used to convert any data type to a floating-point number.

# initializing string
s = "10010"

# printing string converting to int base 2


c = int(s,2)
print ("After converting to integer base 2 : ", end="")
print (c)

# printing string converting to float


e = float(s)
print ("After converting to float : ", end="")
print (e)

Output:
After converting to integer base 2 : 18
After converting to float : 10010.0
Python Type conversion using ord(), hex(), oct()
ord(): This function is used to convert a character to an integer.
hex(): This function is to convert an integer to a hexadecimal string.
oct(): This function is to convert an integer to an octal string.

# initializing integer
s = '4'

# printing character converting to integer


c = ord(s)
print ("After converting character to integer : ",end="")
print (c)

# printing integer converting to hexadecimal string


c = hex(56)
print ("After converting 56 to hexadecimal string : ",end="")
print (c)

# printing integer converting to octal string


c = oct(56)
print ("After converting 56 to octal string : ",end="")
print (c)

Output:
After converting character to integer : 52
After converting 56 to hexadecimal string : 0x38
After converting 56 to octal string : 0o70

Python Type conversion using tuple(), set(), list()


tuple(): This function is used to convert to a tuple.
set(): This function returns the type after converting to set.
list(): This function is used to convert any data type to a list type.

# initializing string
s = 'geeks'

# printing string converting to tuple


c = tuple(s)
print ("After converting string to tuple : ",end="")
print (c)

# printing string converting to set


c = set(s)
print ("After converting string to set : ",end="")
print (c)

# printing string converting to list


c = list(s)
print ("After converting string to list : ",end="")
print (c)

Output:
After converting string to tuple : ('g', 'e', 'e', 'k', 's')
After converting string to set : {'k', 'e', 's', 'g'}
After converting string to list : ['g', 'e', 'e', 'k', 's']
Python code to demonstrate Type conversion using dict(), complex(), str()
dict(): This function is used to convert a tuple of order (key, value) into a dictionary.
str(): Used to convert an integer into a string.
complex(real,imag) : This function converts real numbers to complex(real,imag) number.

# initializing integers
a = 1
b = 2

# initializing tuple
tup = (('a', 1) ,('f', 2), ('g', 3))

# printing integer converting to complex number


c = complex(1,2)
print ("After converting integer to complex number : ",end="")
print (c)

# printing integer converting to string


c = str(a)
print ("After converting integer to string : ",end="")
print (c)

# printing tuple converting to expression dictionary


c = dict(tup)
print ("After converting tuple to dictionary : ",end="")
print (c)

Output:
After converting integer to complex number : (1+2j)
After converting integer to string : 1
After converting tuple to dictionary : {'a': 1, 'f': 2, 'g': 3}

Passing function to function in Python


A function can take multiple arguments, these arguments can be objects, variables(of same or different data
types) and functions. Python functions are first class objects. In the example below, a function is assigned to
a variable. This assignment doesn’t call the function. It takes the function object referenced by shout and
creates a second name pointing to it,

# Python program to illustrate functions


# can be treated as objects
def shout(text):
return text.upper()

print(shout('Hello'))

yell = shout

print(yell('Hello'))

Output:
HELLO
HELLO
Higher Order Functions
Because functions are objects we can pass them as arguments to other functions. Functions that can accept
other functions as arguments are also called higher-order functions. In the example below, a function greet is
created which takes a function as an argument.

# Python program to illustrate functions


# can be passed as arguments to other functions
def shout(text):
return text.upper()

def whisper(text):
return text.lower()

def greet(func):
# storing the function in a variable
greeting = func("Hi, I am created by a function passed as an argument.")
print(greeting)

greet(shout)
greet(whisper)

Output
HI, I AM CREATED BY A FUNCTION PASSED AS AN ARGUMENT.
hi, i am created by a function passed as an argument.

Wrapper function
Wrapper function or decorator allows us to wrap another function in order to extend the behavior of the
wrapped function, without permanently modifying it. In Decorators, functions are taken as the argument into
another function and then called inside the wrapper function.
# defining a decorator
def hello_decorator(func):

# inner1 is a Wrapper function in


# which the argument is called

# inner function can access the outer local


# functions like in this case "func"
def inner1():
print("Hello, this is before function execution")

# calling the actual function now


# inside the wrapper function.
func()

print("This is after function execution")

return inner1

# defining a function, to be called inside wrapper


def function_to_be_used():
print("This is inside the function !!")
# passing 'function_to_be_used' inside the
# decorator to control its behavior
function_to_be_used = hello_decorator(function_to_be_used)

# calling the function


function_to_be_used()

Output:
Hello, this is before function execution
This is inside the function !!
This is after function execution

Lambda wrapper function


In Python, anonymous function means that a function is without a name. As we already know
that def keyword is used to define the normal functions and the lambda keyword is used to create anonymous
functions. This function can have any number of arguments but only one expression, which is evaluated and
returned. Lambda function can also have another function as an argument. The below example shows a
basic lambda function where another lambda function is passed as an argument.

# Defining lambda function


square = lambda x:x * x

# Defining lambda function


# and passing function as an argument
cube = lambda func:func**3

print("square of 2 is :"+str(square(2)))
print("\nThe cube of "+str(square(2))+" is " +str(cube(square(2))))

utput:
square of 2 is :4

The cube of 4 is 64
Python - Modules
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

def print_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 themodule
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 currentnamespace. The
from...import has the following syntax −

from modname 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 introducesthe 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 thefollowing
import statement −

from modname 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 followingsequences −

The current directory.

If the module isn't found, Python then searches each directory in the shell variablePYTHONPATH.
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.

The PYTHONPATH Variable


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
def AddMoney():
# Uncomment the following line to fix the code:
# global Money
Money = Money + 1

print Money
AddMoney() print
Money

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 −

Live Demo
#!/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.

The globals() and locals() Functions


The globals() and locals() functions can be used to return the names in the global and local
namespaces depending on the location from where they are called.

If locals() is called from within a function, it will return all the names that can be accessed locallyfrom
that function.
If globals() is called from within a function, it will return all the names that can be accessed globally from that
function.

The return type of both these functions is dictionary. Therefore, names can be extracted using the keys()
function.

The reload() Function


When the module is imported into a script, the code in the top-level portion of a module is executed only once.

Therefore, if you want to reexecute the top-level code in a module, you can use the reload()function.
The reload() function imports a previously imported module again. The syntax of the reload() function is this

reload(module_name)

Here, module_name is the name of the module you want to reload and not the string containing the module
name. For example, to reload hello module, do the following −

reload(hello)

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 from


Isdn 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.

Python sys Module

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.
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 is used for standard input. It internally calls the input()
method. It, also, automatically adds ‘\n’ after each sentence.
3
Python math Module
Python has a built-in module that you can use for mathematical tasks.

The math module has a set of methods and constants.

Math Methods
Method Description

math.acos() Returns the arc cosine of a number

math.acosh() Returns the inverse hyperbolic cosine of a number

math.asin() Returns the arc sine of a number

math.asinh() Returns the inverse hyperbolic sine of a number

math.atan() Returns the arc tangent of a number in radians

math.atan2() Returns the arc tangent of y/x in radians

math.atanh() Returns the inverse hyperbolic tangent of a number

math.ceil() Rounds a number up to the nearest integer

math.comb() Returns the number of ways to choose k items from n items without repetition and order

math.copysign() Returns a float consisting of the value of the first parameter and the sign of the second parameter

math.cos() Returns the cosine of a number

math.cosh() Returns the hyperbolic cosine of a number

math.degrees() Converts an angle from radians to degrees

math.dist() Returns the Euclidean distance between two points (p and q), where p and q are the coordinates of
that point

math.erf() Returns the error function of a number

math.erfc() Returns the complementary error function of a number

math.exp() Returns E raised to the power of x

math.expm1() Returns Ex - 1

math.fabs() Returns the absolute value of a number

math.factorial() Returns the factorial of a number

math.floor() Rounds a number down to the nearest integer

math.fmod() Returns the remainder of x/y

math.frexp() Returns the mantissa and the exponent, of a specified number

math.fsum() Returns the sum of all items in any iterable (tuples, arrays, lists, etc.)

math.gamma() Returns the gamma function at x

math.gcd() Returns the greatest common divisor of two integers

math.hypot() Returns the Euclidean norm

math.isclose() Checks whether two values are close to each other, or not
math.isfinite() Checks whether a number is finite or not

math.isinf() Checks whether a number is infinite or not

math.isnan() Checks whether a value is NaN (not a number) or not

math.isqrt() Rounds a square root number downwards to the nearest integer

math.ldexp() Returns the inverse of math.frexp() which is x * (2**i) of the given numbers x and i

math.lgamma() Returns the log gamma value of x

math.log() Returns the natural logarithm of a number, or the logarithm of number to base

math.log10() Returns the base-10 logarithm of x

math.log1p() Returns the natural logarithm of 1+x

math.log2() Returns the base-2 logarithm of x

math.perm() Returns the number of ways to choose k items from n items with order and without repetition

math.pow() Returns the value of x to the power of y

math.prod() Returns the product of all the elements in an iterable

math.radians() Converts a degree value into radians

math.remainder() Returns the closest value that can make numerator completely divisible by the denominator

math.sin() Returns the sine of a number

math.sinh() Returns the hyperbolic sine of a number

math.sqrt() Returns the square root of a number

math.tan() Returns the tangent of a number

math.tanh() Returns the hyperbolic tangent of a number

math.trunc() Returns the truncated integer parts of a number

Python Time Module


Python time module allows to work with time in Python. It allows functionality like getting the current time, pausing the
Program from executing, etc. So before starting with this module we need to import it.

Importing time module


The time module comes with Python’s standard utility module, so there is no need to install it externally. We can simply
import it using the import statement.

import time

What is epoch?
The epoch is the point where the time starts and is platform-dependent. On Windows and most Unix systems, the epoch is
January 1, 1970, 00:00:00 (UTC), and leap seconds are not counted towards the time in seconds since the epoch. To check
what the epoch is on a given platform we can use time.gmtime(0).

import time

print(time.gmtime(0))
Output:
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1,
tm_isdst=0)

ex:-
import time

curr = time.time()
print("Current time in seconds since epoch =", curr)

output:-
Current time in seconds since epoch = 1627908387.764925

Getting time string from seconds


time.ctime() function returns a 24 character time string but takes seconds as argument and computes time till mentioned
seconds. If no argument is passed, time is calculated till the present.
Example: Getting time string from seconds

import time

# getting current time by passing


# the number of seconds since epoch
curr = time.ctime(1627908313.717886)
print("Current time:", curr)

Output
Current time: Mon Aug 2 12:45:13 2021

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy