0% found this document useful (0 votes)
10 views35 pages

Python 1-6-1

The document outlines experiments focused on Python programming, covering input/output methods, operators, data types, and control statements. It includes theoretical explanations, rules for identifiers, comments, variables, type conversion, and various built-in functions. Each experiment concludes with practical programming tasks to reinforce the concepts learned.

Uploaded by

Diksha Mirgal
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)
10 views35 pages

Python 1-6-1

The document outlines experiments focused on Python programming, covering input/output methods, operators, data types, and control statements. It includes theoretical explanations, rules for identifiers, comments, variables, type conversion, and various built-in functions. Each experiment concludes with practical programming tasks to reinforce the concepts learned.

Uploaded by

Diksha Mirgal
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/ 35

`

EXPERIMENT NO - 01

Date of Performance :

Date of Submission :

AIM: To study basics of input/output methods and operators in python.

SOFTWARE REQUIREMENT: Python

THEORY:

Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is


designed to be highly readable. It uses English keywords frequently where as other languages use
punctuation, and it has fewer syntactical constructions than otherlanguages.

Python Keywords
Keywords are the reserved words in Python. We cannot use a keyword as a variable name, function
name or any other identifier. They are used to define the syntax and structure of the Python
language. In Python, keywords are case sensitive.

Keywords in Python
False Class finally Is return
None Continue for lambda try
True Def from nonlocal while
and Del global not with
as elif if or yield
assert else import pass
break except in raise

Python Identifiers
An identifier is a name given to entities like class, functions, variables, etc. It helps to
differentiate one entity from another.
Rules for writing identifiers
1. Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0
to 9) or an underscore _. Names like myClass, var_1 and print_this_to_screen, all
are valid example.
2. An identifier cannot start with a digit. 1variable is invalid, but variable1 is perfectly fine.
3. Keywords cannot be used as identifiers.
`

Python Comments
In Python, the hash (#) symbol to start writing a comment. It extends up to the newline character.
Comments are for programmers for better understanding of a program. Python Interpreter ignores
comment.

Multi-line comments
If we have comments that extend multiple lines, one way of doing it is to use hash (#) in the
beginning of each line. For example: Another way of doing this is to use triple quotes, either ''' or
""".

Python Variables
A variable is a named location used to store data in the memory. It is helpful to think of variables
as a container that holds data which can be changed later throughout programming. Rules and
Naming Convention for Variables and constants
1. Constant and variable names should have a combination of letters in lowercase (a to z) or
uppercase (A to Z) or digits (0 to 9) or an underscore (_). For example:
2. snake_case
3. MACRO_CASE
4. camelCase
5. CapWords

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.
1. Implicit Type Conversion
2. 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.

Explicit Type Conversion:


In Explicit Type Conversion, users convert the data type of an object to required data type.
Functions like int(), float(), str(), etc to perform explicit type conversion. This type
conversion is also called typecasting because the user casts (change) the data type of the objects.
Syntax :
(required_datatype)(expression)
`

Python Input, Output


Python provides numerous built-in functions that are readily available at the Python prompt .Some
of the functions like input() and print() are widely used for standard input and output
operations respectively. the print() function to output data to the standard output device (screen).
To allow flexibility to take the input from the user. In Python, we have the input() function
Operators
Operators are special symbols in Python that carry out arithmetic or logical computation. The
value that the operator operates on is called the operand.

Arithmetic operators
Arithmetic operators in Python
Operator Meaning Example
x + y +2
+ Add two operands or unary plus

x - y -2
- Subtract right operand from the left or unary minus

* Multiply two operands x*y


/ Divide left operand by the right one (always results into float) x/y
x % y (remainder of
% Modulus - remainder of the division of left operand by the right x/y)
Floor division - division that results into whole number adjusted to
// the left in the number line x // y

x**y (x to
** Exponent - left operand raised to the power of right the power y)

Logical operators

Logical operators in Python


Operator Meaning Example
And True if both the operands are true x and y
Or True if either of the operands is true x or y
Not True if operand is false (complements the operand) not x
`

Comparison Operators
Comparison operators in Python
Operator Meaning Example
> Greater than - True if left operand is greater than the right x>y
< Less than - True if left operand is less than the right x<y
== Equal to - True if both operands are equal x == y
!= Not equal to - True if operands are not equal x != y
Greater than or equal to - True if left operand is greater than
>= or equal to the right x >= y

Less than or equal to - True if left operand is less than or


<= equal to the right x <= y

Membership operators

Operator Meaning Example


In True if value/variable is found in the sequence 5 in x
not in True if value/variable is not found in the sequence 5 not in x

INPUT/OUTPUT

• Write a python program to input student details and display welcome message to newly
added student record

Diksha

63

Diksha
`

• Write a python Program to perform arithmetic operations on any given inputs

• Write a python Program for Password Length Checker

diksha@123

CONCLUSION: Thus, studied basic input/output methods and operators in python and successfully
implemented python programs for the same.

SIGN AND REMARK:

R1 R2 R3 R4 Total Signature
(3Marks) (3Marks) (3 Marks) (1 Mark) (10
Marks)
`

EXPERIMENT NO - 02
Date of Performance :

Date of Submission :

AIM: To study methods of python data types like string, list, dictionary, tuple and set
THEORY:
Data types:
The data stored in memory can be of many types. For example, a person's age is stored as a numeric value
and his or her address is stored as alphanumeric characters. Python has various standard data types that
are used to define the operations possible on them and the storage method for each of them.

Built-in Data Types

Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:

Text Type: str


Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: Dict
Set Types: Set
Boolean Type: Bool

Numbers
Number data types store numeric values. Number objects are created when you assign a value to them.

Strings
Strings in Python are identified as a contiguous set of characters represented in the quotation marks

String Methods

Python has a set of built-in methods that you can use on strings.

Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
`

count() Returns the number of times a specified value occurs in a string


encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
expandtabs() Sets the tab size of the string
Searches the string for a specified value and returns the position of where it
find()
was found
format() Formats specified values in a string
format_map() Formats specified values in a string
Searches the string for a specified value and returns the position of where it
index()
was found
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
isspace() Returns True if all characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
join() Joins the elements of an iterable to the end of the string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in translations
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified value
Searches the string for a specified value and returns the last position of
rfind()
where it was found
Searches the string for a specified value and returns the last position of
rindex()
where it was found
rjust() Returns a right justified version of the string
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator, and returns a list
`

splitlines() Splits the string at line breaks and returns a list


startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case
translate() Returns a translated string
upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at the beginning

List
A list is a collection which is ordered and changeable. In Python lists are written with square brackets.
List Methods
Method Description

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

extend() Add the elements of a list (or any iterable), to the end of the current list

index() Returns the index of the first element with the specified value

insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list


`

Tuple
A tuple is a collection which is ordered and unchangeable

Tuple Methods
Method Description

count() Returns the number of times a specified value occurs in a tuple

Searches the tuple for a specified value and returns the position of where
index()
it was found

Set
A set is a collection which is unordered and unindexed.

Set Methods

Method Description
add() Adds an element to the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
difference() Returns a set containing the difference between two or more sets
Removes the items in this set that are also included in another, specified
difference_update()
set
discard() Remove the specified item
intersection() Returns a set, that is the intersection of two other sets
Removes the items in this set that are not present in other, specified
intersection_update()
set(s)
isdisjoint() Returns whether two sets have a intersection or not
issubset() Returns whether another set contains this set or not
issuperset() Returns whether this set contains another set or not
pop() Removes an element from the set
remove() Removes the specified element
symmetric_difference() Returns a set with the symmetric differences of two sets
symmetric_difference_update() inserts the symmetric differences from this set and another
union() Return a set containing the union of sets
update() Update the set with the union of this set and others
`

Dictionary
A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are
written with curly brackets, and they have keys and values.

Method Description

clear() Removes all the elements from the dictionary

copy() Returns a copy of the dictionary

fromkeys() Returns a dictionary with the specified keys and value

get() Returns the value of the specified key

items() Returns a list containing a tuple for each key value pair

keys() Returns a list containing the dictionary's keys

pop() Removes the element with the specified key

popitem() Removes the last inserted key-value pair

Returns the value of the specified key. If the key does not exist: insert the key,
setdefault()
with the specified value

update() Updates the dictionary with the specified key-value pairs

values() Returns a list of all the values in the dictionary


`

Create a menu driven python program to study various methods associated to


datatypes string, list, dictionary, set and tuple.

INPUT
`

zkre
`

OUTPUT
`
\

XYZW

‘XYZW’

‘XYZW’

‘XYZW’
`

CONCLUSION: Thus, we have studied different methods of python data types like list, tuple, dictionary, etc.
Also, we have implemented these datatypes in a python program successfully.

SIGN AND REMARK:

R1 R2 R3 R4 Total Signature

(3 Marks) (3 Marks) (3 Marks) (1 Mark) (10 Marks)


`

EXPERIMENT NO - 03
Date of Performance:

Date of Submission:

AIM: To study loops and control statements in python


THEORY:
Control statements:
Decision making is anticipation of conditions occurring while execution of the program and
specifying actions taken according to the conditions.

Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcome.
You need to determine which action to take and which statements to execute if outcome is TRUE
or FALSE otherwise.

Sr.No. Statement & Description

1 if statements

An if statement consists of a boolean expression followed by one or more statements.

2 if...else statements
An if statement can be followed by an optional else statement, which executes when the
boolean expression is FALSE.

3 nested if statements
You can use one if or else if statement inside another if or else ifstatement(s).
`

A loop statement allows us to execute a statement or group of statements multiple times.

Sr.No. Loop Type & Description

1 while loopRepeats a statement or group of statements while a given condition is TRUE.


It tests the condition before executing the loop body.
2 for loop
Executes a sequence of statements multiple times and abbreviates the code that manages
the loopvariable.
3 nested loops
You can use one or more loop inside any another while, for or do..while loop.

Loop Control Statements

Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed.
Python supports the following control statements.

Sr.No. Control Statement & Description

1 break statement
Terminates the loop statement and transfers execution to the statement immediately following theloop.

2 continue statement
Causes the loop to skip the remainder of its body and immediately retest its condition prior to

reiterating.

3 pass statement
The pass statement in Python is used when a statement is required syntactically but you do not want
any command or code to execute.
`

INPUT/OUTPUT

● Write a python program that finds the Fibonacci series from 0 to 20

● Write a python program that finds duplicates from the list [`a`,`b`,‟c`,`a`,`a`,`b`,`d`]
`

● Write a python program that reads alphabet and print desired output.
Alpahbet = [
[1,0,0,0,0,0,1],
[1,0,0,0,0,0,1],
[1,1,1,1,1,1,1],
[1,0,0,0,0,0,1],
[1,0,0,0,0,0,1]]

CONCLUSION: Thus, we have studied and implemented control structures and decision making
instructions in python.

SIGN AND REMARK:

R1 R2 R3 R4 Total Signature
(3 Marks) (3 Marks) (3 Marks) (1 Mark) (10
Marks)
`

EXPERIMENT NO - 04
Date of Performance :
Date of Submission :

AIM: Creating functions, classes, objects and inheritance in python

THEORY:
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.
Python gives you many built- in functions like print(), etc. but you can also create 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 a
function 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
also define parameters inside theseparentheses.
● The first statement of a function can be an optional statement - the documentation string of
the function or docstring.
● The code block within every function starts with a colon (:) and isindented.

● The statement return [expression] exits a function, optionally passing back an expression to
the caller. A return statement with no arguments is the same as returnNone.
Syntax def functionname( parameters ):
"function_docstring" function_suite return [expression]
EXAMPLE def printme( str ):
"This prints a passed string into this function" print str return
Calling a Function
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() 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") 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.
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
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.
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.
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 non-keyword
variable arguments. This tuple remains empty if no additional arguments are specified during the
function call.
`

Python class and objects:


Creating Classes
The class statement creates a new class definition. The name of the class immediately follows the
keyword class followed by a colon as follows– class ClassName:
'Optional class documentation string' class_suite
● The class has a documentation string, which can be accessed via ClassName. doc.
● The class_suite consists of all the component statements defining class members, data
attributes and functions

Create instance object


To create instances of a class, you call the class using class name and pass in whatever arguments
itsinit methodaccepts.
"This would create first object of Employee class" emp1 = Employee("Zara", 2000)
"This would create second object of Employee class" emp2 = Employee("Manni", 5000)

Accessing Attributes
You access the object's attributes using the dot operator with object. Class variable would be
accessed using class name as follows –
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount

Built-In Class Attributes


Every Python class keeps following built-in attributes and they can be accessed using dot
operator like any other attribute − ● dict − Dictionary containing the class'snamespace.
● doc − Class documentation string or none, ifundefined.
● name − Classname.
● module− Module name in which the class is defined. This attribute is " main " in
interactive mode.
● bases − A possibly empty tuple containing the base classes, in the order of their occurrence
in the base classlist.
`

INPUT/OUTPUT

● Write a python program that accepts two strings as input and find the string with
max length

Diksha
Miragal
Miragal

● Write a python program to print dictionary where keys are no’s between 1
and 20(both included) & values are square of keys
`

● Write a python program to implement Object Oriented Programming concept like


Classes, encapsulation, inheritance and multiple inheritance

CONCLUSION: Thus we have implemented object-oriented features in python.

SIGN AND REMARK:

R1 R2 R3 R4 Total Signature
(3 Marks) (3 Marks) (3 Marks) (1 Mark) (10
Marks)
EXPERIMENT NO - 05
Date of Performance:

Date of Submission :

AIM: To Explore files and directories using python

THEORY:
File handling
When working with Python, no need to import a library in order to read and write files. It‟s handled
natively in the language.

Opening and Closing Files


Python provides basic functions and methods necessary to manipulate files by default. You can do
most of the file manipulation using a fileobject.
The open Function
Before you can read or write a file, you have to open it using Python's built-in open() function. This
function creates a file object, which would be utilized to call other support methods associated with
it.
Syntax
fileobject=open(file_name[,access_mode][,buffering])
Here are parameter details −

● file_name − The file_name argument is a string value that


contains the name of the file that you want to access.
● access_mode − The access_mode determines the mode in which the file has to be opened,

i.e., read, write, append, etc. A complete list of possible values is given below in the table. This

is

optional parameter and the default file access mode is read(r).


● buffering − If the buffering value is set to 0, no buffering takes place. If the buffering value is

1, line buffering is performed while accessing a file. If you specify the buffering value as an

integer greater than 1, then buffering action is performed with the indicated buffer size.
If negative, the buffer size is the system default(default behavior).

List of the different modes of opening a file −


`

Sr.No Modes &


. Descriptio
n
1 r
Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the
default mode.

2 rb
Opens a file for reading only in binary format. The file pointer is placed at the beginning of the
file. This is the default mode.
3 r+
Opens a file for both reading and writing. The file pointer placed at the beginning of the file.
4 rb+
Opens a file for both reading and writing in binary format. The file pointer placed at the
beginning of the file.

5 w
Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist,
creates a new file for writing.

6 wb
Opens a file for writing only in binary format. Overwrites the file if the file exists.
If the file does not exist, creates a new file for writing.
7 w+
Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file
does not exist, creates a new file for reading and writing.
8 w+
Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file
does not exist, creates a new file for reading and writing.
9 wb+
Opens a file for both writing and reading in binary format. Overwrites the existing file if the file
exists. If the file does not exist, creates a new file for reading and writing.
10 a
Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the
file is in the append mode. If the file does not exist, it creates a new file for writing.
11 ab

Opens a file for appending in binary format. The file pointer is at the end of the file if the file
exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for
writing.
`

12 a+
Opens a file for both appending and reading. The file pointer is at the end of the file if the file
exists. The file opens in the append mode. If the file does not exist, it creates a new file for
reading and writing.
13 ab+

Opens a file for both appending and reading in binary format. The file pointer is at the end of
the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a
new file for reading and writing.

The file Object Attributes


Once a file is opened and you have one file object, you can get various information related to that
file. Here is a list of all attributes related to file object −
Sr.No. Attribute & Description

le.closed Returns true if file is closed, false otherwise.


1
le.mode Returns access mode with which file wasopened.
2
le.name Returns name of the file.
3
le.softspaceReturns false if space explicitly required with print, true otherwise.
4

The close() Method


The close() method of a file object flushes any unwritten information and closes the file object,
after which no more writing can be done.
Python automatically closes a file when the reference object of a file is reassigned to another file.
It is a good practice to use the close() method to close a file. Syntax

fileObject.close();
Reading and Writing Files
The file object provides a set of access methods to make our lives easier. We would see how to
use read() and write() methods to read and writefiles.
The write() Method
The write() method writes any string to an open file. It is important to note that Python strings
can have binary data and not just text.
The write() method does not add a newline character ('\n') to the end of the string − Syntax
`

fileObject.write(string);
Here, passed parameter is the content to be written into the opened file.
The read() Method
The read() method reads a string from an open file. It is important to note that Python strings can
have binary data. apart from text data.
Syntax

Here, passed parameter is the number of bytes to be read from the opened file. This method starts
reading from the beginning of the file and if count is missing, then it tries to read as much as
possible, maybe until the end of file.

File Positions
The tell() method tells you the current position within the file; in other words, the next read or write
will occur at that many bytes from the beginning of the file.
The seek(offset[, from]) method changes the current file position. The offsetargument indicates the
number of bytes to be moved. The from argument specifies the reference position from where the
bytes are to be moved.
If from is set to 0, it means use the beginning of the file as the reference position and 1 means use
the current position as the reference position and if it is set to 2 then the end of the file would be
taken as the reference position.
Renaming and Deleting Files
The rename() Method
The rename() method takes two arguments, the current filename and the new filename. Syntax

os.rename(current_file_name, new_file_name)
The remove() Method
You can use the remove() method to delete files by supplying the name of the file to be deleted
as the argument.
Syntax
os.remove(file_name)
Directories in Python
All files are contained within various directories, and Python has no problem handling these too.
The os module has several methods that help you create, remove, and changedirectories.
The mkdir() Method
You can use the mkdir() method of the os module to create directories in the current
directory. You need to supply an argument to this method which contains the name of the
directory to be
`

created. Syntax

os.mkdir("newdir")
The chdir() Method
You can use the chdir() method to change the current directory. The chdir() method takes an
argument, which is the name of the directory that you want to make the currentdirectory.
Syntax
os.chdir("newdir")
The getcwd() Method
The getcwd() method displays the current working directory. Syntax

os.getcwd()

The rmdir() method deletes the directory, which is passed as an

argument in the method. Before removing a directory, all the contents in it should be removed.

os.rmdir('dirname')
Syntax
Exampl
e
File & Directory Related Methods
There are three important sources, which provide a wide range of utility methods to handle and
manipulate files & directories on Windows and Unix operating systems. They are as follows ●

File Object Methods: The file object provides functions to manipulatefiles. ● OS Object Methods:
This provides methods to process files as well asdirectories.
`

INPUT/OUTPUT

● Python program to append data to existing file and then display the entire file
`

● Python program to count number of lines, words and characters in a file.


`

● Python program to display file available in current directory

CONCLUSION: Thus we have explored files and directories in python and have executed the programs
successfully

SIGN AND REMARK:

R1 R2 R3 R4 Total Signature
(3 Marks) (3 Marks) (3 Marks) (1 Mark) (10
Marks)
`

EXPERIMENT NO - 06
Date of Performance :

Date of Submission :

AIM: To send emails using python modules and packages


THEORY:

Python modules and Python packages, two mechanisms that facilitate modular programming.

Modular programming refers to the process of breaking a large, unwieldy programming task into
separate, smaller, more manageable subtasks or modules. Individual modules can then be cobbled
together like building blocks to create a larger application.

Python Modules

There are actually three different ways to define a module in Python:

1. A module can be written in Python itself.


2. A module can be written in C and loaded dynamically at run-time, like the re (regular
expression) module.
3. A built-in module is intrinsically contained in the interpreter, like the itertools module.

A module‟s contents are accessed the same way in all three cases: with the import statement.

Create a Module
To create a module just save the code you want in a file with the file extension .py: Example
Save this code in a file named mymodule.py def greeting(name):
print("Hello, " + name)

Use a Module
Now we can use the module we just created, by using the import statement: Example
Import the module named mymodule, and call the greeting function:

import mymodule
mymodule.greeting("Jonathan")

Built-in Modules
There are several built-in modules in Python, which you can import whenever you like. Example
Import and use the platform module: import platform
x = platform.system() print(x)
`

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)
Note: The dir() function can be used on all modules, also the ones you create yourself.
Import From Module
You can choose to import only parts from a module, by using the from keyword.
Example
The module named mymodule has one function and one dictionary: def greeting(name):

print("Hello, " + name)


person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}

Example
Import only the person1 dictionary from the module:
from mymodule import person1

print (person1["age"])

INPUT

(“[email protected]”, “uhgh rhaj fhxx lain”)


`

OUTPUT

Diksha Mirgal < [email protected] >


To: Diksha Mirgal < [email protected] >

CONCLUSION: Thus, we have learnt to send mails in python and hence program has been
executed successfully.

SIGN AND REMARK:

R1 R2 R3 R4 Total Signature
(3 Marks) (3 Marks) (3 Marks) (1 Mark) (10
Marks)

You might also like