0% found this document useful (0 votes)
18 views70 pages

Variable Declaration Python

Uploaded by

Techni Hemanth
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
18 views70 pages

Variable Declaration Python

Uploaded by

Techni Hemanth
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 70

Chapter 1

Introduction to Python

What is Python?
Python is a popular programming language. It was created by Guido van Rossum, and
released in 1991.

It is used for:

 web development (server-side),


 software development,
 mathematics,
 system scripting.

What can Python do?


 Python can be used on a server to create web applications.
 Python can be used alongside software to create workflows.
 Python can connect to database systems. It can also read and modify files.
 Python can be used to handle big data and perform complex mathematics.
 Python can be used for rapid prototyping, or for production-ready software
development.

Why Python?
 Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
 Python has a simple syntax similar to the English language.
 Python has syntax that allows developers to write programs with fewer lines than
some other programming languages.
 Python runs on an interpreter system, meaning that code can be executed as soon as
it is written. This means that prototyping can be very quick.
 Python can be treated in a procedural way, an object-oriented way or a functional
way.
Python Syntax compared to other programming languages
 Python was designed for readability, and has some similarities to the English
language with influence from mathematics.
 Python uses new lines to complete a command, as opposed to other programming
languages which often use semicolons or parentheses.
 Python relies on indentation, using whitespace, to define scope; such as the scope of
loops, functions and classes. Other programming languages often use curly-brackets
for this purpose.

Chapter-2
Variable Declaration
Variables are containers for storing data values.

 A variable name must start with a letter or the underscore character


 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
 Variable names are case-sensitive (age, Age and AGE are three different variables)

Creating Variables
Python has no command for declaring a variable.

Getting the Data Type


You can get the data type of any object by using the type() function:

Example:1
x = 5
y = "John"
print(type(x))
print(type(y))
Example:2
x = "John"

print(x)

#double quotes are the same as single quotes:

x = 'John'

print(x)

Example: 3
a=4

A = "Sally"

Print (a)

Print (A)

Example: 4
myvar = "John"

my_var = "John"

_my_var = "John"

myVar = "John"

MYVAR = "John"

myvar2 = "John"

print(myvar)

print(my_var)

print(_my_var)

print(myVar)

print(MYVAR)

print(myvar2)

Example:5
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)

Example :6

x = str(3)

y = int(3)

z = float(3)

print(x)

print(y)

print(z)

String
Strings in python are surrounded by either single quotation marks, or double quotation marks.

'hello' is the same as "hello".

You can display a string literal with the print() function:

Example:1
print("Hello")
print('Hello')

Example:2
a = "Hello"

print(a)

Python List
Lists are used to store multiple items in a single variable.

Lists are one of 4 built-in data types in Python used to store collections of data, the other 3
are Tuple, Set, and Dictionary, all with different qualities and usage.

Lists are created using square brackets:

Example:1
thislist = ["apple", "banana", "cherry"]
print(thislist)

Python Tuple
Tuples are used to store multiple items in a single variable.

Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set,
and Dictionary, all with different qualities and usage.

A tuple is a collection which is ordered and unchangeable.

Tuples are written with round brackets.

Example:1
thistuple = ("apple", "banana", "cherry")

print(thistuple[-1])

Example:2
thistuple = ("apple", "banana", "cherry")

print(thistuple[1])

Python Set
Sets are used to store multiple items in a single variable.

Set is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Tuple,
and Dictionary, all with different qualities and usage.

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

Sets are written with curly brackets.

Example:1
thisset = {"apple", "banana", "cherry"}

print(thisset)

Python Dictionary
Dictionaries are used to store data values in key:value pairs.

A dictionary is a collection which is ordered*, changeable and does not allow duplicates.
Example:1
thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

print(thisdict)

Python Operators [CH-3]

Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:

Example
print(10 + 5)

Types
 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Identity operators
 Membership operators
 Bitwise operators

1.Arithmetic Operators
Arithmetic operators are used with numeric values to perform common mathematical operations:

Operator Name Example

+ Addition x+y

- Subtraction x-y

* Multiplication x*y

/ Division x/y

% Modulus x%y

** Exponentiation x ** y

// Floor division x // y

Example:1

x=5

y=3

print(x + y)
2.comparsion operators

Comparison operators are used to compare two values:

Operator Name Example

== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or x >= y

equal to

<= Less than or equal x <= y

to

Example:1

x=5

y=3

print(x == y)
3.Logical Operators

Logical operators are used to combine conditional statements:

Operator Description Example

and Returns True if both statements are x < 5 and x <

true 10

or Returns True if one of the x < 5 or x < 4

statements is true

not Reverse the result, returns False if not(x < 5 and

the result is true x < 10)

Example:1
x=5

print(x > 3 and x < 10)

4.Bitwis Operators

Bitwise operators are used to compare (binary) numbers:

Example:1
X=5

Y=12

Z=x*y

Print(z)
5.Assignment Operator

Assignment operators are used to assign values to variables:

Operator Example Same As

= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

//= x //= 3 x = x // 3

**= x **= 3 x = x ** 3

&= x &= 3 x=x&3


|= x |= 3 x=x|3

^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3

Example:1

x=5

x -= 3

print(x)

6.Identity Operator

Identity operators are used to compare the objects, not if they are equal, but if they are actually the
same object, with the same memory location:

Operator Description Example

is Returns True if both variables x is y

are the same object

is not Returns True if both variables x is not y

are not the same object


Example:1

(is)
x = ["apple", "banana"]

y = ["apple", "banana"]

z=x

print(x is z)

print(x is y)

print(x == y)

Example:2
(is not)

x = ["apple", "banana"]

y = ["apple", "banana"]

z=x

print(x is not z)

7.Membership operators

Membership operators are used to test if a sequence is presented in an object:

Operator Description Example

in Returns True if a sequence with the x in y

specified value is present in the object

not in Returns True if a sequence with the x not in y

specified value is not present in the

object

Example
x = ["apple", "banana"]

print("banana" in x)

# returns True because a sequence with the value "banana" is in the list

Example 2

x = ["apple", "banana"]

print("pineapple" not in x)

# returns True because a sequence with the value "pineapple" is not in the list

Chapter 4
Condition Execution
If Statement

Only condition is true statement is executed.

Example:1
a = 33

b = 200

if b > a:

print("b is greater than a")


If Else Statement

Only condition is true then else is executed

Example:1

a = 200

b = 33

if b > a:

print("b is greater than a")

else:

print("b is not greater than a")

If Elif Statement
The elif keyword is pythons way of saying "if the previous conditions were not true, then
try this condition".

Example:1

a = 33

b = 33

if b > a:

print("b is greater than a")

elif a == b:

print("a and b are equal")

Nested if Statement
You can have if statements inside if statements, this is called nested if statements.

Example:1

a = 200

b = 33

if b > a:

print("b is greater than a")

elif a == b:
print("a and b are equal")

else:

print("a is greater than b")

Iteration
For loop
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a
set, or a string).

Example:1

fruits = ["apple", "banana", "cherry"]

for x in fruits:

print(x)

Range () Function

The range() function returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and stops before a specified number.

Example:1

x = range(6)

for n in x:

print(n)

For loop with Else


Example:1

for x in range(6):

print(x)

else:

print("Finally finished!")

While loop
With the while loop we can execute a set of statements as long as a condition is true.

Example:1

i = 1
while i < 6:
print(i)
i += 1

While loop with Else


Example:1

i = 1

while i < 6:

print(i)

i += 1

else:

print("i is no longer than 6")

Break statement
With the break statement we can stop the loop even if the while condition is true:

Example:1

i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1

Continue Statement
With the continue statement we can stop the current iteration, and continue with the next:

Example:1

for i in range(9):

if i == 3:

continue

print(i)
CHAPTER 5
PYTHON FUNCTION
Function is a group of related statements.
Creating a Function

In Python a function is defined using the def keyword:


def my_function():
print("Hello from a function")

Calling a Function
def my_function():

print("Hello from a function")

my_function()

Arguments

Information can be passed into functions as arguments.


Arguments are specified after the function name, inside the parentheses.

def my_function(fname):
print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")

Number of Arguments

This function expects 2 arguments, and gets 2 arguments:

def my_function(fname, lname):


print(fname + " " + lname)

my_function("Emil", "Refsnes")

Return Statement

It is used to exit function.


def my_function(x):
return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))

Keyword Arguments,

You can also send arguments with the key = value syntax.

Example:

def my_function(child3, child2, child1):


print("The youngest child is " + child3)

my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")

Arbitrary Arguments, *args

If the number of arguments is unknown, add a * before the parameter name:

Example:

def my_function(*kids):
print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")

Local Scope:
A variable created inside a function belongs to the local scope of that function, and
can only be used inside that function.

Example:

def myfunc():
x = 300
print(x)

myfunc()

Global Scope:

A variable created outside of a function is global and can be used by anyone:

x = 300
def myfunc():
print(x)
myfunc()
print(x)

Python Lambda

A lambda function can take any number of arguments, but can only have one
expression.

Example:1

x = lambda a: a + 10
print(x(5))

Example 2:

x = lambda a, b, c: a + b + c
print(x(5, 6, 2))

Python Recursive Function:


Recursive is a common mathematical and programming concept. It means
that a function calls itself.

Example:

#Import math Library


import math

#Return factorial of a number


print(math.factorial(9))
print(math.factorial(6))
print(math.factorial(12))

o/p
362880
720
479001600

CHAPTER-6

PYTHON MODULES

MODULES:

A file containing a set of functions you want to include in your application.

Creating modules:

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")

Variables in Module

The module can contain functions, as already described, but also variables of all types

(arrays, dictionaries, objects etc):

person1 = {

"name": "John",

"age": 36,

"country": "Norway"

}
import mymodule

a = mymodule.person1["age"]
print(a)

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:

import platform

x = dir(platform)
print(x)

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"])

Type Conversion

You can convert from one type to another with the int(), float(), and complex() methods:

EXAMPLE:

#convert from int to float:


x = float(1)

#convert from float to int:


y = int(2.8)

#convert from int to complex:


z = complex(x)

print(x)
print(y)
print(z)

print(type(x))
print(type(y))
print(type(z))
Python Math

Python has a set of built-in math functions, including an extensive math module, that allows
you to perform mathematical tasks on numbers.

Built-in Math Functions

The min() and max() functions can be used to find the lowest or highest value in an iterable:

EXAMPLE:

x = min(5, 10, 25)


y = max(5, 10, 25)

print(x)
print(y)

CHAPTER-7

SEQUENCES

List

mylist = ["apple", "banana", "cherry"]

Lists are used to store multiple items in a single variable.

Lists are one of 4 built-in data types in Python used to store collections of data, the other 3
are Tuple, Set, and Dictionary, all with different qualities and usage.

Lists are created using square brackets:

Example
thislist = ["apple", "banana", "cherry"]
print(thislist)

Allow Duplicates

Since lists are indexed, lists can have items with the same value:

thislist = ["apple", "banana", "cherry", "apple", "cherry"]

print(thislist)

List Length

To determine how many items a list has, use the len() function:

thislist = ["apple", "banana", "cherry"]


print(len(thislist))

type()

From Python's perspective, lists are defined as objects with the data type 'list':

mylist = ["apple", "banana", "cherry"]

print(type(mylist))

Python Collections (Arrays)

 List is a collection which is ordered and changeable. Allows duplicate members.


 Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
 Set is a collection which is unordered and unindexed. No duplicate members.
 Dictionary is a collection which is ordered* and changeable. No duplicate members.

Access Items

List items are indexed and you can access them by referring to the index number:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])

Negative Indexing

Negative indexing means start from the end

-1 refers to the last item, -2 refers to the second last item etc.

thislist = ["apple", "banana", "cherry"]


print(thislist[-1])

Range of Indexes

You can specify a range of indexes by specifying where to start and where to end the range.

When specifying a range, the return value will be a new list with the specified items.

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


print(thislist[2:5])

#This will return the items from position 2 to 5.

#Remember that the first item is position 0,


#and note that the item in position 5 is NOT included

Python Arrays

Arrays are used to store multiple values in one single variable:

Example:

cars = ["Ford", "Volvo", "BMW"]


Access the Elements of an Array

cars = ["Ford", "Volvo", "BMW"]

x = cars[0]

print(x)

The Length of an Array

Use the len() method to return the length of an array (the number of elements in an array).
cars = ["Ford", "Volvo", "BMW"]

x = len(cars)

print(x)

Looping Array Elements

You can use the for in loop to loop through all the elements of an array.
cars = ["Ford", "Volvo", "BMW"]

for x in cars:
print(x)

Adding Array Elements

You can use the append() method to add an element to an array.


cars = ["Ford", "Volvo", "BMW"]

cars.append("Honda")

print(cars)

Removing Array Elements

You can use the pop() method to remove an element from the array.

Delete the second element of the cars array:

cars = ["Ford", "Volvo", "BMW"]


cars.pop(1)

print(cars)

CHAPTER-7
PYTHON STRINGS,SETS & DICTIONARY

Strings in python are surrounded by either single quotation marks, or double quotation
marks.

'hello' is the same as "hello".

You can display a string literal with the print() function:

print("Hello")

print('Hello')

Assign String to a Variable

Assigning a string to a variable is done with the variable name followed by an equal sign and
the string:

a = "Hello"

print(a)
Multiline Strings

You can assign a multiline string to a variable by using three quotes:

a = """Lorem ipsum dolor sit amet,

consectetur adipiscing elit,

sed do eiusmod tempor incididunt

ut labore et dolore magna aliqua."""

print(a)

String Length

To get the length of a string, use the len() function.

The len() function returns the length of a string:

a = "Hello, World!"

print(len(a))

Python String Methods

Capitalize:

txt = "hello, and welcome to my world."

x = txt.capitalize()

print (x)

upper:
txt = "THIS IS NOW!"

x = txt.isupper()

print(x)

join

string.join(iterable) ->syntax

myTuple = ("John", "Peter", "Vicky")

x = "#".join(myTuple)

print(x)

Python String Formatting

String format()

The format() method allows you to format selected parts of a string.

price = 49

txt = "The price is {} dollars"

print(txt.format(price))

Python Sets

Sets are used to store multiple items in a single variable.

thisset = {"apple", "banana", "cherry"}

print(thisset)

Duplicates Not Allowed


Sets cannot have two items with the same value.

thisset = {"apple", "banana", "cherry", "apple"}

print(thisset)

Get the Length of a Set

To determine how many items a set has, use the len() method

thisset = {"apple", "banana", "cherry"}

print(len(thisset))

Python - Remove Set Items

To remove an item in a set, use the remove(), or the discard() method.

thisset = {"apple", "banana", "cherry"}

thisset.remove("banana")

print(thisset)

Python Dictionaries

Dictionaries are used to store data values in key:value pairs.

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
CHAPTER-8
PYTHON FILE I/O

File handling is an important part of any web application.

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

File Handling

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

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

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

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

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

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

"x" - Create - Creates the specified file, returns an error if the file exists
"t" - Text - Default value. Text mode

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

f = open("demofile.txt")

Open a File on the Server


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

demofile.txt

Hello! Welcome to demofile.txt


This file is for testing purposes.
Good Luck!

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

The open() function returns a file object, which has a read() method for reading the content of the file:

Example

f = open("demofile.txt", "r")

print(f.read())
Example 1
If the file is located in a different location, you will have to specify the file path, like this:

f = open("D:\\myfiles\welcome.txt", "r")

print(f.read())

Read Only Parts of the File

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

want to return:
Example

f = open("demofile.txt", "r")

print(f.read(5))

Read Lines

You can return one line by using the readline() method:

Example

f = open("demofile.txt", "r")
print(f.readline())

Example 1

Read two lines of the file:

f = open("demofile.txt", "r")

print(f.readline())

print(f.readline())

Python Directory

If there are a large number of files to handle in our Python program, we can arrange our code
within different directories to make things more manageable.

Get Current Directory

We can get the present working directory using the getcwd() method of the os module.
This method returns the current working directory in the form of a string. We can also use
the getcwdb() method to get it as bytes object.

>>> import os
>>> os.getcwd()
'C:\\Program Files\\PyScripter'

>>> os.getcwdb()
b'C:\\Program Files\\PyScripter'

Changing Directory

We can change the current working directory by using the chdir() method.

>>> os.chdir('C:\\Python33')

>>> print(os.getcwd())
C:\Python33

List Directories and Files

All files and sub-directories inside a directory can be retrieved using the listdir() method.

>>> print(os.getcwd())
C:\Python33

>>> os.listdir()
['DLLs',
'Doc',
'include',
'Lib',
'libs',
'LICENSE.txt',
'NEWS.txt',
'python.exe',
'pythonw.exe',
'README.txt',
'Scripts',
'tcl',
'Tools']

>>> os.listdir('G:\\')
['$RECYCLE.BIN',
'Movies',
'Music',
'Photos',
'Series',
'System Volume Information']

Making a New Directory

We can make a new directory using the mkdir() method

Import os->import header

>>> os.mkdir('test')

>>> os.listdir()
['test']

Renaming a Directory or a File

The rename() method can rename a directory or a file.

>>> os.listdir()
['test']

>>> os.rename('test','new_one')

>>> os.listdir()
['new_one']

Removing Directory or File

A file can be removed (deleted) using the remove() method.

>>> os.listdir()
['new_one', 'old.txt']

>>> os.remove('old.txt')
>>> os.listdir()
['new_one']

>>> os.rmdir('new_one')
>>> os.listdir()
[]

CHAPTER-9
PYTHON ERRORS AND BULIT-IN EXCEPTION
The try block lets you test a block of code for errors.

The except block lets you handle the error.

The finally block lets you execute code.

Exception Handling
When an error occurs, or exception as we call it, Python will normally stop and generate an
error message.

Example

The try block will generate an exception, because x is not defined:

try:
print(x)
except:
print("An exception occurred")

1. Syntax errors ->not proper structure

2. Logical errors (Exceptions)->run time error

Exception Cause of Error

AssertionError Raised when an assert statement fails.

AttributeError Raised when attribute assignment or reference fails.

EOFError Raised when the input() function hits end-of-file condition.

FloatingPointError Raised when a floating point operation fails.

GeneratorExit Raise when a generator's close() method is called.

ImportError Raised when the imported module is not found.

IndexError Raised when the index of a sequence is out of range.

KeyError Raised when a key is not found in a dictionary.

KeyboardInterrupt Raised when the user hits the interrupt key (Ctrl+C or Delete).
MemoryError Raised when an operation runs out of memory.

NameError Raised when a variable is not found in local or global scope.

NotImplementedError Raised by abstract methods.

OSError Raised when system operation causes system related error.

Raised when the result of an arithmetic operation is too large to be


OverflowError
represented.

Raised when a weak reference proxy is used to access a garbage


ReferenceError
collected referent.

RuntimeError Raised when an error does not fall under any other category.

Raised by next() function to indicate that there is no further item to be


StopIteration
returned by iterator.

SyntaxError Raised by parser when syntax error is encountered.

IndentationError Raised when there is incorrect indentation.

TabError Raised when indentation consists of inconsistent tabs and spaces.

SystemError Raised when interpreter detects internal error.

SystemExit Raised by sys.exit() function.

Raised when a function or operation is applied to an object of incorrec


TypeError
type.

Raised when a reference is made to a local variable in a function or


UnboundLocalError
method, but no value has been bound to that variable.

UnicodeError Raised when a Unicode-related encoding or decoding error occurs.

UnicodeEncodeError Raised when a Unicode-related error occurs during encoding.

UnicodeDecodeError Raised when a Unicode-related error occurs during decoding.

UnicodeTranslateErro
r Raised when a Unicode-related error occurs during translating.
Raised when a function gets an argument of correct type but imprope
ValueError
value.

ZeroDivisionError Raised when the second operand of division or modulo operation is z

 AssertionError

x = 1

y = 0

assert y != 0, "Invalid Operation"


print(x / y)

AttributeError

X = 10

# Raises an AttributeError
X.append(6)

EOFError

n = int(input())
print(n * 10)

FloatingPointError

a = Decimal('1.1')
b = 2.2
c = a + b
key error:
>>> prices = { 'Pen' : 10, 'Pencil' : 5, 'Notebook' : 25}
>>> prices['Eraser']
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
prices['Eraser']
KeyError: 'Eraser'

IndentationError:

>>> print("hai")

SyntaxError: unexpected indent


IndexError:

Out of range function

CHAPTER-10
PYTHON NAMESPACE AND SCOPE
Namespace is a collection of names.( identifier)

A namespace containing all the built-in names is created when we start the Python interpreter
and exists as long as the interpreter runs.a namespace as a mapping of every name,you have
defined to corresponding objects.

1.local namespace->outer function declaration (b=20)

2.global namespace->(a=10)

3.nested local namespace->inner function declaration (c=30)

This is the reason that built-in functions like id() , print() id()->(we can get the address (in RAM)

# Note: You may get different values for the id

a = 2
print('id(2) =', id(2))

print('id(a) =', id(a))

Output
id(2) = 9302208
id(a) = 9302208

Example of Scope and Namespace in Python

def outer_function():
b = 20
def inner_func():
c = 30

a = 10

Here, the variable a is in the global namespace. Variable b is in the local namespace
of outer_function() and c is in the nested local namespace of inner_function() .

Chapter 11

Python Object and Class


Python Classes/Objects->var+method

Python is an object oriented programming language.

Almost everything in Python is an object, with its properties and methods.

Create a Class
class MyClass:

x=5

print(MyClass)

o/p

<class '__main__.MyClass'>

Create Object
class MyClass:
x=5
p1 = MyClass()
print(p1.x)
o/p
5

The __init__() Function

The examples above are classes and objects in their simplest form, and are not really useful in
real life applications.

To understand the meaning of classes we have to understand the built-in __init__() function.

All classes have a function called __init__(), which is always executed when the class is being
initiated.

Use the __init__() function to assign values to object properties, or other operations that are
necessary to do when the object is being created:
Example:1

class Person:

def __init__(self, name, age):

self.name = name

self.age = age

p1 = Person("John", 36)

print(p1.name)

print(p1.age)

o/p:

john

36

Object Methods
Objects can also contain methods. Methods in objects are functions that belong to the object.

Let us create a method in the Person class:

Example

Insert a function that prints a greeting, and execute it on the p1 object:

Example:1

class Person:

def __init__(self, name, age):

self.name = name

self.age = age

def myfunc(self):
print("Hello my name is " + self.name)

p1 = Person("John", 36)

p1.myfunc()

o/p

Hello my name is john

The self Parameter

The self parameter is a reference to the current instance of the class, and is used to access variables
that belongs to the class.

It does not have to be named self , you can call it whatever you like, but it has to be the first parameter
of any function in the class:

Example:

class Person:

def __init__(mysillyobject, name, age):

mysillyobject.name = name

mysillyobject.age = age

def myfunc(abc):

print("Hello my name is " + abc.name)

p1 = Person("John", 36)

p1.myfunc()

output:
Hello my name is John

Modify Object Properties


You can modify properties on objects like this:

Example

Set the age of p1 to 40:

class Person:

def __init__(self, name, age):

self.name = name

self.age = age

def myfunc(self):

print("Hello my name is " + self.name)

p1 = Person("John", 36)

p1.age = 40

print(p1.age)

output:

40

Delete Object Properties

You can delete properties on objects by using the del keyword:

Example
Delete the age property from the p1 object:

class Person:

def __init__(self, name, age):

self.name = name

self.age = age

def myfunc(self):

print("Hello my name is " + self.name)

p1 = Person("John", 36)

del p1.age

print(p1.age)

output:

Attribute Error

Delete Objects

You can delete objects by using the del keyword:

Example

Delete the p1 object:

class Person:

def __init__(self, name, age):

self.name = name

self.age = age
def myfunc(self):

print("Hello my name is " + self.name)

p1 = Person("John", 36)

del p1

print(p1)

output

Name Error(P1 is not defined)

The pass Statement

class definitions cannot be empty, but if you for some reason have a class definition with no
content, put in the pass statement to avoid getting an error.

Example:
for x in [0, 1, 2]

pass

Chapter 12

Python Inheritance

Inheritance allows us to define a class that inherits all the methods and properties from another
class.
Parent class is the class being inherited from, also called base class.

Child class is the class that inherits from another class, also called derived class.

Create a Parent Class

Any class can be a parent class, so the syntax is the same as creating any other class:

Example

class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname

def printname(self):
print(self.firstname, self.lastname)

#Use the Person class to create an object, and then execute the printname method:

x = Person("John", "Doe")
x.printname()
Create a Child Class

To create a class that inherits the functionality from another class, send the parent class as a
parameter when creating the child class:

Example:1

class Person:

def __init__(self, fname, lname):

self.firstname = fname

self.lastname = lname
def printname(self):

print(self.firstname, self.lastname)

class Student(Person):

pass

x = Student("Mike", "Olsen")

x.printname()

Add the __init__() Function

So far we have created a child class that inherits the properties and methods from its parent.

We want to add the __init__() function to the child class (instead of the pass keyword).

Note: The __init__() function is called automatically every time the class is being used to
create a new object.

Example

class Person:

def __init__(self, fname, lname):

self.firstname = fname

self.lastname = lname

def printname(self):

print(self.firstname, self.lastname)

class Student(Person):
def __init__(self, fname, lname):

Person.__init__(self, fname, lname)

x = Student("Mike", "Olsen")

x.printname()

Use the super() Function

Python also has a super() function that will make the child class inherit all the methods and
properties from its parent:

class Person:

def __init__(self, fname, lname):

self.firstname = fname

self.lastname = lname

def printname(self):

print(self.firstname, self.lastname)

class Student(Person):

def __init__(self, fname, lname):

super().__init__(fname, lname)

x = Student("Mike", "Olsen")

x.printname()

By using the super() function, you do not have to use the name of the parent element, it will
automatically inherit the methods and properties from its parent.
Add properties

Add a property called graduationyear to the Student class:

class Person:

def __init__(self, fname, lname):

self.firstname = fname

self.lastname = lname

def printname(self):

print(self.firstname, self.lastname)

class Student(Person):

def __init__(self, fname, lname):

super().__init__(fname, lname)

self.graduationyear = 2019

x = Student("Mike", "Olsen")

print(x.graduationyear)

o/p

2019

Add Methods

Add a method called welcome to the Student class:

Example:

class Person:
def __init__(self, fname, lname):

self.firstname = fname

self.lastname = lname

def printname(self):

print(self.firstname, self.lastname)

class Student(Person):

def __init__(self, fname, lname, year):

super().__init__(fname, lname)

self.graduationyear = year

def welcome(self):

print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)

x = Student("Mike", "Olsen", 2019)

x.welcome()

o/p

Welcome Mike Olsen to the class of 2019

Chapter 13
Network programming
Python plays an essential role in network programming. The standard library of
Python has full support for network protocols, encoding, and decoding of data and other networking
concepts, and it is simpler to write network programs in Python than that of C++

socket
A socket is the end-point in a flow of communication between two programs or communication
channels operating over a network. They are created using a set of programming requests called
socket API (Application Programming Interface). Python's socket library offers classes for handling
common transports as a generic interface.
Sockets use protocols for determining the connection type for port-to-port communication between
client and server machines. The protocols are used for:

 Domain Name Servers (DNS)

Each device connected to the Internet has a unique IP address which other machines use to find the device.
DNS servers eliminate the need for humans to memorize IP addresses such as 192.168.1.1 (in IPv4), or more
complex newer alphanumeric IP addresses such as 2400:cb00:2048:1::c629:d7a2 (in IPv6).

 IP addressing

An IP address is a string of numbers separated by periods. IP addresses are expressed as a set of four
numbers — an example address might be 192.158.1.38. Each number in the set can range from 0 to 255.
So, the full IP addressing range goes from 0.0.0.0 to 255.255.255.255.

 E-mail->smtp
 FTP (File Transfer Protocol) etc...

The File Transfer Protocol (FTP) is a standard communication protocol used for the transfer of computer
files from a server to a client on a computer network

Socket Program
 listen(): is used to establish and start TCP listener.
 bind(): is used to bind-address (host-name, port number) to the socket.
 accept(): is used to TCP client connection until the connection arrives.
 connect(): is used to initiate TCP server connection.
 send(): is used to send TCP messages.
 recv(): is used to receive TCP messages.
 sendto(): is used to send UDP messages
 close(): is used to close a socket.
A Simple Network Program Using Python

Example

 Create a new folder in desktop (socket)


 Type the client and server program and save into socket folder

#server

import socket

s = socket.socket()

host = socket .gethostname()

port = 1234

s.bind((host, port))

s.listen(5)

while True:

conn,addr = s.accept()

print("Got connection from:",addr)

conn.send(b'Thank you for connection')

conn.close()

Save the filename server.py

#client

import socket

s = socket.socket()
host = socket.gethostname()

port = 1234

s.connect((host,port))

print(s.recv(1024))

s.close()
Save the filename client.py

Open the two command prompt server and client

Set the client and server path (Two command prompt)

Server side Type the name- python server.py

Waiting for client any request from client side

Client side Type the name-python client.py

Receive the message from server side Thank you for connection

Chapter 14
Multithreaded Programming

Threads
It is the execution of a tiny sequence of program instruction that can be managed
independently and is a distinctive part of the operating system. Modern OS manages multiple
programs using a time-sharing technique. In Python, there are two different kinds of thread. These
are:

 Kernel Threads
 User-space threads or User threads

Why use thread?


 Parallel Computation: If any user has a multiprocessor machine, then the thread can allow doing
parallel processing with the goal of an increase in processing speed.
 Standardization: It became a standard approach for all programming languages as it increases
programming speed.
 Parallel I/O (Input/Output): When we talk about the speed of input & output, it is comparatively
slow in CPU. By placing each i/o operations in multiple individual threads, programmers can make
use of operations done in parallel with each other & with the computation speed.
 Asynchronous Events: Multiple threaded applications can deal with asynchronous actions. For
example, in a program, programmers may not know whether the next action will be to use the
mouse or to use the keyboard. By planting a separate thread for each action, i.e., two threads both
for mouse and keyboard, programmers are able to code a cleaner, efficient application, which is to
use non-blocking I/O operations.

Benefits of Thread
 For a single process, multiple threads can be used to process and share the same data-space and
can communicate with each other by sharing information.
 They use lesser memory overhead, and hence they are called lightweight processes.
 A program can remain responsive to input when threads are used.
 Threads can share and process the global variable's memory.

New Thread

It is achievable to execute functions in a separate thread using a module Thread. For doing
this, programmers can use the function - thread.start_new_thread().

Syntax:

thread.start_new_thread(function, args[, kwargs])


Thread Program

#Python multithreading example.

#1. Calculate factorial using recursion.

#2. Call factorial function using thread.

from _thread import start_new_thread

from time import sleep

threadId = 1 # thread counter

waiting = 2 # 2 sec. waiting time

def factorial(n):

global threadId

rc = 0

if n < 1: # base case

print("{}: {}".format('\nThread', threadId ))

threadId += 1

rc = 1

else:

returnNumber = n * factorial( n - 1 ) # recursive call

print("{} != {}".format(str(n), str(returnNumber)))

rc = returnNumber

return rc
start_new_thread(factorial, (5, ))

#start_new_thread(factorial, (4, ))

print("Waiting for threads to return...")

sleep(waiting)

Method of Thread class

The threading module, as described earlier, has a Thread class that is used for implementing
threads, and that class also contains some predefined methods used by programmers in multi-
threaded programming. These are:

 run(): It acts as the entry of the thread


 start(): is used for starting the thread by calling the run()
 isAlive(): is used to verify whether the still executing or not
 getName(): is used for returning the name of a thread
 setName(): is used to set the name of the thread

CHAPTER 15

MY SQL DATABASE ACCESS

In this tutorial we will use the driver "MySQL Connector".

We recommend that you use PIP to install "MySQL Connector”


https://www.mysql.com/downloads/

C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>python -pip


install mysql-connector-python

import mysql.connector
create table kalai(name varchar(25),age int,dept varchar(12),city varchar(5),pincode int)
select * from kalai
insert into kalai values('aaa',25,'ct','mkm',603306)
select * from kalai
insert into kalai values('bbb',24,'ct','ch',603758)
insert into kalai values('ccc',25,'ct','mkm',603306)
insert into kalai values('ddd',28,'ct','gh',603306)
insert into kalai values('eee',29,'it','mve',603306)
select * from kalai
alter table kalai add mark int
select * from kalai
update kalai SET mark=60 WHERE name='aaa';
select * from kalai

Create Connection

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="myusername",
password="mypassword"
)

print(mydb)

DATABASE CONNECTION
import mysql.connector

Creating table
import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="myusername",
password="mypassword",
database="mydatabase"
)

mycursor = mydb.cursor()

mycursor.execute("CREATE TABLE customers (name VARCHAR(255),


address VARCHAR(255))")
INSERT RECORD IN A TABLE
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
password="mypassword",
database="mydatabase"
)

mycursor = mydb.cursor()

sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"


val = ("John", "Highway 21")

mycursor.execute(sql, val)

mydb.commit()

print(mycursor.rowcount, "record inserted.")

CHAPTER 16
GUI PROGRAMMING
Most of the programs we have done till now are text-based programming. But many applications need
GUI (Graphical User Interface).

Python provides various options for developing graphical user interfaces (GUIs). Most important are
listed below.
 Tkinter − Tkinter is the Python interface to the Tk GUI toolkit shipped with Python. We would
look this option in this chapter.
 wxPython − This is an open-source Python interface for wxWindows.
 JPython − JPython is a Python port for Java which gives Python scripts seamless access to
Java class libraries on the local machine

TKINTER PROGRAMMING:

Tkinter is the standard GUI library for Python. Python when combined with Tkinter
provides a fast and easy way to create GUI applications. Tkinter provides a powerful object-oriented interface
to the Tk GUI toolkit.

Example

import tkinter as tk
root = tk.Tk()
root.title("First Tkinter Window")
root.mainloop()

LABLE WIDGET

from Tkinter import *

root = Tk()
var = StringVar()
label = Label( root, textvariable=var, relief=RAISED )

var.set("Hey!? How are you doing?")


label.pack()
root.mainloop()

PYTHON SHELL PROMPT OUTPUT:

from Tkinter import *


root= tk()
photo=photoimage(file=”c:\python27\csclogo.gif”)
w=label(root,image=photo)
w.pack()
root.mainloop()

LABELFRAME WIDGET
The LabelFrame widget is used to draw a border around its child widgets.

top = Tk()
top.geometry("300x200")

labelframe1 = LabelFrame(top, text="Positive Comments")


labelframe1.pack(fill="both", expand="yes")

toplabel = Label(labelframe1, text="Place to put the positive comments")


toplabel.pack()

labelframe2 = LabelFrame(top, text = "Negative Comments")


labelframe2.pack(fill="both", expand = "yes")

bottomlabel = Label(labelframe2,text = "Place to put the negative comments")


bottomlabel.pack()

top.mainloop()

ENTRY WIDGET
Python offers multiple options for developing a GUI (Graphical User Interface).
Out of all the GUI methods, Tkinter is the most commonly used method

Syntax
entry = tk.Entry(parent, options)
1) Parent: The Parent window or frame in which the widget to display.
2) Options: The various options provided by the entry widget are:

Example
import tkinter as tk
root = tk.Tk()
root.title("First Tkinter Window")
root.mainloop()

BUTTON WIDGET

Tkinter is Python’s standard GUI (Graphical User Interface) package. It is one of the
most commonly used packages for GUI applications which comes with Python itself. Let’s
see how to create a button using Tkinter.
import tkinter as tk

def write_slogan():
print("Tkinter is easy to use!")

root = tk.Tk()
frame = tk.Frame(root)
frame.pack()

button = tk.Button(frame,
text="QUIT",
fg="red",
command=quit)
button.pack(side=tk.LEFT)
slogan = tk.Button(frame,
text="Hello",
command=write_slogan)
slogan.pack(side=tk.LEFT)

root.mainloop()
checkbutton widget
The Tkinter Checkbutton widget can contain text, but only in a single font, or images, and a
button can be associated with a Python function or method.

Example

from tkinter import *


master = Tk()
var1 = IntVar()
Checkbutton(master, text="male", variable=var1).grid(row=0, sticky=W)
var2 = IntVar()
Checkbutton(master, text="female", variable=var2).grid(row=1, sticky=W)
mainloop()

LISTBOX WIDGET

The ListBox widget is used to display different types of items. These items must be of
the same type of font and having the same font color.

from tkinter import *

# create a root window.


top = Tk()

# create listbox object


listbox = Listbox(top, height = 10,
width = 15,
bg = "grey",
activestyle = 'dotbox',
font = "Helvetica",
fg = "yellow")

# Define the size of the window.


top.geometry("300x250")

# Define a label for the list.


label = Label(top, text = " FOOD ITEMS")

# insert elements by their


# index and names.
listbox.insert(1, "Nachos")
listbox.insert(2, "Sandwich")
listbox.insert(3, "Burger")
listbox.insert(4, "Pizza")
listbox.insert(5, "Burrito")

# pack the widgets


label.pack()
listbox.pack()

# Display untill User


# exits themselves.
top.mainloop()

MENU WIDGET

Menus are the important part of any GUI. A common use of menus is to
provide convenient access to various operations such as saving or opening a file, quitting a
program, or manipulating data.

# importing only those functions


# which are needed
from tkinter import *
from tkinter.ttk import *
from time import strftime

# creating tkinter window


root = Tk()
root.title('Menu Demonstration')

# Creating Menubar
menubar = Menu(root)

# Adding File Menu and commands


file = Menu(menubar, tearoff = 0)
menubar.add_cascade(label ='File', menu = file)
file.add_command(label ='New File', command = None)
file.add_command(label ='Open...', command = None)
file.add_command(label ='Save', command = None)
file.add_separator()
file.add_command(label ='Exit', command = root.destroy)

# Adding Edit Menu and commands


edit = Menu(menubar, tearoff = 0)
menubar.add_cascade(label ='Edit', menu = edit)
edit.add_command(label ='Cut', command = None)
edit.add_command(label ='Copy', command = None)
edit.add_command(label ='Paste', command = None)
edit.add_command(label ='Select All', command = None)
edit.add_separator()
edit.add_command(label ='Find...', command = None)
edit.add_command(label ='Find again', command = None)

# Adding Help Menu


help_ = Menu(menubar, tearoff = 0)
menubar.add_cascade(label ='Help', menu = help_)
help_.add_command(label ='Tk Help', command = None)
help_.add_command(label ='Demo', command = None)
help_.add_separator()
help_.add_command(label ='About Tk', command = None)

# display Menu
root.config(menu = menubar)
mainloop()

MESSAGE WIDGET

The Message widget is used to show the message to the user regarding the
behavior of the python application

from tkinter import *

root = Tk()
root.geometry("300x200")

w = Label(root, text ='GeeksForGeeks', font = "50")


w.pack()

msg = Message( root, text = "A computer science portal for geeks")

msg.pack()

root.mainloop()
CHAPTER-17
IMAGE PROCESSING IN PYTHON WITH PILLOW

BASIC INSTALLATION:

Step 1:Go to command prompt

Step 2:cd C:\Users\Office\AppData\Local\Programs\Python\Python36-32

Step 3: cd scripts

Step 4:pip install xlwt (package)

Step 5:pip install


Python provides lots of libraries for image processing, including

 OpenCV − Image processing library mainly focused on real-time computer vision with
application in wide-range of areas like 2D and 3D feature toolkits, facial & gesture
recognition, Human-computer interaction, Mobile robotics, Object identification and
others.
 Python Imaging Library (PIL) − To perform basic operations on images like create
thumnails, resize, rotation, convert between different file formats etc.
Image: Open() and show()

#Import required library

from PIL import Image

#Open Image

im = Image.open("TajMahal.jpg")

#Image rotate & show

im.rotate(45).show()
output

>>> im

<PIL.JpegImagePlugin.JpegImageFile image mode = RGB size = 1000x667 at 0x65AB990<

>>> im.size

(1000, 667)

>>> im.format

'JPEG'

>>>

Convert and Save() Image

We can change the format of image from one form to another, like below
>>> im.save('TajMahal.png')
Resize-thumbnails()

You might also like