Python Final
Python Final
[Link]
INTRODUCTION( CONTD….)
Python version 1.0 was released in January 1994. The
major new features included in this release were the
functional programming tools lambda, map, filter and
reduce.
In October 2000, Python 2.0 was introduced. This
release included list comprehensions, a full garbage
collector and it was supporting unicode.
Python flourished for another 8 years in the versions 2.x
before the next major release as Python 3.0
[Link]
INTRODUCTION
Python was conceptualized in the late 1980s.
[Link]
PYTHON
VARIABLES
[Link]
PYTHON - VARIABLES
what's a variable? As the name implies, a variable is
something which can change.
A variable is a way of referring to a memory location
used by a computer program.
[Link]
Eg: int x;
int y;
[Link]
PYTHON - VARIABLES
If a variable is of type integer, solely integers can be
saved in the variable for the duration of the program. In
those programming languages every variable has to be
declared before it can be used. Declaring a variable
means binding it to a data type.
It's a lot easier in Python. There is no declaration of
variables required in Python. It's not even possible. If
there is need of a variable, you think of a name and start
using it as a variable.
[Link]
The value of a variable may change during program
execution but the type as well. You can assign an integer
value to a variable, use it as an integer for a while and
then assign a string to the same variable.
x=5
x = "John"
print(x)
Output: john
[Link]
VARIABLE NAMES
[Link]
ASSIGN VALUE TO MULTIPLE VARIABLES
Output: orange
banana
cherry
[Link]
OUTPUT VARIABLES
[Link]
You can also use the + character to add a variable to
another variable:
Example
x = "Python is "
y = "awesome"
z = x + y
print(z)
[Link]
For numbers, the + character works as a mathematical
operator:
Example
x=5
y = 10
print(x + y)
Output: 15
[Link]
f you try to combine a string and a number, Python will
give you an error:
Example
x=5
y = "John"
print(x + y)
Output:
TypeError: unsupported operand type(s) for +: 'int' and
'str'
[Link]
Python Data Types
[Link]
PYTHON DATA TYPES
[Link]
Getting the Data Type
You can get the data type of any object by using the
type() function:
Example
x=5
print(type(x))
[Link]
PYTHON NUMBERS
float
Complex
Example
x = 1 # int
y = 2.8 # float
z = 1j # complex
[Link]
INT
Integers:
x=1
y = 35656222554887711
z = -3255522
[Link]
FLOAT
Example
Floats:
x = 1.10
y = 1.0
z = -35.59
[Link]
COMPLEX
Example
Complex:
x = 3+5j
y = 5j
z = -5j
[Link]
RANDOM NUMBER
Example
Import the random module, and display a random
number between 1 and 9:
import random
print([Link](1,10))
[Link]
PYTHON CASTING
There may be times when you want to specify a type on
to a variable. This can be done with casting.
Casting in python is therefore done using constructor
functions:
int() - constructs an integer number from an integer
literal, a float literal (by rounding down to the previous
whole number), or a string literal (providing the string
represents a whole number)
[Link]
float() - constructs a float number from an integer literal,
a float literal or a string literal (providing the string
represents a float or an integer)
str() - constructs a string from a wide variety of data
types, including strings, integer literals and float literals
[Link]
Example
Integers:
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
[Link]
Floats:
x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2
[Link]
Strings:
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'
[Link]
PYTHON STRINGS
[Link]
PYTHON STRINGS
Example
print("Hello")
print('Hello')
[Link]
Assigning a string to a variable is done with the variable
name followed by an equal sign and the string:
a = "Hello"
print(a)
[Link]
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.""“
print(a)
[Link]
STRINGS ARE ARRAYS
a = "Hello, World!"
print(a[1])
Output: e
[Link]
STRING SLICING
Output: llo
[Link]
NEGATIVE INDEXING
Output: orl
[Link]
STRING LENGTH
a = "Hello, World!"
print(len(a))
Output:13
[Link]
STRING METHODS
a = "Hello, World!"
print([Link]())
[Link]
The upper() method returns the string in upper case:
a = "Hello, World!"
print([Link]())
[Link]
The split() method splits the string into substrings if it
finds instances of the separator:
a = "Hello, World!"
print([Link](",")) # returns ['Hello', ' World!']
[Link]
CHECK STRING
[Link]
Check if the phrase "ain" is NOT present in the
following text:
txt = "The rain in Spain stays mainly in the plain"
x = "ain" not in txt
print(x)
Output: false
[Link]
STRING FORMAT
[Link]
Output:
My name is John, and I am 36
[Link]
The format() method takes unlimited number of
arguments, and are placed into the respective
placeholders. We use { } as place holder.
Example
quantity = 3
itemno = 567
price = 49.95
myorder = ("I want { } pieces of item { } for { }
dollars.“)
print([Link](quantity, itemno, price))
[Link]
Output:
I want 3 pieces of item 567 for 49.95 dollars.
[Link]
You can use index numbers {0} to be sure the arguments
are placed in the correct placeholders:
Example
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of
item {1}."
print([Link](quantity, itemno, price))
[Link]
Output:
[Link]
PYTHON
BOOLEANS
[Link]
PYTHON BOOLEANS
[Link]
print(10 > 9)
print(10 == 9)
print(10 < 9)
Output:
True
False
False
[Link]
Example: Print a message based on whether the
condition is True or False.
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
Output: b is not greater than a
[Link]
EVALUATE VALUES AND VARIABLES
print(bool("Hello"))
print(bool(15))
Output:
True
True
[Link]
Almost any value is evaluated to True if it has some sort
of content.
Any string is True, except empty strings.
Example
bool("abc")
bool(123)
[Link]
Output:True
True
True
[Link]
In fact, there are not many values that evaluates to False,
except empty values, such as (), [], {}, "", the number 0,
and the value None. And of course the value False
evaluates to False.
Example
bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
[Link]
bool({})
Output:
False
False
False
False
False
False
False
[Link]
PYTHON
OPERATORS
[Link]
PYTHON OPERATORS
Arithmetic operators
Assignment operators
Comparison operators
[Link]
Logical operators
Identity operators
Membership operators
Bitwise operators
[Link]
PYTHON ARITHMETIC OPERATORS
[Link]
PYTHON ASSIGNMENT OPERATORS
[Link]
PYTHON COMPARISON OPERATORS
[Link]
PYTHON LOGICAL OPERATORS
[Link]
PYTHON IDENTITY OPERATORS
[Link]
x = ["apple", "banana"]
y = ["apple", "banana"]
z=x
print(x is z)
print(x is y)
# returns False because x is not the same object as y, even if they have the same content
print(x == y)
# to demonstrate the difference betweeen "is" and "==": this comparison returns True
because x is equal to y [Link]
x = ["apple", "banana"]
y = ["apple", "banana"]
z=x
print(x is not z)
print(x is not y)
# returns True because x is not the same object as y, even if they have the same content
print(x != y)
# to demonstrate the difference betweeen "is not" and "!=": this comparison returns
False because x is equal to y [Link]
PYTHON MEMBERSHIP OPERATORS
Operator Description
in Returns True if a sequence with
the specified value is present in the
object
not in Returns True if a sequence with the
specified value is not present in the object
[Link]
x = ["apple", "banana"]
print("banana" in x)
x = ["apple", "banana"]
print("pineapple" not in x)
[Link]
PYTHON BITWISE OPERATORS
[Link]
INDENTATION IN YTHON
if a==1:
print(a)
if b==2:
print(b)
print('end')
[Link]
PYTHON USER INPUT
EXAMPLE:
username = input("Enter username:")
print("Username is: " + username)
[Link]
OUTPUT:
[Link]
INTEGER AS AN INPUT
EXAMPLE:
x = int(input("Enter a number: "))
Print(x)
Print(y)
Output:
Enter a number: 22
22
25 [Link]
PYTHON
CONDITIONAL
STATEMENTS
[Link]
PYTHON IF ... ELSE
b is greater than a
[Link]
ELIF
[Link]
ELSE
[Link]
PYTHON WHILE LOOPS
Example
Print i as long as i is less than 6:
i=1
while i < 6:
print(i)
i += 1
Output: 1 2 3 4 5
[Link]
THE BREAK STATEMENT
The break statement can stop the loop even if the while
condition is true.
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
Output: 1 2 3
[Link]
THE CONTINUE STATEMENT
Output: 1 2 4 5 6
[Link]
THE ELSE STATEMENT
[Link]
PYTHON FOR
LOOPS
[Link]
PYTHON FOR LOOPS
A for loop is used for iterating over a sequence (that is either a
list, a tuple, a dictionary, a set, or a string)
Syntax is for followed by a variable followed by in and followed
by the variable to iterate and colon
Indentation is applied in for
Example
[Link]
LOOPING THROUGH A STRING
Even strings are iterable objects, they contain a sequence of
characters
Example
for x in "banana":
print(x)
Output: b
a
n
a
n
a
[Link]
THE BREAK STATEMENT
The break statement stops the loop before it has looped
through all the items
Example
banana
[Link]
THE CONTINUE STATEMENT
The continue statement stops the current iteration of the
loop, and continue with the next
Example
cherry
[Link]
THE RANGE() FUNCTION
for x in range(6):
print(x)
Output: 0 1 2 3 4 5
Example
[Link]
The range() function defaults to increment the sequence
by 1, however it is possible to specify the increment
value by adding a third parameter: range(2, 30, 3)
Example
[Link]
ELSE IN FOR LOOP
The else keyword in a for loop specifies a block of code
to be executed when the loop is finished
Example
finally finished
[Link]
NESTED LOOPS
A nested loop is a loop inside a loop.
The "inner loop" will be executed one time for each
iteration of the "outer loop"
Example: print the colour of fruit along with name
[Link]
PYTHON
FUNCTIONS
[Link]
PYTHON FUNCTIONS
[Link]
CREATING A FUNCTION
Example
def my_function():
print("Hello from a function")
[Link]
CALLING A FUNCTION
def my_function():
print("Hello from a function")
my_function()
output: Hello from a function
[Link]
ARGUMENTS
[Link]
Example
def my_function(fname):
print(fname + " kumar")
my_function(“Muthu")
my_function(“Ramesh")
my_function(“Raj")
Output: muthu kumar
Ramesh kumar
Raj kumar
[Link]
ARGUMENT TYPE
The Function arugments are of four types
Required arguments
Keyword arguments
Default arguments
Variable-length arguments
[Link]
REQUIRED ARGUMENTS
print (str )
printme(“hello”)
Output: hello
[Link]
KEYWORD ARGUMENTS
[Link]
Example
def printinfo( name, age ):
Output:
Name: miki
Age 50
[Link]
DEFAULT ARGUMENTS
Example:
A default argument is an argument that assumes a default
value if a value is not provided in the function call for
that argument.
Example:
printinfo( name="miki" )
[Link]
VARIABLE-LENGTH ARGUMENTS
A function for more arguments than you specified while
defining the function. These arguments are called
variable-length arguments
Example:
print (var)
printinfo( 10 )
[Link]
Output:
10
70 60 50
[Link]
THE RETURN STATEMENT
[Link]
Output:
Sum:30
abc: 30
[Link]
PYTHON LISTS
[Link]
PYTHON LISTS
List is a sequential data type in python
A list is a collection of datas which is ordered and
changeable. In Python lists are written with square
brackets, a list can have string or numerical data
The list is created by using square bracket with each
elements separated by commas, each element in a list is
indexed beginning with [0] ie: the index for apple is [0],
banana is [1] and so on
Example: thislist = ["apple", "banana", "cherry"]
print(thislist)
Output: ["apple", "banana", "cherry"]
[Link]
ACCESS ITEMS IN A LIST
Example
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
Output: banana
[Link]
NEGATIVE INDEXING
Negative indexing means beginning from the end, -1
refers to the last item, -2 refers to the second last item etc
Example:
Output: cherry
[Link]
RANGE OF INDEXES
[Link]
Example:
thislist = ["apple", "banana", "cherry", "orange", "kiwi",
"melon", "mango"]
print(thislist[:4])
[Link]
thislist = ["apple", "banana", "cherry", "orange", "kiwi",
"melon", "mango"]
print(thislist[2:])
[Link]
RANGE OF NEGATIVE INDEXES
[Link]
This example returns the items from index -4 (included)
to index -1 (excluded)
Output:
['orange', 'kiwi', 'melon']
[Link]
CHANGE ITEM VALUE
[Link]
LOOP THROUGH A LIST
Output:
apple
banana
cherry
[Link]
CHECK IF ITEM EXISTS
Example:
thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
Output: Yes, 'apple' is in the fruits list
[Link]
LIST LENGTH
Example
Print the number of items in the list:
[Link]
ADD ITEMS
Example
thislist = ["apple", "banana", "cherry"]
[Link]("orange")
print(thislist)
Output:
['apple', 'banana', 'cherry', 'orange']
[Link]
INSERT() METHOD
To add an item at the specified index, use the insert()
method
Example
[Link]
REMOVE ITEM
Output:['apple', 'cherry']
[Link]
The pop() method removes the specified index, (or the
last item if index is not specified)
Example
[Link]
The del keyword removes the specified index
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
[Link]
The clear() method empties the list:
Example
Output: [ ]
[Link]
COPY A LIST
[Link]
thislist = ["apple", "banana", "cherry"]
mylist = list(thislist)
print(mylist)
[Link]
JOIN TWO LISTS
Example
[Link]
Output: ['a', 'b', 'c', 1, 2, 3]
[Link](list2)
print(list1)
[Link]
Output:
['a', 'b', 'c', 1, 2, 3]
[Link]
THE LIST() CONSTRUCTOR
[Link]
PYTHON SETS
[Link]
PYTHON SETS
Create a Set:
[Link]
ACCESS ITEMS IN SETS
Set cannot be accessed by items in a set by referring to
an index, since sets are unordered the items has no index.
But you can loop through the set items using a for loop,
or ask if a specified value is present in a set, by using the
in keyword.
Example
[Link]
Output: cherry
banana
apple
Example
[Link]
CHANGE ITEMS IN A SET
[Link]
Example:
thisset = {"apple", "banana", "cherry"}
[Link]("orange")
print(thisset)
[Link]
Add multiple items to a set, using the update() method:
Example:
print(thisset)
Output:{'grapes', 'mango', 'orange', 'apple', 'cherry',
'banana'}
[Link]
To determine how many items a set has, use the len()
method.
Example
print(len(thisset))
Output: 3
[Link]
REMOVE ITEM
To remove an item in a set, use the remove(), or the
discard() method.
Example
[Link]
Remove the last item by using the pop() method:
Example
Output: apple
{'banana', 'cherry'}
[Link]
The clear() method empties the set:
Example:
thisset = {"apple", "banana", "cherry"}
[Link]()
print(thisset)
Output: set()
[Link]
JOIN TWO SETS
There are several ways to join two or more sets in Python.
You can use the union() method that returns a new set
containing all items from both sets, or the update() method
that inserts all the items from one set into another
Example
The union() method returns a new set with all items from
both sets:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = [Link](set2)
print(set3)
[Link]
Output:
{2, 'a', 1, 3, 'c', 'b'}
set2 = {1, 2, 3}
[Link](set2)
print(set1
[Link]
Output: {3, 'a', 'b', 1, 2, 'c'}
[Link]
The set() Constructor
It is also possible to use the set() constructor to make a
set.
Example
[Link]
PYTHON TUPLES
[Link]
PYTHON TUPLES
Create a Tuple:
[Link]
ACCESS TUPLE ITEMS
banana
[Link]
NEGATIVE INDEXING
cherry
[Link]
RANGE OF INDEXES
[Link]
CHANGE TUPLE VALUES
Once a tuple is created, you cannot change its values.
Tuples are unchangeable, or immutable as it also is
called.
But there is a method to change it. You can convert the
tuple into a list, change the list, and convert the list back
into a tuple.
Example
Example
Example:
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
Output:
Yes, 'apple' is in the fruits tuple
[Link]
ADD ITEMS
[Link]
REMOVE ITEMS
Example:
The del keyword can delete the tuple completely:
[Link]
JOIN TWO TUPLES
[Link]
THE TUPLE() CONSTRUCTOR
Example:
thistuple = tuple(("apple", "banana", "cherry"))
print(thistuple)
[Link]
PYTHON-
DICTIONARIES
[Link]
PYTHON DICTIONARIES
[Link]
Example
Create and print a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
In the above example the key is brand and the value is
Ford , in the next pair model is the key and Mustang is
the value.
[Link]
Ouput:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
[Link]
ACCESSING ITEMS IN DICTIONARY
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
Print(x) [Link]
Output: Mustang
There is also a method called get() that will give you the
same result
x = [Link]("model")
Print(x)
Output: Mustang
[Link]
CHANGE VALUES IN A DICTIONARY
print (Capital)
[Link]
Output:
{"Austria":"Vienna", "Switzerland":"Bern",
"Germany":"Berlin", "Netherlands":"Amsterdam"}
[Link]
LOOP THROUGH A DICTIONARY
[Link]
Output
Austria
Switzerland
Germany
Netherlands
[Link]
Example : To access values
capital ={"Austria":"Vienna", "Switzerland":"Bern",
"Germany":“Berlin", "Netherlands":"Amsterdam"}
For x in capital:
Print(capital[x])
Output:
Vienna
Bern
Berlin
Amsterdam
[Link]
You can also use the values() function to return values of
a dictionary
Example:
for x in [Link]():
print(x)
[Link]
Loop through both keys and values, by using the items()
function:
Example:
for x, y in [Link]():
print(x, y)
[Link]
CHECK IF KEY EXISTS
print(“Germany is present”)
Else:
[Link]
Output:
Germany is present
[Link]
ADDING NEW ITEMS TO A
DICTIONARY
Print(capital)
[Link]
Output:
{"Austria":"Vienna", "Switzerland":"Bern",
"Germany":“Berlin", "Netherlands":"Amsterdam“
“India” : “Newdelhi”}
[Link]
REMOVING ITEMS
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]
[Link]("model")
print(thisdict)
Output: {'brand': 'Ford', 'year': 1964}
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]
del thisdict
print(thisdict)
[Link]
NESTED DICTIONARIES
[Link]
Output:
[Link]
UPDATE: MERGING DICTIONARIES
[Link]
[Link](knowledge2)
Print(knowledge)
Output:
{'Frank': {'Python', 'Perl'}, 'Guido': {'Python'}, 'Monica':
{'C', 'C++'}}
[Link]
LISTS FROM DICTIONARIES
items_view = [Link]()
[Link]
items = list(items_view) >>>
Print( items)
print(keys)
[Link]
THE DICT() CONSTRUCTOR
[Link]
PYTHON– OBJECT
ORIENTED
PROGRAMMING
[Link]
PYTHON - OOPS
Python Class
[Link]
CREATE A CLASS
class MyClass:
x=5
Create Object
[Link]
Example
Create an object named p1, and print the value of x:
p1 = MyClass()
print(p1.x)
class MyClass:
x=5
p1 = MyClass()
print(p1.x)
OUTPUT: 5
[Link]
THE __INIT__() FUNCTION
[Link]
THE SELF PARAMETER
[Link]
EXAMPLE:
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
[Link]
OBJECT IN PYTHON
Object is simply a collection of data (variables) and methods
(functions) that act on those data. And, class is a blueprint for
the object.
EXAMPLE:
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
p1 = Person("John", 36)
print([Link])
print([Link])
[Link]
OUTPUT:
John
36
[Link]
OBJECT METHODS
The method in object refers to the functions in the object
Example:
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
def myfunc(self):
print("Hello my name is " + [Link])
p1 = Person("John", 36)
[Link]()
[Link]
OUTPUT:
Hello my name is John
[Link]
THE PASS STATEMENT
class Person:
pass
[Link]
PYTHON INHERITANCE
[Link]
CREATE A PARENT CLASS
class Person:
def __init__(self, fname, lname):
[Link] = fname
[Link] = lname
def printname(self):
print([Link], [Link])
x = Person("John", "Doe")
[Link]()
[Link]
OUTPUT:
John Doe
[Link]
CREATE A CHILD CLASS
[Link]
Example:
class Person:
[Link] = fname
[Link] = lname
def printname(self):
print([Link], [Link])
class Student(Person):
pass
x = Student("Mike", "Olsen")
[Link]()
[Link]
Output : Mike olsen
[Link]
TYPES OF INHERITANCE
Single Inheritance
Multiple Inheritance
Multilevel Inheritance
Hybrid Inheritance
Hierarchical Inheritance
[Link]
SINGLE INHERITANCE
[Link]
MULTIPLE INHERITANCE
MULTIPLE INHERITANCE
Multiple inheritance is possible in python A class can be
derived from more then one base classes. The syntax for
multiple inheritance is similar to single inheritance
Here is an example of multiple inheritance
[Link]
EXAMPLE
[Link]
OUTPUT
45
25
[Link]
MULTILEVEL INHERITANCE
Multilevel inheritance is also possible in Python like
other Object Oriented programming languages. We can
inherit a derived class from another derived class, this
process is known as multilevel inheritance. In Python,
multilevel inheritance can be done at any depth.
[Link]
EXAMPLE
[Link]
OUTPUT
45
[Link]
HYBRID INHERITANCE
[Link]
EXAMPLE
[Link]
OUTPUT
M( ) from class d
M( ) from class b
M( ) from class a
M( ) from class a
[Link]
FILE HANDLING IN
PYTHON
[Link]
FILE HANDLING IN PYTHON
File handling is an important part of any web
application.
The file handling performs three important functions
i) Read files
[Link]
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:
f = open( “[Link]”)
[Link]
PYTHON READ FILES
f = open("[Link]", "r")
print([Link]())
Output: the above code opens the contents in the file. Let
us assume that it has the below text
Hello! Welcome to [Link]
This file is for testing purposes.
Good Luck!
[Link]
READ ONLY PARTS OF THE FILE
The read() method returns the whole text, but you can
also specify how many characters you want to return
Example
f = open("[Link]", "r")
print([Link](5))
Output:Hello
[Link]
READLINE()
The readline() method returns one line from the text file.
Example
f = open("[Link]", "r")
print([Link]())
[Link]
TO READ TWO LINES
By calling readline() two times, you can read the two
first lines
Example
f = open("[Link]", "r")
print([Link]())
print([Link]())
Output:
f = open("[Link]", "r")
print([Link]())
[Link]()
[Link]
PYTHON FILE WRITE
[Link]
Example
f = open("[Link]", "a")
[Link]("Now the file has more content!")
[Link]()
f = open("[Link]", "r")
print([Link]())
Output:
[Link]
OVERWRITE THE CONTENTS IN FILE
The overwriting in a file is done by using the keyword
‘W’, it deletes the contents present previously and
replace it with the content we give .
Example
f = open("[Link]", "w")
[Link]("Woops! I have deleted the content!")
[Link]()
f = open("[Link]", "r")
print([Link]())
[Link]
Output:
Woops! I have deleted the content!
[Link]
APPEND TEXT TO A FILE
f = open("[Link]", "a")
[Link]("Now the file has more content!")
[Link]()
f = open("[Link]", "r")
print([Link]())
[Link]
OUTPUT
[Link]
CREATE A NEW FILE
Example
Create a file called "[Link]":
f = open("[Link]", "x")
Example
Create a new file if it does not exist:
f = open("[Link]", "w")
[Link]
PYTHON DELETE FILE
Example
Remove the file "[Link]":
import os
[Link]("[Link]")
[Link]
CHECK IF FILE EXIST:
import os
if [Link]("[Link]"):
[Link]("[Link]")
else:
print("The file does not exist")
[Link]
DELETE FOLDER
import os
[Link]("myfolder")
[Link]
PYTHON DATE AND
TIME
[Link]
PYTHON DATETIME
import datetime
datetime_object = [Link]()
print(datetime_object)
[Link]
GET CURRENT DATE
EXAMPLE:
import datetime
date_object = [Link]() print(date_object)
OUTPUT
2020-04-07
[Link]
DATE TIME CLASS
Commonly used classes in the datetime module are:
date Class
time Class
datetime Class
timedelta Class
[Link]
[Link] CLASS
The date class accepts a date from the user
Example
import datetime
d = [Link](2020, 4, 07)
print(d)
OUTPUT
2020-04-07
[Link]
PRINT TODAY'S YEAR, MONTH AND
DAY
EXAMPLE
from datetime import date
today = [Link]( )
Current month: 04
Current DAY: 07
[Link]
[Link] CLASS
a = time( )
print("a =", a)
print("b =", b)
[Link]
OUTPUT
a = [Link]
b = [Link]
c = [Link]
d = [Link].234566
[Link]
PRINT HOUR, MINUTE, SECOND AND MICROSECOND
EXAMPLE:
from datetime import time
[Link]
OUTPUT
hour = 11
minute = 34
second = 56
microsecond = 0
[Link]
[Link] CLASS
EXAMPLE:
print(a)
[Link]
OUTPUT
2020-11-28 [Link]
2020-11-28 [Link].342380
[Link]
[Link]
[Link]
t5 = datetime(year = 2019, month = 6, day = 10, hour =
5, minute = 55, second = 13)
t6 = t4 - t5
OUTPUT:
t3 = 201 days, [Link]
[Link]
DIFFERENCE BETWEEN TWO TIMEDELTA
OBJECTS
EXAMPLE
[Link]
OUTPUT
t3 = 14 days, [Link]
[Link]
PYTHON STRFTIME()
[Link]
EXAMPLE
From datetime import datetime
now = [Link]()
t = [Link]("%H:%M:%S")
print("time:", t)
s1 = [Link]("%m/%d/%Y, %H:%M:%S")
print("s1:", s1)
s2 = [Link]("%d/%m/%Y, %H:%M:%S")
print("s2:", s2)
[Link]
OUTPUT:
time: [Link]
s1: 04/07/2018, [Link]
[Link]
PYTHON STRPTIME() - STRING TO DATETIME
[Link]
EXAMPLE:
from datetime import datetime
[Link]
OUTPUT:
date_string = 21 June, 2018
[Link]
PYTHON
EXCEPTION
HANDLING
[Link]
PYTHON EXCEPTION HANDLING
When an error occurs, or exception as we call it, Python
will normally stop and generate an error message
[Link]
TRY BLOCK
The try block raises an error, the except block will
handle the error and the output in the except block will
be executed
Example:
try:
print(x)
except:
print("An exception occurred")
Example:
Print one message if the try block raisesNameError and
another for other errors.
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong"
[Link]
OUTPUT:
[Link]
We can use the else keyword to define a block of code to
be executed if no errors were raised
Example
Nothing went wrong
[Link]
FINALLY BLOCK
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
[Link]
Output:
[Link]
RAISE AN EXCEPTION
EXAMPLE:
Example
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
[Link]
OUTPUT:
Traceback (most recent call last):
File "demo_ref_keyword_raise.py", line 4, in
<module>
raise Exception("Sorry, no numbers below zero")
Exception: Sorry, no numbers below zero
[Link]
Example
Raise a TypeError if x is not an integer:
x = "hello"
[Link]
OUTPUT:
Traceback (most recent call last):
File "demo_ref_keyword_raise2.py", line 4, in
<module>
raise TypeError("Only integers are allowed")
TypeError: Only integers are allowed
[Link]
PYTHON- MY
SQL
[Link]
PYTHON MYSQL DATABASE CONNECTION
[Link]
The [Link]() to execute SQL queries from
Python
[Link]
PYTHON EXAMPLE TO CONNECT MYSQL DATABASE
[Link]
Host Name – is the server name or Ip address on which
MySQL is running. if you are running on localhost, then
you can use localhost, or it’s IP, i.e. [Link]
Database Name – Database name to which you want to
connect. Here we are using Database named
‘Electronics‘ because we have already created this for
our example
[Link]
EXAMPLE TO CREATE A DATABASE
CONNECTION
Create database Electronics;
import [Link] from [Link] import
Error
try: connection = [Link](host='localhost',
database='Electronics', user=‘root', password=‘ ‘)
if connection.is_connected():
db_Info = connection.get_server_info() print("Connected
to MySQL Server version ", db_Info) cursor =
[Link]( )
[Link]("select database( );")
record = [Link]() [Link]
print("You're connected to database: ", record)
except Error as e:
print("Error while connecting to MySQL", e)
finally:
if (connection.is_connected( )):
[Link]( )
[Link]( )
print("MySQL connection is closed")
[Link]
OUTPUT
Connected to MySQL Server version 5.7.19
[Link]
UNDERSTAND THE PYTHON MYSQL
DATABASE CONNECTION PROGRAM
import [Link]
This line imports the MySQL Connector Python module
in your program so you can use this module’s API to
connect MySQL.
from [Link] import Error
[Link]
[Link]()
Using this method we can connect the MySQL Database,
this method accepts four required parameters: Host,
Database, User and Password that we already
discussed.
connect() method established a connection to the
MySQL database from Python application and returned a
MySQLConnection object. Then we can use
MySQLConnection object to perform various operations
on the MySQL Database.
[Link]
The Connect() method can throw an exception, i.e.
Database error if one of the required parameters is
wrong. For example, if you provide a database name that
is not present in MySQL, then Python application throws
an exception. So check the arguments that you are
passing to this method.
connection.is_connected()
[Link]
[Link]()
This method returns a cursor object. Using a cursor object, we
can execute SQL queries.
The MySQLCursor class instantiates objects that can execute
operations such as SQL statements.
Cursor objects interact with the MySQL server using a
MySQLConnection object.
[Link]()
Using the cursor’s close method we can close the cursor
object. Once we close the cursor object, we can not execute
any SQL statement.
[Link]
[Link]()
At last, we are closing the MySQL database connection
using a close() method of MySQLConnection class.
[Link]
PYTHON MYSQL CREATE TABLE
import [Link]
from [Link] import Error
try: connection =
[Link](host='localhost',
database='Electronics', user='pynative',
password='pynative@#29')
[Link]
mySql_Create_Table_Query = """CREATE TABLE
Laptop ( Id int(11) NOT NULL, Name
varchar(250) NOT NULL, Price float NOT
cursor = [Link]()
result = [Link](mySql_Create_Table_Query)
[Link]
except [Link] as error: print("Failed to
create table in MySQL: {}".format(error))
finally:
if (connection.is_connected( )):
[Link]( )
[Link]( )
print("MySQL connection is closed")
[Link]
OUTPUT
Laptop Table created successfully
[Link]
PYTHON INSERT INTO MYSQL TABLE
try:
connection = [Link](host='localhost',
database='electronics', user='root', password=‘ ‘)
[Link]
mySql_insert_query = """INSERT INTO Laptop (Id,
Name, Price, Purchase_date) VALUES (10, 'Lenovo
ThinkPad P71', 6459, '2019-08-14') """
cursor = [Link]()
[Link](mySql_insert_query)
[Link]( )
[Link]
except [Link] as error: print("Failed to
insert record into Laptop table {}".format(error))
finally:
if (connection.is_connected( )):
[Link]( )
[Link]
OUTPUT
Record inserted successfully into Laptop table
[Link]
PYTHON SELECT FROM MYSQL
TABLE
[Link]
EXAMPLE FOR MY SQL SELECT
import [Link]
from [Link] import Error
try:
connection = [Link](host='localhost',
database='Electronics', user=‘root', password=‘ ‘)
[Link]
sql_select_Query = "select * from Laptop"
cursor = [Link]( )
[Link](sql_select_Query)
records = [Link]( )
[Link]
for row in records:
print("Id = ", row[0], )
print("Name = ", row[1])
print("Price = ", row[2])
print("Purchase date = ", row[3], "\n")
except Error as e:
print("Error reading data from MySQL table", e)
[Link]
finally:
if (connection.is_connected()):
[Link]( )
[Link]( )
[Link]
OUTPUT
Total number of rows in Laptop is: 7
Printing each laptop record
Id = 1
Price = 6459.0
[Link]
PYTHON UPDATE MYSQL TABLE
[Link]
import [Link]
from [Link] import Error
try:
connection = [Link](host='localhost',
database='Electronics', user=‘root', password=‘ ‘)
[Link]
cursor = [Link]( )
print("Before updating a record ") sql_select_query =
"""select * from Laptop where id = 1"""
[Link](sql_select_query)
[Link]
sql_update_query = """Update Laptop set Price = 7000
where id = 1"""
[Link](sql_update_query)
[Link]( )
[Link](sql_select_query)
finally:
if (connection.is_connected()):
[Link]( )
print("MySQL connection is closed")
[Link]
OUTPUT
Before updating a record
(1, 'Lenovo ThinkPad P71', 6459.0, [Link](2019,
8, 14))
Record Updated successfully
[Link]
PYTHON DELETE DATA FROM MYSQL
TABLE
import [Link]
from [Link] import Error
try:
connection = [Link](host='localhost',
database='Electronics', user=‘root', password=‘ ‘)
[Link]
cursor = [Link]( )
delete_table_query = """DROP TABLE Laptop"""
[Link](delete_table_query)
delete_database_query = """DROP DATABASE
Electronics""" [Link](delete_database_query)
[Link]( )
print("Table and Database Deleted successfully ")
[Link]
except [Link] as error:
print("Failed to Delete table and database:
{}".format(error))
finally:
if (connection.is_connected( )):
[Link]( ) [Link]( )
print("MySQL connection is closed")
[Link]
OUTPUT
Table and Database Deleted successfully
[Link]