Ql. Define Python?
Ans : Python is a general purpose interpreted, in-
teractive, object - oriented and high level pro-
gramming language. Itwas created by Guldo
Van Rossum during 1985 - 1990,
Q2. What is the advantage of python?
Ans : Advantages of python are as follows
* Very simple language to learn
* tis portable, expandable and embeddable.
* Ithas huge community which provides a lot
ipport and libraries for the language.
. What are the library support in python?
Ans : a) Sockets
b) Mysqldb
c) Numpy
d) Pandas
e) Open CV
{) Thinter
) Requests
What are the features of Python lan-
guage?
+ Features of python language are as follows
Easy
.. Expressive
. Free and open source
|. High level
Portable
Interpreted
Object oriented etc.,
Q5. Write the syntax for creating a
in python? ;
‘Ans : 'n Python a function is defined using d
word.
Syntax:
def my_function ( ):
print (“Hello from a function”)
Q6.
parameter value in python?
2 The following example shows the usag
default parameters value in python.
def my function (County= “Norway’
Prinit(“1 am from “ + County)
my function ("Sweden")
my_function (“India”)
my_funetion ( )
my_function (“Brazil”)
What are the basic data types of,
‘The basic data types of python are
. Integers
Ans
Q7.
Ans :
. Floating point numbers
Complex numbers
Strings
. Boolean type
DOR were
Built - in functions
Q8. What is data structure in Python?
Ans :terme a ————
what are the built in data structures of of
OQ ython?
= The built - in data structures of python are
1, List
Tuple
Dictionary
_ Program to add two number in python as
follows,
numl = 15
num2 = 63
# Add two numbers
Sum=float (numl) + float (num2)
2 Display the sum
Print (“The sum of {0} and {1} is {2};
format (num1, num2, sum)
Qi. What is the use of JSON in python?
Ans: Python has a JSON module that will help
converting data structure to JSON strings. It
is mainly used to convert the python dictio-
nary above into a JSON string that can be
uritten into a file.3.30
SS Qu
3-1 Lancuace FEA
Qi.
Ans:
TURES OF PYTHON
What is Pyt
thon? Explain brie
Python: oe
Python is a
ive cb 2l- Purpose interpreted, in-
(eractive, object-oriented, wat high level bro
gramming langua,
ge. It was
van Rossum during 1936: ated by Guido
Basic Syntax of Python .
#Python Baise syntax-exam
Print (“Hello
tax")
History of ‘Python language :
Python, languages is, derived from many other
Popular languages, Som:
7 of the
are given in following ist °° andueges
+ ABC
-¢
+ C++
+ Algol-68,
+ Modula 3
+ SmallTalk,
+ Unix shell
+ other scripting languages
——atherscripting languages.
Q2._ Explain the language features of python?
Ans: Language features of Python :
Python features include the following
1. Easy-to-leamm : Python has few keywords,
simple structure, and a clearly defined syn.
tax. This allows the student to pick up the lan-
guage quickly. ‘a
2. Easy-to-read : Python code is more clearly
defined and visible to the eyes.
3. Easy-to-maintain : Python's source code is
fairly easy-to-maintain.
4. Interactive Mode : Python has support for
an interactive mode which allows interactive
testing and debugging of snippets of code
5. Portable : Python can run on a wide variety
” Gf hardware platforms and has the same in-
terface on all platforms.
ple program
Python, Iam python Basic syn-
ee
Bo
Seka fee
Hlevel
: can add low- mod,
ete Se Then
ules enable Preto be more eicent.
se
7. Boater commercial data
hte : Python provides a better strc.
‘8. Scalable j port for large Programs than she
ture and sui
_ see
plications of Python?
Q3. Explain the aPI :
‘Ans: Application of Python =
‘There are a iot of applications that are wrt.
ten in python language.
‘Types of python application :
2) Sciences and education applications
wveiop the applications
1on you can develop .
mar athe for scientific an:i educational
purposes.
Here are some popular python science and
‘education applications.
+ Metapath
+ Pychem
+ ACQ4
b) Console based application:
Here are list of popular console based appli-
cation in python.
+ SQL python
+ Ipython
¢) Image applications :
* img seek
+ Vpthon:
* Gogh
The above are sonic ;opular Image applica-
tions.
4) Enterprise applications :
The following are list of some common en-
terprise applications
+ Picalo
+. Tryton
Fag 7 KeroePRotoconying oF tls book & CRNINAL At Ayo foun pally BURGE i acs LEGA mae
NeWeming : Xero:
Internet of Things m
¢) Official applications ;
+ Pyspread
+ Calibre
‘The above are list of official applications
f) Mobile applications :
Mobile applications ean also di
python, a.
* Pyroute
+ AppBackup
g) Internet or Webbased application
+ Bit torrent
+ SpamBayers
* Mnet
+ Netusage
The above are list of some popular web based
applications.
3.2 PyTHON Datatypes ADN Data sTRUC-
TURES
Q4. Explain Datatypes of python language
briefly with examples?
Ans: Data types of python :
The following are five standard data type of
python.
+ Numbers type
+ String type
«List type
* Tuple type
* Dictionary type
a) Python number:
Number data types are used to store numeric
values in python program. Changing the val-
ues of a number data type results in a newly
allocated object.
Example :
#python NumberDatatyoe - Example pro-
gram
num1 = 10
num2 = 20
Print ‘num1=", num1," and num2
num2)
B34
Delete the reference to a number object in
python,
To delete reference to a number object in
python, use the keyword del
del vari, var2[, var3{....-varN]]]
Examples :
#Python Number Datatype_example pro-
‘gram.
num = 10
num] = 20
Print (“num
num2)
b) Python
Strings are contiguous set of characters in
between quotation marks.
num,
_ Example
str] = ‘Hello Python’
str = "This is Python Strings Tutorial”
Repeating string in python :
String in python can be repeated using
* Operator as shown in example given below
Example =
# String Repeating example in python
Print (“This is string repeat in python");
Print (“Below code will repeat the string re-
peat 10 times\n’);
Print (“StrongRepeat” *10);
Print( “Below code will repeat the string re-
peat 10 times with space\n”)
Print (“StringRepeat” *10);
¢) Python strings
Lists in python are also a type of sequence
just like tuples,
Unlike tuples lists are mutable, that is, list can
be modified.
Creating list in python :
List 1 = [‘computer’, ‘programming’, 1957,
2070, 3242")
List 2 = [1,2,3,4.5);
List 3
a ew CRIMINAL ck. Anyone Tounsd Guy Io LIABLE fave LEGAL proceedings
erwet gh Things
A f item in tuple
inting each item in tuph
Print ("wn Now Pri
"»
Finding length of tuple in python :
‘The fen () funciton in python is used to tt
length of tuple as shown in following example
Example
oe tuple in python
“Two"
“on
length_of_tuple = ten (my_tuple);
Print (“Length of tuple, my_tuple is :*,
length_of _tuple}s
ict same as real life dic-
tionary book, as in dictionary, you can store
your information in form of key value pair,
Using dictionary in python, you can organize
your information.
Create Dictionary in Python :
Dictionaries are enclosed with in the curly
braces { } ee
my_dictionary = {‘Name’; Devraj”, ‘Id’
9388, ‘Branch’ : ‘CSE"}; es
Access dictionary values in python :
One can access dictionary values using the
9g
square braces [ ] as shown in following ex-
ample.
my_dictionary{name]
Example for python dictionary :
dictionary 1 = { }
dictionary 1 one’ = “This is one”
dictionary 1 [2] = “This is two"
small dictionary = {‘name’: ‘Devraj’, ‘id’ :
9388, ‘branch’ : ‘CS’
Print (dictionary 1(2})
Print (dictionary 1[*One’})
Print (small dictionary)
Print (small dictionary key ( ))
Print (small dictionary.values Q)Int
3.3 CONTROL oF FLOW,
Q5. Explain the con:
An
ternet of Thing
Eo trol of flow in python bri-
ns: Control of flow : i
The following are fix
a) Python if,
b) Python for loop
©) Python while loop
ive standard data type of
else
d) Python break & continue
e) Python pass
a) Python if...
Syntax :
- else
if test expression
Body of if
else
body of else
Flow chart of if else :
The following figure shows the flow chart of if,
else
reve
ody oft Body otese
Example : :
# program checks if number is positive or
negative.
num = 3
# num 5
# num =0
if num > =0;
Print (“Positive or Zero”)
else
Print (“Negative number”)
b) Python for loop
is used to iterate over a sequence or other
erable objects,
erating over a sequence is called traversal.
Syntax :
for val in sequence
Body of far
for each tam
imeequence
Body of or
Exttloop
Examples :
# Program to find sum of all numbers sotred_
ina list
number = [6,5,4;3,4,2,5,4,11]
# variable to store sum
sum = 0
for val in numbers ;
sum = sum+val
Print (“The sum is”, sum)
Example for loop with else
digits = (0,1,5]
for i indigits
print (i)
else:
Print (“No item left.”)
c) Python while loop
Itis used to iterate over a a block of code as
Jong as the test expression is true
Syntax :
While test_expression
Body of white
Flow chart :
is book is @ CRIMINAL Act. Anyone found guilty Is LIABLE to face LEGAL proceedings
is book Is & CRIMINAL/Act. Anyone found guilty le LIABLE to face LEGAL bsBody of white
Eaton
Example :
# program to add natural numbers
n=10
sum = 0
1
while i < = n;
sum = sum +i
isi+d
Print (“The sum is”, sum)
Example for while loop with else :
Counter = 0
while counter < 3:
Print (“Inside loop")
Counter = counter +1
else :
Print (“Inside else”)
4) Python break & continue :
+ Break and continue statements can alter the
flow of a normal loop. ;
Python break : ‘i
Syntax
fenerice
Remaining body often
‘Wiarsina * Keren] Phatacnnvinn af th TAS
Internet of Things
Example :
for val in “Strings”,
ifval = =
break
Print (val)
Print (“The end”)
Python continue :
Syntax,
Continue
Flow chart
Remaining body of loop
Ext loop
Example :
for val in “Strings”;
if val
continue
Print (val)
Print ("The end”)
“e) Python Pass :
Pass is a null statement. Difference between
comment and pass statement in python is
while interpreter ignores a comment entirely,
ass is not ignored.
Syntax of pass :
Pass,
Example :
a
Sequence = ['p',‘a', 's''s]
int val in sequence
pass
- def fun () :
passInternet of Things
Print (*Uhave called function”)
fun ()
3.4 Functions :
Q6. Explain python functions briefly?
Aus: Functions in python :
* Functions are the most important aspect of
an application. A function can be defined as
the organized block of reusable code which
can be called whenever required,
* Python allows us to divide a large program
into the basic building blocks known as func-
tion. The function contains the set of program-
ming statements enclosed by { }
* A function can be called multiple times to pro-
vide reusability and modularity of python
program,
* In other words, we can say that the collection
of functions creates a program. The function
is also known as procedure ot subroutine in
other programming languages.
Advantages of functions in python :
* By using functions, we can avoid rewriting
same logic/code again and again in a program,
* We can call python functions any number of
‘times in a program and from any place in a
Program.
* Reusability is the main achievement of py-
thon functions
However, Function calling is always overhead
in a python program,
Creating a function
The syntax to define a function in python is
given below.
def my_function( ):
function-suite
return
Function calling :
In python, a function must be defined before
the function calling otherwise the python in:
tempreter gives an error
* A simple function that prints the message
"Hello Word" is given below,
Warning : Xerox/Photocopying of this book is @ GRIMINAL Aa. Anyone found guilty is LIABLE to face LEGAL proceed
Ans: Call by reference :
dat ello_world }
print(thello world")
hello_world()
Parameters in function :
i functio (
+ The information into the ca
ee as the parameters. The parameter 3
specified in the parentheses. ‘
+ The following example which contains a
tion thatacceptsa string as the parameter any
prints it
lef func (name}:
print("Hi",name);
func("Ayush")
Example program :
# python function to calculate the
variables,
def sum (a,b):
return a+b;
Sum of tp
@ = int(input("Enter a: "))
b = int{input("Enter b: "))
print(’Sum =", sum(a,b))
plain briefly?
erence inside the function revert back to
original value referred by the reference
Example : Passing immutable objec (List
def change_listlist1):
list append(20); ;
list] append(30); ‘2s
Print("list i si
List = (10,30,40,50] a
Change list (lst 1)
Print ("list ‘outside function =' g
Example 2 : Passing ‘mutable object (String):
def change_string (sr): ;
str = str +" Hows. you";
Print(‘printing the string inside functionsringl = "Hil am there”
change_string(string])
print(‘printing the string outside function :*,
stringl)
5, Explain types of arguments briefly?
\s ‘Types of arguments :
| There may be several types of arguments
uihich can be passed at the time of function
caling.
a) Required arguments
) Keyword arguments
) Default arguments
4) Variable-length arguments
1, Required Arguments
‘These are the arguments which are required
to be passed at the time of function calling
with the exact match of their positions in the
function call and function definition.
Examples,
def simple_interest(p,t.r)
return (p*t*r)/100
P= float{input("Enter the principle amount? "))
float{input("Enter the rate of interest? *))
t
float{input("Enter the time in years? *))
Prin'Simple Interest: ° simple_interest(p.74))
2. Keyword arguments :
Python allows us to call the function with the
Keyword arguments. This kind of function call
will enable us to pass the arguments in the
random order.
Examples
def simple _interest(p.t.r):
tetum (p*t*1)/100
Prin (‘simple Interest”, simple_interest (t=10,
=10, p=1900)
. Default arguments
Python allows us to initialize the arguments at
| the function definition. If the value of any of
| the argument is not provided at the time of
function call, then that argument can be ini-
tialized with the value given in the definition
|__€ven if the argument is not specified
ating XeroxiPhotocopying of this book is a CRIMINAL Ac Anyor
MW Internet of Things
Example
def printme(name,age=22)
print("My name is".name,"and age is".age)
printme(name = "john’)
Printme(age = 10,name="David")
4. Variable length arguments :
In this we define variable with
* (star) as *
Example :
def printme(*names)
print("type of passed argument is “type
(names)
print(‘printing the passed arguments...)
for name in names:
print(name)
printme("john","David’,"smith* ‘nick”)
3.5 PytHon Moputes
Q9. Explain python modules briefly?
Ans: Python modules :
A python module can be defined as a py-
thon program file which contains a python
code including python functions, classes, or
variables.
Modules in Python provides us the flexibility
to organize the code in a logical view.
Example :
#displayMsg prints a message to the name
being passed.
def displayMsa(name)
Print("Hi "+name);
Loading the module in our python code:
We need to load the module in our python
code to use its functionality. Python provides
two types of statements as defined below.
a) The import statement
b) The from-import statement
a) The import statement :
The import statement is used to import all the
functionality of one module into another.
‘The syntax to use the import statement is given
ne found guilty is LIABLE to face LEGAL procesding®Internet of Things
import module 1,module2,........ module n
Example
import fite
pame = input("Enter the name?")
file displayMsa(name)
b) The from _import statement :
*+ Instead of importing the whole module into
the namespace, python provides the flexibil-
tty to import only the specific attributes of a
module. This can be done by using from?
import statement,
* The syntax to use the from-import statement
is given below.
from < module-name> import ,
-hame n>
Example :
Consider the following module named as cal-
culation which contains three functions as
summation, multiplication, and divide.
calculation. py:
def summation(a,b)
retum a+b
def multiplication(a,b):
retum a*b;
def divide(a,b)
return afb;
Main.py:
from calculation import summation
a = int(input("Enter the first number")
b = intlinput("Enter the second number"))
= "summation(a,b))
Renaming a module
4 Python provides us the flexibility to import
some module with a specific name so that we
can use this name to use that module in our
python source file,
+ The syntax to rename a module is given be-
low.
import as
Example
import calculation as cal;
a = int{input(Enter 2?°)):
b = int(input("Enter b?")):
cal summation(a,b})
print("Sum
Using dir()) function .
ic ted list of
The dir( ) function returns a sor a
ames defined in the passed module. This
contains all the sub-modules, variables ang
functions defined in this module.
Example
import json
List = dir(json)
——brint(List)
Q10. Write an example of python modules?
Ans: Module student :
Sum = sum + students [Key] [grade] «
average = Sum/len (Students)
return average
def Print records (Student):
Print “There are %d students”%(Len stu-
dents)
t=1
for key in students :
Print “Studen -%d:"%(i)
Print “Name :”+students [key][‘name’]
itl
Using module student :
>>> import student
>>> students = ‘1’; ‘name’ : ‘Bob’, ‘grade’
‘Many’, ‘grade’; 3.5,
‘David’, ‘grade’; 4.2,
John’, ‘grade’; 4.1,
2 Alex’, ‘grade’; 3.8,
>> >Student.printRecords(students)
‘There are 5 students
Student-1 :
Name: Bob
Grade: 2,5
‘5’ ‘name’
Warning : Xerox/Photocopying of this Look Is @ GRIMINAL Act. Anyone found gully le LABLE fo Taco LEGAL proceedingsinternet of Things
Student -2 ;
Name : David
Grade : 4.2
Student-3.
Name: Marry
Grade : 3.5
Student-4
Name: Alex
Grade : 3.8
‘Sjudent-5 :
Name: John
* Grade : 4.1
>>>avg = student.average student(Student)
0.21" %lAvg) 3.62
Importing a specific function from a module :
>>>print “The average grade is :
>>> from student import average grade
‘name’: ‘bob’, ‘grade’ :2.5,
“Manry’, ‘grade’; 3.5,
‘David’, ‘grade’; 4.2,
John’, ‘grade’, 4.1,
‘9: ‘name’ : ‘Alex’, ‘grade’; 3.8,
>>>avg = averageGrade (students)
>>>Print “The average grade is :%0.2 £"% (avg) 3.62
3.6 PACKAGES
QI1. Discuss about python package briefly.
Ans: Python Package :
+ Python package is hierarchical file
allow better organization of modules related to a single application
nt environment by providing a hierarchica!
ges, modules and sub modules.
structure that consists of modules and subpackages. Packages
environment,
* It facilate the developer with application developme
directory struture where a package contains sub packay
Example :
Let's create a package named Employees in your directory. Cor
1. Create a directory with name employees on path / home.
2. Create a python source file with name IT employeers.py on pathvhome/employees.
sider the following steps.
IT employees.py
def getITNames(
List = ["John", "David", "Nick", Martin") return List; ,
2 ABLE to face LEGAL proceedings
Warang DKerantbncrecapying of ns book Tea GRIMINAL At: Anyone found gully s UABLE 1 52Internet of Things
jes.py and create a functioy
3. Similarly, create one more python file with name BPOEmployees.py m
getBPONames(),
—init_py
from ITEmplovees import get! TNames
from BPOEmployees import get8PONames
4. Test.py
import Employees
print(Employees.getNames())
: ication Lit t system
* The following image shows the directory structure of an application Library management v
which contains three sub-packages as Admin, Librarian, and Student, The sub-packages contain the
python modules.
Ls package
Ls sub-package
module 2
3.7 FILEHANDLING
Q12. Explain file handling in python briefly? _
Ans: Python Packag. :
* Python allows reading and writing to file using file object. The open (filename, mode) function is u
sed to geta file objects.
* fhe mode can read (r), write (w), append (a), read and wtite (r+ oF ut) read binary (0b), write
binary (Wb) etc., =
* The following example shows reading on entire file with read function,
Example :
1. Reading an entire file
>>>fp = open(file.txt’. '’)
>>>content = fp.read| )
>>>print content
Python is an interpreted language and does not require explicit compilation step.
>> >fp.close()
2, Reading line by line
>>>fp.close ()
>>>fp = open(tile.txt’, )
>>>print "Line-1: "+fp.readline( )
Line-1: Python supports more than one programming paradigms,
Warning : Kerox/Photocopying of tis book is @ CRIMINAL Adt. Anyone found gully S LABLE We face LEGAL procoodnas 73.13
>>>print "Line-2
"+ fp.readline( )
Line-2: Python is an interpreted language.
>>>fp.close( )
Reading line in a loop :
v)
fp.readlines( )
>>>fp = openttile.ts
>> olin
>>>for line in lines:
print line
Python supports more than paradigms includ
ing
Python is an interpreted language.
Reading a certain number of bytes
>>>fp = open(file.txt,'")
>>>fp.read(10)
"Python sup’
>>>fp.close( )
Getting the current position of read:
>>>fp = opent(filetxt’, ')
>>>{p.read(10)
‘Python sup!
>>>currentpos = fp.tell
>>>print currentpos
>>>fp.closel ) ;
Seeking to a certain position :
>>>fp = open({ile.txt’,’)
>>>{p.seek(10,0)
>>>econtent = fp.read(10)
>>,>print content ports more
>>>fp.close( )
Writing to a file:
>>>fo = open((filel txt'w’)
>>>content = ‘This is an example of writ-
ing toa file in python.”
>>>fo.write (content)
>>>fo.close ()
Interne!
hinge
3.8 Datt/time Orcrations
Q13.
plain about Python Date and time op-
erations?
Ans: Python Date and Time ;
In python, the date is not a data type, but we
can work with the date objects by importing
the module named with datetime, time, and
calendar.
Consider the following example.
import time;
# prints the number of ticks spent since 12
AM, 1" January 1970
print(time.time( ))
How to get the current time? .
‘The localtime( ) functions of the time module
_are used to get the current time tuple. Con-
sider the following example.
Example :
import time;
#retuims a time tuple
print(time.localtime(time.time()))
Ge
The time can be formatted by using the
asctime ( ) function of time module.
g formatted time :
Example :
import time;
#returns the formatted time
print(time.asctime(time.localtime (time. time
cm).
Python sleep time:
The sleep ( ) method of time module is used
to stop the execution of the script for a given
amount of time. The output will be delayed
for the number of seconds given as float.
Example :
import time
for | in range(0,5):
print(i)
#Each element will be printed after 1 second
time.sleep
time.sleep (1)Internet of Things m
Datetime Module :
+ The datetime module enables us to create the
custom date objects, perform various opera-
tions on dates like the comparison, ete
+ Consider the following example to get the
datetime object representation for the current
time.
Example :
import datetime;
print (datetime.datetime.now())
Creating data objects :
+ Consider the following example
import datetime;
# retums the datetime object for the speci-
fied date
print(datetime.datetime(2018,12,10)
* Consider the example
import datetime;
# retus the datetime object for the speci-
fied time
print(datetime.datetime(2018,12,10,14,15,
10) 7
Comparision of two dates :
* Two dates by using the comparison opera-
tors like >, >=, <, and <=
* Consider the following example.
from datetime import datetime as dt
if dt(dt.now().yeardt.now().month,dt.now().
day,8)
continon>Bloodroot
Sanguinaria canadensis
4
Mostly Shady
2.44
Columbine
Aquilegia canadensis
3
Mostly Shady
9.37
Parsing on XML file in python :
from xml.dom.minidom import parse
dom = parse("test.xml")
for node in dom.getElementsByTagName
(plant):
id=node.getAttribute(id’)
print "Plant ID:", id
‘common=node.getElementsByTagName
(common’){0} .childNodes{0].nodeValue
print "Common:’
"common.
botanical=node.getElementsByTagName
(octanical’{0}.childNodes{0].nodeValue
__W Internet of Things
print "Botanical:", botanical
zone=node.getElementsByTagName (zone)
{0].childNodes{0]. nodeValue
_—_Brint "Zone:", zone.
print "Zone:”. zone.
QI7. Explain about HTTL#b & URLLib brie-
fly?
‘Ans: HTTPlib and URLLib2 are Python libraries
used in network/intemet prograraming (111
121, HTTPLib2 is an HTTP dlient library and
URLLIb2 is a library for fetching URLs.
Examples :
HTTP GET request using HTTPLib
>>> import httplib2
>> >h=httplib2. Htp( )
>>> resp, content = h.request (“http://
example.com’, "GET")
>>> resp
{‘status’'200;, ‘content -length':'1270, ‘content
= location’: ‘http://example.com’, 'x-cache':
HIT, ‘accept-ranges’: ‘bytes’, ‘server’: ECS
(cpmvF585)',
‘last -modified’: Thu,25 Apr 2013 16:13:23
GMT, ‘etag': ‘date’: Wed, 31 Jul 2013 12: 36:
05 GMT, ‘content-type’: text/html; charset =
UTF8)
>>> content
\n\n\n
Codestin Search App\n\n
\n
HTTP request using URL Lib2
>>> import urllibS
>>>
>>> req = urllib2, Request (‘htttp://
example.com’) :
>>> response = urllib2.urlopen (rea)
>>> response_page = response.read| }
>>> response_pege
< ! doctype html>\ n\n\n
Example Domain\n\n
\n
‘Waring : Xerox/Phatocopying of thia book Is a CRIMINAL Act. Anyone found guilty le LIABLE fo face LEGAL proceedings
a |Q18. Explain SMTP Lib with example?
Ans: SMTP Lib: ao
* Simple Mail Transfer Protocol(SMTP) is a protocol which handles sending
between mail servers,
see éan he used to send ema
* The Python smtplib module provides an SMTP client session object that €an mail
(213).
* ing Message contains the _
The following is an example of sending email from Gmail account. The srnaress seas
email message to be sent. To send email from a Gmail account the Gmail
server string,
ail and routing &- may
Example
import smtplib
from_email = '"
recipients_list =
=U
subject = ‘Hello!
‘']
col
message = This isa test message."
username = ''
Password = ''
server = 'smtp.gmail.com:587'
def sendemaillfrom_addr, o_addr list, ec_addt_lst, subject, message, login, password, smipserver:
header = ‘From: %s\n' % from_addr
header += "To: s\n’ % ',"join(to_addr_list)
header += ‘Ce: %sin' % 'join(cc_addr_list)
header += ‘Subject: %s\n\n' % subject
message = header + message
server = smtplib.SMTP(smtpserver)
server startils( )
server. login(login password)
server.quit()
#Send email
sendemail (rom_email, recipients list, cc_lst, subject, message, username, password, server)