0% found this document useful (0 votes)
6 views18 pages

Python Unit3

The document covers file handling in Python, detailing functions for creating, reading, updating, and deleting files using the open() function with various modes. It also discusses exception handling, including built-in exceptions and user-defined exceptions, along with the syntax for try-except blocks. Additionally, it introduces regular expressions for pattern matching in strings and the principles of object-oriented programming in Python.

Uploaded by

Punam Sindhu
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)
6 views18 pages

Python Unit3

The document covers file handling in Python, detailing functions for creating, reading, updating, and deleting files using the open() function with various modes. It also discusses exception handling, including built-in exceptions and user-defined exceptions, along with the syntax for try-except blocks. Additionally, it introduces regular expressions for pattern matching in strings and the principles of object-oriented programming in Python.

Uploaded by

Punam Sindhu
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

UNIT III

CHAPTER1
FILES

File handling is an important part of any web application.

Python has several functions for creating, reading, updating, and deleting files.

File Handling

The key function for working with files in Python is the open() function.

The open() function takes two parameters; filename, and mode.

There are four different methods (modes) for opening a file:

"r" - Read - Default value. Opens a file for reading, error if the file does not exist

"a" - Append - Opens a file for appending, creates the file if it does not exist

"w" - Write - Opens a file for writing, creates the file if it does not exist

"x" - Create - Creates the specified file, returns an error if the file exists

In addition you can specify if the file should be handled as binary or text mode

"t" - Text - Default value. Text mode

"b" - Binary - Binary mode (e.g. images)

Syntax

To open a file for reading it is enough to specify the name of the file:

f = open("[Link]")

The code above is the same as:

f = open("[Link]", "rt")
Python file open
Open a File on the Server

Assume we have the following file, located in the same folder as Python:

[Link]

Hello! Welcome to [Link]


This file is for testing purposes.
Good Luck!

To open the file, use the built-in open() function.

The open() function returns a file object, which has a read() method for reading the content of the file:
f = open("[Link]", "r")
print([Link]())
Read Only Parts of the File

By default the read() method returns the whole text, but you can also specify how many characters you
want to return:

f = open("[Link]", "r")
Example
Return the 5 first characters of the file:
print([Link](5))

Python File Write


Write to an Existing File
To write to an existing file, you must add a parameter to the open() function:
"a" - Append - will append to the end of the file
"w" - Write - will overwrite any existing content
Example

Open the file "[Link]" and append content to the file:


f = open("[Link]", "a")
[Link]("Now the file has more content!")
[Link]()

#open and read the file after the appending:


f = open("[Link]", "r")
print([Link]())

Example
Open the file "[Link]" and overwrite the content:
f = open("[Link]", "w")
[Link]("Woops! I have deleted the content!")
[Link]()
#open and read the file after the overwriting:
f = open("[Link]", "r")
print([Link]())
Note: the "w" method will overwrite the entire file.

Create a New File

To create a new file in Python, use the open() method, with one of the following parameters:

"x" - Create - will create a file, returns an error if the file exist

"a" - Append - will create a file if the specified file does not exist

"w" - Write - will create a file if the specified file does not exist

Example

Create a file called "[Link]"


f = open("[Link]", "x")

Result: a new empty file is created!

Example
Create a new file if it does not exist:
f = open("[Link]", "w")

DIRECTORIES
Here we will import the OS module to be able to access the methods we will apply.
import os

How to Get Current Python Directory?


To find out which directory in python you are currently in, use the getcwd() method.
[Link]()
Output:
‘C:\\Users\\lifei\\AppData\\Local\\Programs\\Python\\Python36-32’

Cwd is for current working directory in python. This returns the path of the current python directory as
a string in Python.

To get it as a bytes object, we use the method getcwdb().


[Link]()
Output:
b’C:\\Users\\lifei\\AppData\\Local\\Programs\\Python\\Python36-32′ Here, we get two backslashes
instead of one. This is because the first one is to escape the second one since this is a string object.
type([Link]())
<class 'str'>
To render it properly, use the Python method with the print statement.
print([Link]())

Output:
Changing Current Python Directory
To change our current working directories in python, we use the chdir()
method.
This takes one argument- the path to the directory to which to change.
Output:
‘unicodeescape’ code can’t decode bytes in position 2-3: truncated
\UXXXXXXXX escape
But remember that when using backward slashes, it is recommended to escape the backward slashes to
avoid a problem.
Output:

How to Create Python Directory?


We can also create new python directories with the mkdir() method. It takes one argument, that is, the
path of the new python directory to create.

[Link]('Christmas Photos')
[Link]()
Output:
[‘Adobe Photoshop [Link]’, ‘[Link]’, ‘Burn [Link]’, ‘Christmas Photos’, ‘[Link]’,
‘Documents’, ‘Eclipse Cpp [Link]’, ‘Eclipse Java [Link]’, ‘Eclipse Jee [Link]’, ‘For the
[Link]’, ‘Items for [Link]’, ‘Papers’, ‘Remember to [Link]’, ‘Sweet [Link]’,
‘[Link]’, ‘[Link]’, ‘[Link]’]
How to Rename Python Directory?:
To rename directories in python, we use the rename() method. It takes two arguments- the python
directory to rename, and the new name for it.

[Link]('Christmas Photos','Christmas 2017')


[Link]()
Output:
[‘Adobe Photoshop [Link]’, ‘[Link]’, ‘Burn [Link]’, ‘Christmas 2017’, ‘[Link]’,
‘Documents’, ‘Eclipse Cpp [Link]’, ‘Eclipse

CHAPTER 2
Exception Handling

Error in Python can be of two types i.e. Syntax errors and Exceptions. Errors are problems
in a program due to which the program will stop the execution. On the other hand,
exceptions are raised when some internal events occur which change the normal flow of the
program.

Different types of exceptions in python:

In Python, there are several built-in Python exceptions that can be raised when an error
occurs during the execution of a program. Here are some of the most common types of
exceptions in Python:
● SyntaxError: This exception is raised when the interpreter encounters a syntax
error in the code, such as a misspelled keyword, a missing colon, or an
unbalanced parenthesis.
● TypeError: This exception is raised when an operation or function is applied to
an object of the wrong type, such as adding a string to an integer.
● NameError: This exception is raised when a variable or function name is not
found in the current scope.
● IndexError: This exception is raised when an index is out of range for a list,
tuple, or other sequence types.
● KeyError: This exception is raised when a key is not found in a dictionary.
● ValueError: This exception is raised when a function or method is called with an
invalid argument or input, such as trying to convert a string to an integer when the
string does not represent a valid integer.
● AttributeError: This exception is raised when an attribute or method is not
found on an object, such as trying to access a non-existent attribute of a class
instance.
● IOError: This exception is raised when an I/O operation, such as reading or
writing a file, fails due to an input/output error.
● ZeroDivisionError: This exception is raised when an attempt is made to divide a
number by zero.
● ImportError: This exception is raised when an import statement fails to find or
load a module.

These are just a few examples of the many types of exceptions that can occur in Python. It’s
important to handle exceptions properly in your code using try-except blocks or other
error-handling techniques, in order to gracefully handle errors and prevent the program from
crashing.
HANDLING EXCEPTIONS
If you have some suspicious code that may raise an exception, you can defend your program by
placing the suspicious code in a try: block.
After the try: block, include an except: statement, followed by a block of code which handles the
problem as elegantly as possible.
Syntax:
Here is simple syntax of try....except...else blocks:

try:
You do your operations here;
...................... except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
...................... else:

If there is no exception then execute this block.


Here are few important points about the above-mentioned syntax − A single try statement can have
multiple except statements. This is useful when the try block contains statements that may throw
different types of exceptions.
You can also provide a generic except clause, which handles any
exception.
After the except clause(s), you can include an else-clause. The code in the else-block executes if the
code in the try: block does not raise an exception.

Example:
This example opens a file, writes content in the, file and comes out
gracefully because there is no problem at all:
try:
fh = open("testfile", "w")
[Link]("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find file or read data"
else:
print "Written content in the file successfully"
[Link]()
This produces the following result:
Written content in the file successfully

EXCEPTION WITH ARGUMENTS


Using arguments for Exceptions in Python is useful for the following reasons:
It can be used to gain additional information about the error encountered.
As contents of an Argument can vary depending upon different types of Exceptions in Python,
Variables can be supplied to the Exceptions to capture the essence of the encountered errors. Same
error can occur of different causes, Arguments helps us identify the specific cause for an error using
the except clause.
It can also be used to trap multiple exceptions, by using a variable to follow the tuple of
Exceptions.

Arguments in Built-in Exceptions:


The below codes demonstrates use of Argument with Built-in Exceptions:
Example 1:
try:
b = float(100 + 50 / 0)
except Exception as Argument:
print( 'This is the Argument\n', Argument)
Output:
This is the Argument
division by zero
Arguments in User-defined Exceptions:
The below codes demonstrates use of Argument with User-defined
Exceptions:
Example 1:
# create user-defined exception
# derived from super class Exception
class MyError(Exception):
# Constructor or Initializer
def __init__(self, value):
[Link] = value
# __str__ is to print() the value
def __str__(self):
return(repr([Link]))

try:
raise(MyError("Some Error Data"))
# Value of Exception is stored in error
except MyError as Argument:
print('This is the Argument\n', Argument)
Output:
'This is the Argument
'Some Error data'

USER-DEFINED
Creating User-defined Exception
Programmers may name their own exceptions by creating a new exception class. Exceptions need
to be derived from the Exception class, either directly or indirectly. Although not mandatory, most
of the exceptions are named as names that end in “Error” similar to naming of the standard
exceptions in python. For example:

# A python program to create user-defined exception


# class MyError is derived from super class Exception
class MyError(Exception):
# Constructor or Initializer
def __init__(self, value):

[Link] = value
# __str__ is to print() the value
def __str__(self):
return(repr([Link]))

try:
raise(MyError(3*2))
# Value of Exception is stored in error
except MyError as error:
print('A New Exception occured: ',[Link])
Ouput:
('A New Exception occured: ', 6)

CHAPTER 3
REGULAR EXPRESSION
Regular expressions (called REs, or regexes, or regex patterns) are
essentially a tiny, highly specialized programming language embedded
inside Python and made available through the re module. Using this little
language, you specify the rules for the set of possible strings that you want
to match; this set might contain English sentences, or e-mail addresses, or
TeX commands, or anything you like. You can then ask questions such as
“Does this string match the pattern?”, or “Is there a match for the pattern
anywhere in this string?”. You can also use REs to modify a string or to
split it apart in various ways.
CONCEPT OF REGULAR EXPRESSION
You may be familiar with searching for text by pressing ctrl-F and
typing in the words you’re looking for.
Regular expressions go one step further: They allow you to specify a
pattern of text to search for.
Symbol and it’s Meaning:

VARIOUS TYPES OF REGULAR EXPRESSIONS


The "re" package provides several methods to actually perform
queries on an input string. We will see the methods of re in Python:
Note: Based on the regular expressions, Python offers two different
primitive operations. The match method checks for a match only at the
beginning of the string while search checks for a match anywhere in the
string.
[Link](): Finding Pattern in Text:
[Link]() function will search the regular expression pattern and return
the first occurrence. Unlike Python [Link](), it will check all lines of the
input string. The Python [Link]() function returns a match object when
the pattern is found and “null” if the pattern is not found
In order to use search() function, you need to import Python re
module first and then execute the code. The Python [Link]() function
takes the "pattern" and "text" to scan from our main string. The search() function searches the string for
a match, and returns
a Match object if there is a match.
If there is more than one match, only the first occurrence of the
match will be returned:
Example:
Search for the first white-space character in the string:
import re
txt = "The rain in Spain"
x = [Link]("\s", txt)
print("The first white-space character is located in position:", [Link]())
output:
The first white-space character is located in position: 3
9.3.2 The split() Function:
The split() function returns a list where the string has been split at each
match:
Example:
Split at each white-space character:
import re
txt = "The rain in Spain"
x = [Link]("\s", txt)
print(x)
output:
[‘The’,‘rain’,‘in’,‘Spain’]

9.3.3 [Link]():
findall() module is used to search for “all” occurrences that match
a given pattern. In contrast, search () module will only return the first
occurrence that matches the specified pattern. findall () will iterate over all
the lines of the file and will return all non-overlapping matches of pattern
in a single step.
The findall () function returns a list containing all matches
Example:
Print a list of all matches:
import re
txt = "The rain in Spain"
x = [Link]("ai", txt)
print(x)
output:
[‘ai’ , ‘ai’]
For example, here we have a list of e-mail addresses, and we want
all the e-mail addresses to be fetched out from the list, we use the method
[Link]() in Python. It will find all the e-mail addresses from the list.
9.3.4 The Sub () Function:
The sub() function replaces the matches with the text of your choice:
Replace every white-space character with the number 9:
import re
txt = "The rain in Spain"
x = [Link]("\s", "9", txt)
print(x)
output:
The9rain9in9Spain
You can control the number of replacements by specifying
the count parameter:
Example:
Replace the first 2 occurrences:

import re
txt = "The rain in Spain"
x = [Link]("\s", "9", txt, 2)
print(x)
output:
The9rain9inSpain
Match Object

A Match Object is an object containing information about the search and the result.

Note: If there is no match, the value None will be returned, instead of the Match Object.

CHAPTER 4
CLASSES AND OBJECTS

Python is an object-oriented programming language. It allows us to develop applications using Object


Oriented approach. In Python, we can easily create and use classes and objects.
Major principles of object-oriented programming system are given below

Object:
Object is an entity that has state and behavior. It may be anything. It may be physical and logical. For
example: mouse, keyboard, chair, table, pen etc.

Class:
Class can be defined as a collection of objects. It is a logical entity that has some specific attributes and
methods.

Inheritance:
Inheritance is a feature of object-oriented programming. It specifies that one object acquires all the
properties and behaviors of parent object. By using inheritance you can define a new class with a little
or no changes to the existing class. The new class is known as derived class or child class and from
which it inherits the properties is alled base class or parent class.
It provides re-usability of the code.

Polymorphism:
Polymorphism is made by two words "poly" and "morphs". Poly means many and Morphs means form,
shape. It defines that one task can be performed in different ways.

Encapsulation:
Encapsulation is also the feature of object-oriented programming. It is used to restrict access to
methods and variables. In encapsulation, code and data are wrapped together within a single unit from
being modified by accident.

Data Abstraction:
Data abstraction and encapsulation both are often used as synonyms. Both are nearly synonym because
data abstraction is achieved through encapsulation.
Abstraction is used to hide internal details and show only functionalities. Abstracting something means
to give names to things, so that the name captures the core of what a function or a whole program does.
Class:
Class can be defined as a collection of objects. It is a logical entity that has some specific attributes and
methods. For example: if you have an employee class then it should contain an attribute and method i.e.
an email id, name, age, salary etc.

For example: if you have an employee class then it should contain an


attribute and method i.e. an email id, name, age, salary etc.
Syntax:
class ClassName:
<statement-1>
.
.
.<statement-N>

Method:
Method is a function that is associated with an object. In Python, method is not unique to class
instances. Any object type can have methods.
Object:
Object is an entity that has state and behavior. It may be anything. It may be physical and logical. For
example: mouse, keyboard, chair, table, pen
etc.
Everything in Python is an object, and almost everything has attributes and methods. All functions have
a built-in attribute __doc__, which returns the doc string defined in the function source code.
Syntax
class ClassName:
self.instance_variable = value #value specific to instance
class_variable = value #value shared across all class instances
#accessing instance variable
class_instance = ClassName()
class_instance.instance_variable
#accessing class variable
ClassName.class_variable
Example
class Car:
wheels = 4 # class variable
def __init__(self, make):
[Link] = make #instance variable
newCar = Car("Honda")
print ("My new car is a {}".format([Link]))
print ("My car, like all cars, has {%d} wheels".format([Link]))
INHERITANCE
What is Inheritance?
Inheritance is a feature of Object Oriented Programming. It is used to specify that one class will get
most or all of its features from its parent class. It is a very powerful feature which facilitates users to
create a new class with a few or more modification to an existing class.
The new class is called child class or derived class and the main class from which it inherits the
properties is called base class or parent class.
The child class or derived class inherits the features from the parent class, adding new features to it. It
facilitates re-usability of code.

METHOD OVERRIDING
Method overriding is an ability of any object-oriented programming language that allows a subclass or
child class to provide a specific implementation of a method that is already provided by one of its
superclasses or parent classes. When a method in a subclass has the same name, same parameters or
signature and same return type(or sub-type) as a method in its super-class, then the method in the
subclass is said to override the method in the super-class.

class Parent():
# Constructor
def __init__(self):
[Link] = "Inside Parent"
# Parent's show method
def show(self):
print([Link])
# Defining child class
class Child(Parent):
# Constructor
def __init__(self):
[Link] = "Inside Child"
# Child's show method
def show(self):
print([Link])
# Driver's code
obj1 = Parent()
obj2 = Child()
[Link]()
[Link]()
Output:
Inside Parent
Inside Child

DATA ENCAPSULATION
Encapsulation is one of the fundamental concepts in object- oriented programming (OOP). It describes
the idea of wrapping data and the methods that work on data within one unit. This puts restrictions on
accessing variables and methods directly and can prevent the accidental modification of data. To
prevent accidental change, an object’s variable can only be changed by an object’s method. Those types
of variables are known as private variable. A class is an example of encapsulation as it encapsulates all
the data that is member functions, variables, etc.
DATA HIDING
What is Data Hiding?
Data hiding is a part of object-oriented programming, which is generally used to hide the data
information from the user. It includes internal object details such as data members, internal working. It
maintained the data integrity and restricted access to the class member. The main working of data
hiding is that it combines the data and functions into a single unit to conceal data within a class. We
cannot directly access the data from outside the class.
This process is also known as the data encapsulation. It is done by hiding the working information to
user. In the process, we declare class members as private so that no other class can access these data
members. It is accessible only within the class.

Data Hiding in Python:


Python is the most popular programming language as it applies in every technical domain and has a
straightforward syntax and vast libraries. In the official Python documentation, Data hiding isolates the
client from a part of program implementation. Some of the essential members must be hidden from the
user. Programs or modules only reflected how we could use them, but users cannot be familiar with
how the application works. Thus it provides security and avoiding dependency as well.
We can perform data hiding in Python using the __ double underscore before prefix. This makes the
class members private and inaccessible to the other classes.

Example - class CounterClass:


__privateCount = 0
def count(self):
self.__privateCount += 1
print(self.__privateCount)
counter = CounterClass()
[Link]()
[Link]()
print(counter.__privateCount)
Output:
1
2
Traceback (most recent call last):
File "<string>", line 17, in <module>
AttributeError: 'CounterClass' object has no attribute '__privateCount

CHAPTER 5
MATH MODULE
Python math module is defined as the most famous mathematical functions, which includes
trigonometric functions, representation functions, logarithmic functions, etc. Furthermore, it also
defines two mathematical constants, i.e., Pie and Euler number, etc.

Pie (n): It is a well-known mathematical constant and defined as the ratio of circumstance to the
diameter of a circle.
Its value is 3.141592653589793.

Euler's number(e): It is defined as the base of the natural logarithmic,


and its value is 2.718281828459045.
There are different math modules which are given below:
[Link] ()
This method returns the natural logarithm of a given number. It is calculated to the base e.

Example
import math
number = 2e-7 # small value of of x
print('log(fabs(x), base) is :', [Link]([Link](number), 10))

Output:
log(fabs(x), base) is : -6.698970004336019
math.log10()
This method returns base 10 logarithm of the given number and
called the standard logarithm.

Example
import math
x=13 # small value of of x
print('log10(x) is :', math.log10(x))

Output:
log10(x) is : 1.1139433523068367
[Link]()
This method returns a floating-point number after raising e to the given
Number.

Example
import math
number = 5e-2 # small value of of x
print('The given number (x) is :', number)
print('e^x (using exp() function) is :', [Link](number)-1)
Output:
The given number (x) is : 0.05
e^x (using exp() function) is : 0.05127109637602412

Example
import math
number = [Link](10,2)
print("The power of number:",number)
Output:
The power of number: 100.0
[Link](x)
This method returns the floor value of the x. It returns the less than or equal value to x.

Example:
import math
number = [Link](10.25201)
print("The floor value is:",number)

Output:
The floor value is: 10
[Link](x)
This method returns the ceil value of the x. It returns the greater than or equal value to x.

import math
number = [Link](10.25201)
print("The floor value is:",number)
Output:
The floor value is: 11
[Link](x)

This method returns the absolute value of x.


import math
number = [Link](10.001)
print("The floor absolute is:",number)

Output:
The absolute value is: 10.001

number = [Link](7)
print("The factorial of number:",number)

Output:
The factorial of number: 5040
[Link](x)
This method returns the fractional and integer parts of x. It carries the sign of x is float.

Example
import math
number = [Link](44.5)
print("The mod of number:",number)
Output:
The mod of number: (0.5, 44.0)

RANDOM MODULE

The Python random module functions depend on a pseudo- random number generator function
random(), which generates the float number between 0.0 and 1.0.
There are different types of functions used in a random module which is given below:
[Link]()
This function generates a random float number between 0.0 and 1.0. [Link]()
This function returns a random integer between the specified integers.
[Link]()
This function returns a randomly selected element from a non-empty sequence.

Example
# importing "random” module.
import random
# We are using the choice() function to generate a random number from the given list of numbers.
print ("The random number from list is : ",end="")
print ([Link]([50, 41, 84, 40, 31]))

Output:
The random number from list is : 84

[Link]()
This function randomly reorders the elements in the list.
[Link](beg,end,step)
This function is used to generate a number within the range specified in its argument. It accepts
three arguments, beginning number, last number, and step, which is used to skip a number in the
range.

Consider the following example.


# We are using the randrange() function to generate in range from 100 to 500. The last parameter
10 is step size to skip ten numbers when selecting.
import random
print ("A random number from range is : ",end="")
print ([Link](100, 500, 10))

Output:
A random number from range is : 290
[Link]()
This function is used to apply on the particular random number with the seed argument. It returns
the mapper value.
Consider the following example.
import random
print("The random number between 0 and 1 is : ", end="")
print([Link]())
# using seed() to seed a random number
[Link](4)
Output:
The random number between 0 and 1 is : 0.4405576668981033

TIME MODULE
Python has defined a module, “time” which allows us to handle various operations regarding time,
its conversions and representations, which find its use in various applications in life. The beginning
of time started measuring from 1 January, 12:00 am, 1970 and this very time is termed as “epoch”
in Python.

Operations on Time:
1. time (): - This function is used to count the number of seconds elapsed since the epoch.
2. gmtime(sec) :- This function returns a structure with 9 values each representing a time attribute
in sequence. It converts seconds into time attributes(days, years, months etc.) till specified seconds
from epoch. If no seconds are mentioned, time is calculated till present. The structure attribute
table is given below.
Index Attributes Values
0 tm_year 2008
1 tm_mon 1 to 12
2 tm_mday 1 to 31
3 tm_hour 0 to 23
4 tm_min 0 to 59
5 tm_sec 0 to 61 (60 or 61 are leap- seconds)
6 tm_wday 0 to 6
7 tm_yday 1 to 366
8 tm_isdst -1, 0, 1 where -1 means Library
determines DST

# Python code to demonstrate the working of


# time() and gmtime()
# importing "time" module for time operations
import time
# using time() to display time since epoch
print ("Seconds elapsed since the epoch are : ",end="")
print ([Link]())
# using gmtime() to return the time attribute structure
print ("Time calculated acc. to given seconds is : ")
print ([Link]())

Output:
Seconds elapsed since the epoch are : 1470121951.9536893
Time calculated acc. to given seconds is :
time.struct_time(tm_year=2016, tm_mon=8, tm_mday=2,
tm_hour=7, tm_min=12, tm_sec=31, tm_wday=1,
tm_yday=215, tm_isdst=0)

3. asctime(“time”) :- This function takes a time attributed string


produced by gmtime() and returns a 24 character string denoting
time.
4. ctime(sec) :- This 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 present.
# Python code to demonstrate the working of
# asctime() and ctime()
# importing "time" module for time operations
import time
# initializing time using gmtime()
ti = [Link]()
# using asctime() to display time acc. to time mentioned
print ("Time calculated using asctime() is : ",end="")
print ([Link](ti))
# using ctime() to display time string using seconds
print ("Time calculated using ctime() is : ", end="")
print ([Link]())
Output:
Time calculated using asctime() is : Tue Aug 2 07:47:02 2016
Time calculated using ctime() is : Tue Aug 2 07:47:02 2016

5. sleep(sec) :- This method is used to halt the program


execution for the time specified in the arguments.

Python
# Python code to demonstrate the working of
# sleep()
# importing "time" module for time operations
import time
# using ctime() to show present time
print ("Start Execution : ",end="")
print ([Link]())
# using sleep() to hault execution
[Link](4)
# using ctime() to show present time
print ("Stop Execution : ",end="")
print ([Link]())

# Python code to demonstrate the working of


# sleep()
# importing "time" module for time operations
import time
# using ctime() to show present time
print ("Start Execution : ",end="")
print ([Link]())
# using sleep() to hault execution
[Link](4)
# using ctime() to show present time
print ("Stop Execution”)

Output:
Start Execution : Tue Aug 2 07:59:03 2016
Stop Execution : Tue Aug 2 07:59:07 2016

You might also like