Você está na página 1de 64

Contents

The print Function................................................................................................................................... 2


Reading Input from Keyboard .............................................................................................................. 2
Python Numbers ..................................................................................................................................... 3
Python Strings......................................................................................................................................... 3
Python Lists ............................................................................................................................................. 4
Python Tuples.......................................................................................................................................... 5
Python Dictionary.................................................................................................................................... 6
Other string methods for Formatting ..................................................................................... 7
Types of Operator................................................................................................................................... 9
The range() function ............................................................................................................................ 12
What is pass statement in Python? ................................................................................................... 14
Sets .................................................................................................................................................... 15
Sublists ............................................................................................................................................. 16
Optional Parameters ................................................................................................................... 17
Arbitrary Number of Parameters ............................................................................................ 18
Arbitrary Number of Keyword Parameters ......................................................................... 19
Recursive Functions in Python ................................................................................................ 20
First Steps to Decorators .......................................................................................................... 21
The map() Function ..................................................................................................................... 23
Filtering ............................................................................................................................................ 24
Examples of reduce().................................................................................................................. 25
The dir( ) Function ................................................................................................................................ 26
Importing Modules ....................................................................................................................... 26
Renaming a Namespace ............................................................................................................ 27
What is Tick? ......................................................................................................................................... 28
Example ......................................................................................................................................... 28
Getting formatted time ........................................................................................................................ 28
Getting calendar for a month.............................................................................................................. 29
Exception Handling in Python .................................................................................................. 29
FILE Handling in Python............................................................................................................. 30
Example of Inheritance in Python .................................................................................................. 34
Method Overriding in Python .............................................................................................................. 35
Data Abstraction, Data Encapsulation, and Information Hiding ................................ 37
Destructor ....................................................................................................................................... 42
Example ......................................................................................................................................... 48
Example of w+ and ^ Expression ........................................................................................................... 49
Python Closures .......................................................................................................................................... 57
Querying data with fetchmany ............................................................................................................ 62
Python MySQL Insert Data .................................................................................................................. 63

Python references:

The print Function


print("Hello World")# in Python 3, print must be followed by ()

In Python 3, "end =' '" appends space instead of newline.

print(x,end=" ")# Appends a space instead of a newline in Python 3

Reading Input from Keyboard


>>> x = input("something:")

something:10

>>> x

'10'

>>> x = input("something:")

something:'10'#entered data treated as string with or without ''

>>> x

"'10'"

Simple function coding:


Converted code :

def area(x,y =3.14):# formal parameters

a = y*x*x

print(a)

return a

a = area(10)

print("area",a)

Python has five standard data types −

 Numbers

 String

 List

 Tuple

 Dictionary

Python Numbers
var1 = 1
var2 = 10
del var
del var_a, var_b

Python supports four different numerical types −

 int (signed integers)

 long (long integers, they can also be represented in octal and hexadecimal)

 float (floating point real values)

 complex (complex numbers)

Python Strings
str ='Hello World!'

str # Prints complete string

str[0]# Prints first character of the string

str[2:5]# Prints characters starting from 3rd to 5th

str[2:]# Prints string starting from 3rd character

str *2# Prints string two times

str +"TEST"# Prints concatenated string

This will produce the following result −


Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST

Strings can be created by enclosing characters inside a single quote or double quotes. Even
triple quotes can be used in Python but generally used to represent multiline strings and
docstrings.
String Formats:

name='priya'

>>> age=26

>>> 'I am {} and i am {} years old'.format(name,age)

'I am priya and i am 26 years old'

Python Lists

list =['abcd',786,2.23,'john',70.2]

tinylist =[123,'john']
list # Prints complete list

list[0]# Prints first element of the list

list[1:3]# Prints elements starting from 2nd till 3rd

list[2:]# Prints elements starting from 3rd element

tinylist *2# Prints list two times

list + tinylist # Prints concatenated lists


['abcd', 786, 2.23, 'john', 70.200000000000003]
abcd
[786, 2.23]
[2.23, 'john', 70.200000000000003]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john']

Python Tuples
tuple =('abcd',786,2.23,'john',70.2)

tinytuple =(123,'john')

print tuple # Prints complete list

print tuple[0]# Prints first element of the list

print tuple[1:3]# Prints elements starting from 2nd till 3rd

print tuple[2:]# Prints elements starting from 3rd element

print tinytuple *2# Prints list two times

print tuple + tinytuple # Prints concatenated lists

This produce the following result −


('abcd', 786, 2.23, 'john', 70.200000000000003)
abcd
(786, 2.23)
(2.23, 'john', 70.200000000000003)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john')

The following code is invalid with tuple, because we attempted to update a


tuple, which is not allowed. Similar case is possible with lists −

#!/usr/bin/python
tuple =('abcd',786,2.23,'john',70.2)

list =['abcd',786,2.23,'john',70.2]

tuple[2]=1000# Invalid syntax with tuple

list[2]=1000# Valid syntax with list

Python Dictionary
tinydict ={'name':'john','code':6734,'dept':'sales'}

print tinydict # Prints complete dictionary

print tinydict.keys()# Prints all the keys

print tinydict.values()# Prints all the values


{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']

The second case can be expressed with a dictionary as well, as we can see in the following
code:
>>> data = dict(province="Ontario",capital="Toronto")
>>> data
{'province': 'Ontario', 'capital': 'Toronto'}
>>> print("The capital of {province} is {capital}".format(**data))
The capital of Ontario is Toronto

The double "*" in front of data turns data automatically into the form
'province="Ontario",capital="Toronto"'. Let's look at the following Python program:
capital_country = {"United States" : "Washington",
"US" : "Washington",
"Canada" : "Ottawa",
"Germany": "Berlin",
"France" : "Paris",
"England" : "London",
"UK" : "London",
"Switzerland" : "Bern",
"Austria" : "Vienna",
"Netherlands" : "Amsterdam"}

print("Countries and their capitals:")


for c in capital_country:
print("{country}: {capital}".format(country=c,
capital=capital_country[c]))

Other string methods for Formatting


The string class contains further methods, which can be used for formatting purposes as
well: ljust, rjust, center and zfill

Let S be a string, the 4 methods are defined like this:

 center(...):

 S.center(width[, fillchar]) -> str

Return S centred in a string of length width. Padding is done using the specified fill
character. The default value is a space.

Examples:

>>> s = "Python"
>>> s.center(10)
' Python '
>>> s.center(10,"*")
'**Python**'

 ljust(...):

 S.ljust(width[, fillchar]) -> str

Return S left-justified in a string of length "width". Padding is done using the


specified fill character. If none is given, a space will be used as default.

Examples:
>>> s = "Training"
>>> s.ljust(12)
'Training '
>>> s.ljust(12,":")
'Training::::'
>>>

 rjust(...):

 S.rjust(width[, fillchar]) -> str

Return S right-justified in a string of length width. Padding is done using the


specified fill character. The default value is again a space.

Examples:

>>> s = "Programming"
>>> s.rjust(15)
' Programming'
>>> s.rjust(15, "~")
'~~~~Programming'
>>>

 zfill(...):

 S.zfill(width) -> str

Pad a string S with zeros on the left, to fill a field of the specified width. The string S
is never truncated. This method can be easily emulated with rjust.

Examples:

>>> account_number = "43447879"


>>> account_number.zfill(12)
'000043447879'
>>> # can be emulated with rjust:
...
>>> account_number.rjust(12,"0")
'000043447879'
>>>

Types of Operator
Python language supports the following types of operators.

 Arithmetic Operators

% modulo

** exponent

// floor division

 Comparison (Relational) Operators

If else loop:

amount = int(input("Enter amount: "))

if amount<1000:

discount = amount*0.05

print ("Discount",discount)

else:

discount = amount*0.10

print ("Discount",discount)

print ("Net payable:",amount-discount)

Assignment Operators
Logical Operators

marks=67

>>> if(marks>80 and attendance=='present'):

print('grade a')

else:

print('grade b')

grade b

elif loop:

if(marks>80 and marks<95):

print('grade a')

elif(marks<60and marks>80):

print('grade b')

elif(marks<40 and marks>60):

print('grade c')

else:

print('fail')

Bitwise Operators

&-And
|-or

^-xor

~ones compliment

<<binary left

>>binary right

Membership Operators

In

Not in

if(a in list):

print("yes")

else:

print("no")

Identity Operators:

Is

Is not

Id(a)

While loop:

count =0

while(count <9):

print('The count is:', count)


count = count +1

print("Good bye!")

while with else:

count =0

while count <5:

print(count," is less than 5")

count = count +1

else:

print(count," is not less than 5")

The range() function


>>> range(5)

range(0,5)

>>> list(range(5))

[0,1,2,3,4]

>>>forvarin list(range(5)):

print(var)

for letter in'Python':# traversal of a string sequence

print('Current Letter :', letter)

print()

fruits =['banana','apple','mango']

for fruit in fruits:# traversal of List sequence

print('Current fruit :', fruit)


fruits =['banana','apple','mango']

for index in range(len(fruits)):

print('Current fruit :', fruits[index])

The following program uses a nested-for loop to display multiplication tables


from 1-10.

for i in range(1,11):

for j in range(1,11):

k=i*j

print(k,end=' ')

print()

Break statement:

for letter in'Python':# First Example

if letter =='h':

break

print('Current Letter :', letter)

var=10# Second Example

whilevar>0:

print('Current variable value :',var)

var=var-1

ifvar==5:

break
no=int(input('any number: '))

numbers =[11,33,55,39,55,75,37,21,23,41,13]

for num in numbers:

if num ==no:

print('number found in list')

break

else:

print('number not found in list')

Continue statements:

for letter in'Python':# First Example

if letter =='h':

continue

print('Current Letter :', letter)

var=10# Second Example

whilevar>0:

var=var-1

ifvar==5:

continue

print('Current variable value :',var)

What is pass statement in Python?


In Python programming, pass is a null statement. The difference between
a comment and pass statement in Python is that, while the interpreter ignores a
comment entirely, pass is not ignored.

However, nothing happens when pass is executed. It results into no operation (NOP).

sequence = {'p', 'a', 's', 's'}

for val in sequence:

pass

Sets
If we want to create a set, we can call the built-in set function with a sequence or another
iterable object:

In the following example, a string is singularized into its characters to build the resulting set
x:
>>> x = set("A Python Tutorial")
>>> x
{'A', ' ', 'i', 'h', 'l', 'o', 'n', 'P', 'r', 'u', 't', 'a', 'y', 'T'}
>>> type(x)
<class 'set'>
>>>

We can pass a list to the built-in set function, as we can see in the following:

>>> x = set(["Perl", "Python", "Java"])


>>> x
{'Python', 'Java', 'Perl'}
>>>

Now, we want to show what happens, if we pass a tuple with reappearing elements to the
set function - in our example the city "Paris":
>>> cities = set(("Paris", "Lyon", "London","Berlin","Paris","Birmingham"))
>>> cities
{'Paris', 'Birmingham', 'Lyon', 'London', 'Berlin'}
>>>

Sequences are one of the principal built-in data types besides numerics, mappings, files,
instances and exceptions. Python provides for six sequence (or sequential) data types:

 strings
 byte sequences
 byte arrays
 lists
 tuples
 range objects

countries = ["Germany","Switzerland","Austria","France","Belgium",
"Netherlands", "England"]
>>> len(countries)
7
>>> fib = [1,1,2,3,5,8,13,21,34,55]
>>> len(fib)
10

Sublists
Lists can have sublists as elements. These sublists may contain sublists as well, i.e. lists can
be recursively constructed by sublist structures.
>>> person = [["Marc","Mayer"],["17, Oxford Str", "12345","London"],"07876-
7876"]
>>> name = person[0]
>>> print(name)
['Marc', 'Mayer']
>>> first_name = person[0][0]
>>> print(first_name)
Marc
>>> last_name = person[0][1]
>>> print(last_name)
Mayer
>>> address = person[1]
>>> street = person[1][0]
>>> print(street)
17, Oxford Str
Functions:
def fahrenheit(T_in_celsius):
""" returns the temperature in degrees Fahrenheit """
return (T_in_celsius * 9 / 5) + 32

for t in (22.6, 25.8, 27.3, 29.8):


print(t, ": ", fahrenheit(t))

The output of this script looks like this:


22.6 : 72.68
25.8 : 78.44
27.3 : 81.14
29.8 : 85.64

Optional Parameters
def Hello(name="everybody"):
""" Greets a person """
print("Hello " + name + "!")

Hello("Peter")
Hello()

The output looks like this:


Hello Peter!
Hello everybody!

Using keyword parameters is an alternative way to make function calls. The definition of the
function doesn't change.
An example:

def sumsub(a, b, c=0, d=0):


return a - b + c - d

print(sumsub(12,4))
print(sumsub(42,15,d=10))

Keyword parameters can only be those, which are not used as positional arguments. We can
see the benefit in the example. If we hadn't keyword parameters, the second call to function
would have needed all four arguments, even though the c needs just the default value:
print(sumsub(42,15,0,10))
def empty_return(x,y):
c = x + y
return

res = empty_return(4,5)
print(res)

def f():
s = "Perl"
print(s)

s = "Python"
f()
print(s)
def f():
global s
print(s)
s = "dog"
print(s)
s = "cat"
f()
print(s)

Arbitrary Number of Parameters

def arithmetic_mean(first, *values):


""" This function calculates the arithmetic mean of a non-empty
arbitrary number of numerical values """

return (first + sum(values)) / (1 + len(values))

print(arithmetic_mean(45,32,89,78))
print(arithmetic_mean(8989.8,78787.78,3453,78778.73))
print(arithmetic_mean(45,32))
print(arithmetic_mean(45))

x = [3, 5, 9]
arithmetic_mean(*x)

A practical example:
We have a list
my_list = [('a', 232),
('b', 343),
('c', 543),
('d', 23)]

We want to turn this list into the following list:


[('a', 'b', 'c', 'd'),
(232, 343, 543, 23)]

This can be done by using the *-operator and the zip function in the following way:
list(zip(*my_list))

Arbitrary Number of Keyword Parameters


In the previous chapter we demonstrated how to pass an arbitrary number of positional
parameters to a function. It is also possible to pass an arbitrary number of keyword
parameters to a function. To this purpose, we have to use the double asterisk "**"
>>> def f(**kwargs):
... print(kwargs)
...
>>> f()
{}
>>> f(de="German",en="English",fr="French")
{'fr': 'French', 'de': 'German', 'en': 'English'}
>>>

One use case is the following:


>>> def f(a,b,x,y):
... print(a,b,x,y)

>>> d = {'a':'append', 'b':'block','x':'extract','y':'yes'}
>>> f(**d)
('append', 'block', 'extract', 'yes')
Recursive Functions in Python
Now we come to implement the factorial in Python. It's as easy and elegant as the
mathematical definition.
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)

We can track how the function works by adding two print() functions to the previous
function definition:
def factorial(n):
print("factorial has been called with n = " + str(n))
if n == 1:
return 1
else:
res = n * factorial(n-1)
print("intermediate result for ", n, " * factorial(" ,n-1, "):
",res)
return res

print(factorial(5))

This Python script outputs the following results:


factorial has been called with n = 5
factorial has been called with n = 4
factorial has been called with n = 3
factorial has been called with n = 2
factorial has been called with n = 1
intermediate result for 2 * factorial( 1 ): 2
intermediate result for 3 * factorial( 2 ): 6
intermediate result for 4 * factorial( 3 ): 24
intermediate result for 5 * factorial( 4 ): 120
120

Function example:
>>> def no_side_effects(cities):
... print(cities)
... cities = cities + ["Birmingham", "Bradford"]
... print(cities)
...
>>> locations = ["London", "Leeds", "Glasgow", "Sheffield"]
>>> no_side_effects(locations)
['London', 'Leeds', 'Glasgow', 'Sheffield']
['London', 'Leeds', 'Glasgow', 'Sheffield', 'Birmingham', 'Bradford']
>>> print(locations)
['London', 'Leeds', 'Glasgow', 'Sheffield']
>>>

First Steps to Decorators


We know from our various Python training classes that there are some sticking points in the
definitions of decorators, where many beginners get stuck.

Therefore, we wil will introduce decorators by repeating some important aspects of


functions. First you have to know or remember that function names are references to
functions and that we can assign multiple names to the same function:
>>> def succ(x):
... return x + 1
...
>>> successor = succ
>>> successor(10)
11
>>> succ(10)
11

This means that we have two names, i.e. "succ" and "successor" for the same function. The
next important fact is that we can delete either "succ" or "successor" without deleting the
function itself.
>>> del succ
>>> successor(10)
11

Functions inside Functions


The concept of having or defining functions inside of a function is completely new to C or
C++ programmers:
def f():

def g():
print("Hi, it's me 'g'")
print("Thanks for calling me")

print("This is the function 'f'")


print("I am calling 'g' now:")
g()

f()

We will get the following output, if we start the previous program:


This is the function 'f'
I am calling 'g' now:
Hi, it's me 'g'
Thanks for calling me

Another example using "proper" return statements in the functions:


def temperature(t):
def celsius2fahrenheit(x):
return 9 * x / 5 + 32

result = "It's " + str(celsius2fahrenheit(t)) + " degrees!"


return result

print(temperature(20))

The output:
It's 68.0 degrees!

Lambda expressions:

The general syntax of a lambda function is quite simple:

lambda argument_list: expression

The argument list consists of a comma separated list of arguments and the expression is an
arithmetic expression using these arguments. You can assign the function to a variable to
give it a name.

The following example of a lambda function returns the sum of its two arguments:
>>> sum = lambda x, y : x + y
>>> sum(3,4)
7

The map() Function


As we have mentioned earlier, the advantage of the lambda operator can be seen when it is
used in combination with the map() function.
map() is a function which takes two arguments:

r = map(func, seq)

The first argument func is the name of a function and the second a sequence (e.g. a
list) seq. map() applies the function func to all the elements of the sequence seq. Before
Python3, map() used to return a list, where each element of the result list was the result of
the function func applied on the corresponding element of the list or tuple "seq". With
Python 3, map() returns an iterator.

The following example illustrates the way of working of map():


>>> def fahrenheit(T):
... return ((float(9)/5)*T + 32)
...
>>> def celsius(T):
... return (float(5)/9)*(T-32)
...
>>> temperatures = (36.5, 37, 37.5, 38, 39)
>>> F = map(fahrenheit, temperatures)
>>> C = map(celsius, F)
>>>
>>> temperatures_in_Fahrenheit = list(map(fahrenheit, temperatures))
>>> temperatures_in_Celsius = list(map(celsius,
temperatures_in_Fahrenheit))
>>> print(temperatures_in_Fahrenheit)
[97.7, 98.60000000000001, 99.5, 100.4, 102.2]
>>> print(temperatures_in_Celsius)

[36.5, 37.00000000000001, 37.5, 38.00000000000001, 39.0]

In the example above we haven't used lambda. By using lambda, we wouldn't have had to
define and name the functions fahrenheit() and celsius(). You can see this in the following
interactive session:
>>> C = [39.2, 36.5, 37.3, 38, 37.8]
>>> F = list(map(lambda x: (float(9)/5)*x + 32, C))
>>> print(F)
[102.56, 97.7, 99.14, 100.4, 100.03999999999999]
>>> C = list(map(lambda x: (float(5)/9)*(x-32), F))
>>> print(C)
[39.2, 36.5, 37.300000000000004, 38.00000000000001, 37.8]
>>>

Filtering
The function

filter(function, sequence)

offers an elegant way to filter out all the elements of a sequence "sequence", for which the
function function returns True. i.e. an item will be produced by the iterator result of
filter(function, sequence) if item is included in the sequence "sequence" and if
function(item) returns True.

In other words: The function filter(f,l) needs a function f as its first argument. f has to
return a Boolean value, i.e. either True or False. This function will be applied to every
element of the list l. Only if f returns True will the element be produced by the iterator,
which is the return value of filter(function, sequence).

In the following example, we filter out first the odd and then the even elements of the
sequence of the first 11 Fibonacci numbers:

>>> fibonacci = [0,1,1,2,3,5,8,13,21,34,55]


>>> odd_numbers = list(filter(lambda x: x % 2, fibonacci))
>>> print(odd_numbers)
[1, 1, 3, 5, 13, 21, 55]
>>> even_numbers = list(filter(lambda x: x % 2 == 0, fibonacci))
>>> print(even_numbers)
[0, 2, 8, 34]
>>>

The function

reduce(func, seq) :

>>> import functools


>>> functools.reduce(lambda x,y: x+y, [47,11,42,13])
113
>>>
The following diagram shows the intermediate steps of the calculation:

Examples of reduce()
Determining the maximum of a list of numerical values by using reduce:
>>> from functools import reduce
>>> f = lambda a,b: a if (a > b) else b
>>> reduce(f, [47,11,42,102,13])
102
>>>

Calculating the sum of the numbers from 1 to 100:


>>> from functools import reduce
>>> reduce(lambda x, y: x+y, range(1,101))
5050

It's very simple to change the previous example to calculate the product (the factorial) from
1 to a number, but do not choose 100. We just have to turn the "+" operator into "*":
>>> reduce(lambda x, y: x*y, range(1,49))
12413915592536072670862289047373375038521486354677760000000000
If you are into lottery, here are the chances to win a 6 out of 49 drawing:
>>> reduce(lambda x, y: x*y, range(44,50))/reduce(lambda x, y: x*y,
range(1,7))
13983816.0
>>>

The dir( ) Function


The dir() built-in function returns a sorted list of strings containing the
names defined by a module.

The list contains the names of all the modules, variables and functions that
are defined in a module. Following is a simple example −

#!/usr/bin/python3

# Import built-in module math

import math

content = dir(math)

print(content)

Importing Modules
>>> math.pi
3.141592653589793
>>> math.sin(math.pi/2)
1.0
>>> math.cos(math.pi/2)
6.123031769111886e-17
>>> math.cos(math.pi)
-1.0
from math import *
>>> sin(3.01) + tan(cos(2.1)) + e
2.2968833711382604
>>> e
2.718281828459045
>>>

Let's turn our Fibonacci functions into a module. There is hardly anything to be done, we
just save the following code in the file fibonacci.py:

def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
def ifib(n):
a, b = 0, 1
for i in range(n):
a, b = b, a + b
return a

The newly created module "fibonacci" is ready for use now. We can import this module like
any other module in a program or script. We will demonstrate this in the following
interactive Python shell:
>>> import fibonacci
>>> fibonacci.fib(7)
13
>>> fibonacci.fib(20)
6765
>>> fibonacci.ifib(42)
267914296
>>> fibonacci.ifib(1000)
434665576869374564356885276750406258025646605173717804024817290895365554179
490518904038798400792551692959225930803226347752096896232398733224711616429
96440906533187938298969649928516003704476137795166849228875
>>>

Renaming a Namespace

While importing a module, the name of the namespace can be changed:

>>> import math as mathematics


>>> print(mathematics.cos(mathematics.pi))
-1.0

After this import there exists a namespace mathematics but no namespace math.
It's possible to import just a few methods from a module:
>>> from math import pi,pow as power, sin as sinus
>>> power(2,3)
8.0
>>> sinus(pi)
1.2246467991473532e-16

What is Tick?
Time intervals are floating-point numbers in units of seconds. Particular
instants in time are expressed in seconds since 12:00am, January 1,
1970(epoch).

There is a popular time module available in Python which provides


functions for working with times, and for converting between
representations. The function time.time() returns the current system time
in ticks since 12:00am, January 1, 1970(epoch).

Example
#!/usr/bin/python3

import time;# This is required to include time module.

ticks = time.time()

print("Number of ticks since 12:00am, January 1, 1970:", ticks)

import time

print(time.localtime());

Getting formatted time


You can format any time as per your requirement, but a simple method to
get time in a readable format is asctime() −

#!/usr/bin/python3

import time
localtime = time.asctime( time.localtime(time.time()))

print("Local current time :", localtime)

This would produce the following result −


Local current time : Mon Feb 15 09:34:03 2016

Getting calendar for a month


The calendar module gives a wide range of methods to play with yearly and
monthly calendars. Here, we print a calendar for a given month ( Jan 2008
)−

#!/usr/bin/python3

import calendar

cal = calendar.month(2016,2)

print("Here is the calendar:")

print(cal)

This would produce the following result −


Here is the calendar:
February 2016
Mo Tu We Th Fr Sa Su
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29

Exception Handling in Python


n = int(input("Please enter a number: "))
Please enter a number: 23.5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '23.5'

With the aid of exception handling, we can write robust code for reading an integer from
input:
while True:
try:
n = input("Please enter an integer: ")
n = int(n)
break
except ValueError:
print("No valid integer! Please try again ...")

try:
num1, num2 = eval(input("Enter two numbers, separated by a comma : "))
result = num1 / num2
print("Result is", result)

except ZeroDivisionError:
print("Division by zero is error !!")

except SyntaxError:
print("Comma is missing. Enter numbers separated by comma like this 1, 2")

except:
print("Wrong input")

else:
print("No exceptions")

finally:
print("This will execute no matter what")
FILE Handling in Python

print the name of the file:


fo = open("D:\\local disk c\\Desktop\\abc.txt", "wb")
>>> print ("Name of the file: ", fo.name)
Name of the file: D:\local disk c\Desktop\abc.txt

Reading from a file:


fobj = open("D:\\local disk c\\Desktop\\abc.txt")
for line in fobj:
print(line.rstrip())
//close will truncate in 1st line
Writing into the file:
fo = open("D:\\local disk c\\Desktop\\abc.txt", "w")
fo.write( "Python is a great language.\nYeah its great!!\n")
fo.close()

classEmployee:

'Common base class for all employees'

empCount =0

def __init__(self, name, salary):

self.name = name

self.salary = salary

Employee.empCount +=1

def displayCount(self):

print("Total Employee %d"%Employee.empCount)

def displayEmployee(self):

print("Name : ",self.name,", Salary: ",self.salary)

#This would create first object of Employee class"

emp1 =Employee("Zara",2000)

#This would create second object of Employee class"

emp2 =Employee("Manni",5000)

emp1.displayEmployee()

emp2.displayEmployee()

print("Total Employee %d"%Employee.empCount)

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


Name : Zara ,Salary: 2000
Name : Manni ,Salary: 5000
Total Employee 2

You can add, remove, or modify attributes of classes and objects at any
time −
emp1.salary = 7000 # Add an 'salary' attribute.
emp1.name = 'xyz' # Modify 'age' attribute.
del emp1.salary # Delete 'age' attribute.

Instead of using the normal statements to access attributes, you can use
the following functions −

 The getattr(obj, name[, default]) − to access the attribute of object.

 The hasattr(obj,name) − to check if an attribute exists or not.

 The setattr(obj,name,value) − to set an attribute. If attribute does not exist,


then it would be created.

 The delattr(obj, name) − to delete an attribute.

hasattr(emp1,'salary')# Returns true if 'salary' attribute exists

getattr(emp1,'salary')# Returns value of 'salary' attribute

setattr(emp1,'salary',7000)# Set attribute 'salary' at 7000

delattr(emp1,'salary')# Delete attribute 'salary'

print("Employee.__doc__:",Employee.__doc__)

print("Employee.__name__:",Employee.__name__)

print("Employee.__module__:",Employee.__module__)

print("Employee.__bases__:",Employee.__bases__)

print("Employee.__dict__:",Employee.__dict__ )

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


Employee.__doc__: Common base class for all employees
Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: (<class 'object'>,)
Employee.__dict__: {
'displayCount': <function Employee.displayCount at 0x0160D2B8>,
'__module__': '__main__', '__doc__': 'Common base class for all employees',
'empCount': 2, '__init__':
<function Employee.__init__ at 0x0124F810>, 'displayEmployee':
<function Employee.displayEmployee at 0x0160D300>,
'__weakref__':
<attribute '__weakref__' of 'Employee' objects>, '__dict__':
<attribute '__dict__' of 'Employee' objects>
}

classParent:# define parent class

parentAttr =100

def __init__(self):

print("Calling parent constructor")

def parentMethod(self):

print('Calling parent method')

def setAttr(self, attr):

Parent.parentAttr = attr

def getAttr(self):

print("Parent attribute :",Parent.parentAttr)

classChild(Parent):# define child class

def __init__(self):

print("Calling child constructor")

def childMethod(self):

print('Calling child method')

c =Child()# instance of child

c.childMethod()# child calls its method

c.parentMethod()# calls parent's method

c.setAttr(200)# again call parent's method


c.getAttr()# again call parent's method

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


Calling child constructor
Calling child method
Calling parent method
Parent attribute : 200

Example of Inheritance in Python


To demonstrate the use of inheritance, let us take an example.

A polygon is a closed figure with 3 or more sides. Say, we have a class


called Polygondefined as follows.

classPolygon:
def __init__(self, no_of_sides):
self.n = no_of_sides
self.sides =[for i in range(no_of_sides)]

def inputSides(self):
self.sides =[float(input("Enter side "+str(i+1)+" : "))for i in
range(self.n)]

def dispSides(self):
for i in range(self.n):
print("Side",i+1,"is",self.sides[i])

This class has data attributes to store the number of sides, n and magnitude of each
side as a list, sides.

Method inputSides() takes in magnitude of each side and similarly, dispSides() will
display these properly.

A triangle is a polygon with 3 sides. So, we can created a class called Triangle which
inherits from Polygon. This makes all the attributes available in class Polygon readily
available in Triangle. We don't need to define them again (code re-
usability). Triangle is defined as follows.
classTriangle(Polygon):
def __init__(self):
Polygon.__init__(self,3)

def findArea(self):
a, b, c =self.sides
# calculate the semi-perimeter
s =(a + b + c)/2
area =(s*(s-a)*(s-b)*(s-c))**0.5
print('The area of the triangle is %0.2f'%area)

However, class Triangle has a new method findArea() to find and print the area of the
triangle. Here is a sample run.

>>> t =Triangle()

>>> t.inputSides()
Enter side 1:3
Enter side 2:5
Enter side 3:4

>>> t.dispSides()
Side1is3.0
Side2is5.0
Side3is4.0

>>> t.findArea()
The area of the triangle is6.00

Method Overriding in Python


In the above example, notice that __init__() method was defined in both
classes, Triangleas well Polygon. When this happens, the method in the derived class
overrides that in the base class. This is to say, __init__() in Triangle gets preference
over the same in Polygon.

Generally when overriding a base method, we tend to extend the definition rather than
simply replace it. The same is being done by calling the method in base class from the
one in derived class (calling Polygon.__init__() from __init__() in Triangle).

A better option would be to use the built-in function super(). So, super().__init__(3) is
equivalent to Polygon.__init__(self,3) and is preferred. You can learn more about
the super() function in Python.

Two built-in functions isinstance() and issubclass() are used to check inheritances.
Function isinstance() returns True if the object is an instance of the class or other
classes derived from it. Each and every class in Python inherits from the base
class object.

>>> isinstance(t,Triangle)
True

>>> isinstance(t,Polygon)
True

>>> isinstance(t,int)
False

>>> isinstance(t,object)
True

Similarly, issubclass() is used to check for class inheritance.

>>> issubclass(Polygon,Triangle)
False

>>> issubclass(Triangle,Polygon)
True
>>> issubclass(bool,int)
True

Data Abstraction, Data Encapsulation, and Information Hiding


Definitions of Terms

Data Abstraction, Data Encapsulation and


Information Hiding are often synonymously used in books and tutorials on OOP. But there is
a difference. Encapsulation is seen as the bundling of data with the methods that operate on
that data. Information hiding on the other hand is the principle that some internal
information or data is "hidden", so that it can't be accidentally changed. Data encapsulation
via methods doesn't necessarily mean that the data is hidden. You might be capable of
accessing and seeing the data anyway, but using the methods is recommended. Finally,
data abstraction is present, if both data hiding and data encapsulation is used. This means
data abstraction is the broader term:

Data Abstraction = Data Encapsulation + Data Hiding

Encapsulation is often accomplished by providing two kinds of methods for attributes: The
methods for retrieving or accessing the values of attributes are called getter methods.
Getter methods do not change the values of attributes, they just return the values. The
methods used for changing the values of attributes are called setter methods.

We will define now a Robot class with a Getter and a Setter for the name attribute. We will
call them get_name and set_name accordingly.

class Robot:

def __init__(self, name=None):


self.name = name

def say_hi(self):
if self.name:
print("Hi, I am " + self.name)
else:
print("Hi, I am a robot without a name")

def set_name(self, name):


self.name = name

def get_name(self):
return self.name

x = Robot()
x.set_name("Henry")
x.say_hi()
y = Robot()
y.set_name(x.get_name())
print(y.get_name())

Hopefully, it will be easy for you to see, that this program prints the following:
Hi, I am Henry
Henry

Before you go on, you can do a little exercise. You can add an additional attribute
"build_year" with Getters and Setters to the Robot class.
class Robot:

def __init__(self,
name=None,
build_year=None):
self.name = name
self.build_year = build_year

def say_hi(self):
if self.name:
print("Hi, I am " + self.name)
else:
print("Hi, I am a robot without a name")
if self.build_year:
print("I was built in " + str(self.build_year))
else:
print("It's not known, when I was created!")

def set_name(self, name):


self.name = name

def get_name(self):
return self.name

def set_build_year(self, by):


self.build_year = by

def get_build_year(self):
return self.build_year

x = Robot("Henry", 2008)
y = Robot()
y.set_name("Marvin")
x.say_hi()
y.say_hi()

The program returns the following output:


Hi, I am Henry
I was built in 2008
Hi, I am Marvin
It's not known, when I was created!
class Robot:

def __init__(self, name, build_year):


self.name = name
self.build_year = build_year
def __repr__(self):
return "Robot(\"" + self.name + "\"," + str(self.build_year) +
")"

def __str__(self):
return "Name: " + self.name + ", Build Year: " +
str(self.build_year)

if __name__ == "__main__":
x = Robot("Marvin", 1979)

x_repr = repr(x)
print(x_repr, type(x_repr))
new = eval(x_repr)
print(new)
print("Type of new:", type(new))

The output looks like this:

$ python3 robot_class6b.py
Robot("Marvin",1979) <class 'str'>
Name: Marvin, Build Year: 1979
Type of new: <class '__main__.Robot'>
class Robot:

def __init__(self, name=None, build_year=2000):


self.__name = name
self.__build_year = build_year

def say_hi(self):
if self.__name:
print("Hi, I am " + self.__name)
else:
print("Hi, I am a robot without a name")
def set_name(self, name):
self.__name = name

def get_name(self):
return self.__name

def set_build_year(self, by):


self.__build_year = by

def get_build_year(self):
return self.__build_year

def __repr__(self):
return "Robot('" + self.__name + "', " + str(self.__build_year) +
")"

def __str__(self):
return "Name: " + self.__name + ", Build Year: " +
str(self.__build_year)

if __name__ == "__main__":
x = Robot("Marvin", 1979)
y = Robot("Caliban", 1943)
for rob in [x, y]:
rob.say_hi()
if rob.get_name() == "Caliban":
rob.set_build_year(1993)
print("I was built in the year " + str(rob.get_build_year()) + "!")

We get the following out, if we call this program:

Hi, I am Marvin
I was built in the year 1979!
Hi, I am Caliban
I was built in the year 1993!
class ComplexNumber:
def __init__(self,r = 0,i = 0):
self.real = r
self.imag = i

def getData(self):
print("{0}+{1}j".format(self.real,self.imag))

# Create a new ComplexNumber object


c1 = ComplexNumber(2,3)

# Call getData() function


# Output: 2+3j
c1.getData()

# Create another ComplexNumber object


# and create a new attribute 'attr'
c2 = ComplexNumber(5)
c2.attr = 10

# Output: (5, 0, 10)


print((c2.real, c2.imag, c2.attr))

Destructor
What we said about constructors holds true for destructors as well. There is no "real"
destructor, but something similar, i.e. the method __del__. It is called when the instance is
about to be destroyed and if there is no other reference to this instance. If a base class has
a __del__() method, the derived class's __del__() method, if any, must explicitly call it to
ensure proper deletion of the base class part of the instance.

The following script is an example with __init__ and __del__:

class Robot():
def __init__(self, name):
print(name + " has been created!")

def __del__(self):
print ("Robot has been destroyed")

if __name__ == "__main__":
x = Robot("Tik-Tok")
y = Robot("Jenkins")
z = x
print("Deleting x")
del x
print("Deleting z")
del z
del y

The output of the previous program:

$ python3 del_example.py
Tik-Tok has been created!
Jenkins has been created!
Deleting x
Deleting z
Robot has been destroyed
Robot has been destroyed

The new method creates and returns the new class object, and after this the init method
initializes the newly created object.

class Robot:
counter = 0
def __init__(self, name):
self.name = name
def sayHello(self):
return "Hi, I am " + self.name
def Rob_init(self, name):
self.name = name
Robot2 = type("Robot2",
(),
{"counter":0,
"__init__": Rob_init,
"sayHello": lambda self: "Hi, I am " + self.name})
x = Robot2("Marvin")
print(x.name)
print(x.sayHello())
y = Robot("Marvin")
print(y.name)
print(y.sayHello())
print(x.__dict__)
print(y.__dict__)

The previous Python code returned the following result:

Marvin
Hi, I am Marvin
Marvin
Hi, I am Marvin
{'name': 'Marvin'}
{'name': 'Marvin'}

''' Program make a simple calculator that can add, subtract, multiply and
divide using functions '''

# This function adds two numbers


def add(x, y):
return x + y

# This function subtracts two numbers


def subtract(x, y):
return x - y

# This function multiplies two numbers


def multiply(x, y):
return x * y

# This function divides two numbers


def divide(x, y):
return x / y

print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

# Take input from the user


choice = input("Enter choice(1/2/3/4):")

num1 = int(input("Enter first number: "))


num2 = int(input("Enter second number: "))

if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))

elif choice == '2':


print(num1,"-",num2,"=", subtract(num1,num2))

elif choice == '3':


print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")

# Python program to find the largest number among the three input numbers

# change the values of num1, num2 and num3


# for a different result
num1 = 10
num2 = 14
num3 = 12

# uncomment following lines to take three numbers from user


#num1 = float(input("Enter first number: "))
#num2 = float(input("Enter second number: "))
#num3 = float(input("Enter third number: "))

if (num1 >= num2) and (num1 >= num3):


largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3

print("The largest number between",num1,",",num2,"and",num3,"is",largest)

# Program to sort alphabetically the words form a string provided by the user

# change this value for a different result

my_str = "Hello this Is an Example With cased letters"


# uncomment to take input from the user

#my_str = input("Enter a string: ")

# breakdown the string into a list of words

words = my_str.split()

# sort the list

words.sort()

# display the sorted words

print("The sorted words are:")

for word in words:

print(word)

Regular expressions:

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

"easily" is a substring of the string "Regular expressions easily explained!":


>>> s = "Regular expressions easily explained!"
>>> "easily" in s
True

pattern = "Cookie"

sequence = "Cookie"

if re.match(pattern, sequence):

print("Match!")

else: print("Not a match!")

Example
import re
# Lets use a regular expression to match a date string. Ignore
# the output since we are just testing if the regex matches.
regex = r"([a-zA-Z]+) (\d+)"
if re.search(regex, "June 24"):
# Indeed, the expression "([a-zA-Z]+) (\d+)" matches the date string

# If we want, we can use the MatchObject's start() and end() methods


# to retrieve where the pattern matches in the input string, and the
# group() method to get all the matches and captured groups.
match = re.search(regex, "June 24")

# This will print [0, 7), since it matches at the beginning and end of the
# string
print("Match at index %s, %s" % (match.start(), match.end()))

# The groups contain the matched values. In particular:


# match.group(0) always returns the fully matched string
# match.group(1), match.group(2), ... will return the capture
# groups in order from left to right in the input string
# match.group() is equivalent to match.group(0)

# So this will print "June 24"


print("Full match: %s" % (match.group(0)))
# So this will print "June"
print("Month: %s" % (match.group(1)))
# So this will print "24"
print("Day: %s" % (match.group(2)))
else:
# If re.search() does not match, then None is returned
print("The regex pattern does not match. :(")

Example
#!/usr/bin/python

import re

line ="Cats are smarter than dogs";

searchObj = re.search( r'(.*) are (.*?) .*', line, re.M|re.I)


if searchObj:

print"searchObj.group() : ", searchObj.group()

print"searchObj.group(1) : ", searchObj.group(1)

print"searchObj.group(2) : ", searchObj.group(2)

else:

print"Nothing found!!"

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


searchObj.group() : Cats are smarter than dogs
searchObj.group(1) : Cats
searchObj.group(2) : smarter

import re

phone ="2004-959-559 # This is Phone Number"

# Delete Python-style comments

num = re.sub(r'#.*$',"", phone)

print"Phone Num : ", num

# Remove anything other than digits

num = re.sub(r'\D',"", phone)

print"Phone Num : ", num

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


Phone Num : 2004-959-559
Phone Num : 2004959559

Example of w+ and ^ Expression


 "^": This expression matches the start of a string
 "w+": This expression matches the alphanumeric character in the string

xx="happy100 is fine"
>>> rl=re.findall(r"^\w+",xx)
>>> print(rl)
['happy100']
text=”software testing is easy to learn”
patterns = ['software testing', 'abcd']

>>> for pattern in patterns:

print('Looking for "%s" in "%s" ->' % (pattern, text), end=' ')

if re.search(pattern, text):

print('found a match!')

else:

print('no match')

Looking for "software testing" in "software testing is fun?" -> found a


match!

Looking for "abcd" in "software testing is fun?" -> no match

abc = 'guru99@google.com, careerguru99@hotmail.com, users@yahoomail.com'

>>> emails = re.findall(r'[\w\.-]+@[\w\.-]+', abc)

>>> for email in emails:

print(email)

guru99@google.com

careerguru99@hotmail.com

users@yahoomail.com

The threading module


Using threads allows a program to run multiple operations concurrently in the
same process space. Through out this tutorials, we'll be
using threading module. Note that there is another module
called thread which has been renamed to _thread in Python 3. Actually,
the threading module constructs higher-level threading interfaces on top of
the lower level _thread module. We rarely touch the low
level _thread module.

import threading

def f():

print ("thread function")

return

if __name__ == '__main__':

for i in range(3):

t = threading.Thread(target=f)

t.start()

Passing parameters
To make a thread more useful, we want to pass args to give more information
about the work. The code below passes an integer for thread id, and then the
thread prints it. The args is the argument tuple for the target invocation.
Defaults to ().

import threading

def f(id):

print ('thread function %s' %(id))

return

if __name__ == '__main__':

for i in range(3):

t = threading.Thread(target=f, args=(i,))

t.start()
import threading

import datetime

class myThread (threading.Thread):

def __init__(self, name, counter):

threading.Thread.__init__(self)

self.threadID = counter

self.name = name

self.counter = counter

def run(self):

print ("Starting " + self.name)

print_date(self.name, self.counter)

print ("Exiting " + self.name)

def print_date(threadName, counter):

datefields = []

today = datetime.date.today()

datefields.append(today)

print ("%s[%d]: %s" % ( threadName, counter, datefields[0] ))

# Create new threads

thread1 = myThread("Thread", 1)

thread2 = myThread("Thread", 2)

# Start new Threads

thread1.start()

thread2.start()

thread1.join()

thread2.join()

print ("Exiting the Program!!!")


import threading

import datetime

exitFlag = 0

class myThread (threading.Thread):

def __init__(self, name, counter):

threading.Thread.__init__(self)

self.threadID = counter

self.name = name

self.counter = counter

def run(self):

print ("Starting " + self.name)

# Acquire lock to synchronize thread

threadLock.acquire()

print_date(self.name, self.counter)

# Release lock for the next thread

threadLock.release()

print ("Exiting " + self.name)

def print_date(threadName, counter):

datefields = []

today = datetime.date.today()

datefields.append(today)

print ("%s[%d]: %s" % ( threadName, counter, datefields[0] ))

threadLock = threading.Lock()

threads = []

# Create new threads

thread1 = myThread("Thread", 1)
thread2 = myThread("Thread", 2)

# Start new Threads

thread1.start()

thread2.start()

# Add threads to thread list

threads.append(thread1)

threads.append(thread2)

# Wait for all threads to complete

for t in threads:

t.join()

print ("Exiting the Program!!!")

Generator Functions:
Let's look at the interactive example below:

>>> def create_counter(n):


print('create_counter()')
while True:
yield n
print('increment n')
n += 1

>>> c = create_counter(2)
>>> c
<generator object create_counter at 0x03004B48>
>>> next(c)
create_counter()
2
>>> next(c)
increment n
3
>>> next(c)
increment n
4
>>>

Here are the things happening in the code:

1. The presence of the yield keyword in create_counter() means that this is not
a normal function. It is a special kind of function which generates values one
at a time. We can think of it as a resumable function. Calling it will return
a generator that can be used to generate successive values of n.
2. To create an instance of the create_counter() generator, just call it like any
other function. Note that this does not actually execute the function code. We
can tell this because the first line of the create_counter() function
calls print(), but nothing was printed from the line:

3. >>> c = create_counter(2)

4. The create_counter() function returns a generator object.


5. The next() function takes a generator object and returns its next value. The
first time we call next() with the counter generator, it executes the code
in create_counter() up to the first yield statement, then returns the value that
was yielded. In this case, that will be 2, because we originally created the
generator by calling create_counter(2).
6. Repeatedly calling next() with the same generator object resumes exactly
where it left off and continues until it hits the next yield statement. All
variables, local state, &c.; are saved on yield and restored on next(). The next
line of code waiting to be executed calls print(), which prints increment n.
After that, the statement n += 1. Then it loops through the while loop again,
and the first thing it hits is the statement yield n, which saves the state of
everything and returns the current value of n (now 3).
7. The second time we call next(c), we do all the same things again, but this
time n is now 4.
8. Since create_counter() sets up an infinite loop, we could theoretically do this
forever, and it would just keep incrementing n and spitting out values.

Iterators
In computer science, an iterator is an object that allows a programmer to
traverse through all the elements of a collection regardless of its specific
implementation.

1. iterable produces iterator via __iter__()

iterator = iterable.__iter__()

2. iterator produces a stream of values via next()

value = iterator.next()
value = iterator.next()
...

To be more specific, we can start from an iterable, and we know a list (e.g,
[1,2,3]) is iterable. iter(iterable) produces an iterater, and from this we can
get stream of values.
>>> # Python 3
>>> iterable = [1,2,3]
>>> iterator = iterable.__iter__() # or iterator =
iter(iterable)
>>> type(iterator)
<type 'listiterator'>
>>> value = iterator.__next__() # or value = next(iterator)
>>> print(value)
1
>>> value = next(iterator)
>>> print(value)
2

Python Closures
3
Before seeing what a closure is, we have to first understand what are nested functions and non-local
variables.

Nested functions in Python


A function which is defined inside another function is known as nested function. Nested functions are able
to access variables of the enclosing scope.
In Python, these non-local variables can be accessed only within their scope and not outside their scope.
This can be illustrated by following example:
# Python program to illustrate

# nested functions

defouterFunction(text):

text =text

definnerFunction():

print(text)

innerFunction()

if__name__ =='__main__':

outerFunction('Hey!')

Run on IDE
As we can see innerFunction() can easily be accessed inside the outerFunction body but not outside of
it’s body. Hence, here, innerFunction() is treated as nested Function which uses textas non-local
variable.
Python Closures
A Closure is a function object that remembers values in enclosing scopes even if they are not present in
memory.
 It is a record that stores a function together with an environment: a mapping associating each free
variable of the function (variables that are used locally, but defined in an enclosing scope) with the
value or reference to which the name was bound when the closure was created.
 A closure—unlike a plain function—allows the function to access those captured variables through
the closure’s copies of their values or references, even when the function is invoked outside their
scope.
# Python program to illustrate

# closures

defouterFunction(text):

text =text

definnerFunction():

print(text)

returninnerFunction # Note we are returning function WITHOUT parenthesis


if__name__ =='__main__':

myFunction =outerFunction('Hey!')

myFunction()

Run on IDE

Output:

omkarpathak@omkarpathak-Inspiron-3542:

~/Documents/Python-Programs/$ python Closures.py

Hey!

1. As observed from above code, closures help to invoke function outside their scope.
2. The function innerFunction has its scope only inside the outerFunction. But with the use of
closures we can easily extend its scope to invoke a function outside its scope.
When and why to use Closures:
1. As closures are used as callback functions, they provide some sort of data hiding. This helps us to
reduce the use of global variables.
2. When we have few functions in our code, closures prove to be efficient way. But if we need to have
many functions, then go for class (OOP).

To check mysql.connector installation:


import mysql.connector
>>>
mysql.connector.connect(host='localhost',databa
se='mysql',user='root',password='abc')
<mysql.connector.connection.MySQLConnectio
n object at 0x03106430>
Connecting to database:

Create table in python:


Module:

import mysql.connector

from mysql.connector import Error

def connect():

""" Connect to MySQL database """

try:

conn = mysql.connector.connect(host='localhost',

database='python',

user='root',

password='abc')

if conn.is_connected():

print('Connected to MySQL database')

cursor = conn.cursor()

cursor.execute("SELECT * FROM books")

row = cursor.fetchone()

while row is not None:

print(row)

row = cursor.fetchone()

except Error as e:

print(e)
finally:

cursor.close()

conn.close()

if __name__ == '__main__':

connect()

connect with fetch all:

import mysql.connector

from mysql.connector import Error

def connect():

""" Connect to MySQL database """

try:

conn = mysql.connector.connect(host='localhost',

database='python',

user='root',

password='abc')

if conn.is_connected():

print('Connected to MySQL database')

cursor = conn.cursor()

cursor.execute("SELECT * FROM books")

rows = cursor.fetchall()

print('Total Row(s):', cursor.rowcount)

for row in rows:

print(row)
except Error as e:

print(e)

finally:

cursor.close()

conn.close()

if __name__ == '__main__':

connect()

Querying data with fetchmany


For a relatively big table, it takes time to fetch all rows and return the result set. In
addition, fetchall() needs to allocate enough memory to store the entire result set in the
memory. This is inefficient and not a good practice.
MySQL Connector/Python provides us with the fetchmany() method that returns the next
number of rows (n) of the result set, which allows us to balance between time and memory
space. Let’s take a look at how do we use fetchmany() method.
import mysql.connector

from mysql.connector import Error

def iter_row(cursor, size=10):

while True:

rows = cursor.fetchmany(size)

if not rows:

break

for row in rows:

yield row

def connect():

""" Connect to MySQL database """

try:

conn = mysql.connector.connect(host='localhost',
database='python',

user='root',

password='abc')

if conn.is_connected():

print('Connected to MySQL database')

cursor = conn.cursor()

cursor.execute("SELECT * FROM books")

for row in iter_row(cursor, 10):

print(row)

except Error as e:

print(e)

finally:

cursor.close()

conn.close()

if __name__ == '__main__':

connect()

Python MySQL Insert Data


import mysql.connector

from mysql.connector import Error

def insert_book(book_id,book_name,book_price):

query = "INSERT INTO books(book_id,book_name,book_price) " \

"VALUES(%s,%s,%s);"

args = (book_id,book_name,book_price)

try:
conn = mysql.connector.connect(host='localhost',

database='python',

user='root',

password='abc')

if conn.is_connected():

print('Connected to MySQL database')

cursor = conn.cursor()

cursor.execute(query, args)

conn.commit()

except Error as e:

print(e)

finally:

cursor.close()

conn.close()

def main():

insert_book('15','geography','7600')

insert_book('16','geoscience','9600')

print('inserted successfully')

if __name__ == '__main__':

main()

Você também pode gostar