You are on page 1of 308

PYTHON - TUTORIAL

379A, 4th floor, K. P ROAD,


NEAR COLLECTORATE, NAGERCOIL-629001
PHONE: 04652-230105, 9498029898
INTRODUCTION
 Python was conceptualized in the late 1980s.

 Guido Van Rossum published the first version of Python


code in February 1991. This release included already
exception handling, functions, and the core data types of
list, dict, str and others. It was also object oriented and
had a module system.

www.careerin.co.in
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

www.careerin.co.in
INTRODUCTION
 Python was conceptualized in the late 1980s.

 Guido Van Rossum published the first version of Python


code in February 1991. This release included already
exception handling, functions, and the core data types of
list, dict, str and others. It was also object oriented and
had a module system.

www.careerin.co.in
PYTHON
VARIABLES

www.careerin.co.in
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.

 What we have said so far about variables best fits the


way variables are implemented in C, C++ or Java.
Variable names have to be declared in these languages
before they can be used.

www.careerin.co.in
 Eg: int x;
int y;

 x,y are the variables declared by its data types.

www.careerin.co.in
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.

www.careerin.co.in
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

www.careerin.co.in
VARIABLE NAMES

 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)
 #Legal variable names:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
www.careerin.co.in
 #Illegal variable names:
2myvar = "John"
my-var = "John"
my var = "John"

www.careerin.co.in
ASSIGN VALUE TO MULTIPLE VARIABLES

 x, y, z = "Orange", "Banana", "Cherry"


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

 Output: orange
banana
cherry

www.careerin.co.in
OUTPUT VARIABLES

 The Python print statement is often used to output


variables.
 To combine both text and a variable, Python uses the +
character
 x = "awesome"
print("Python is " + x)

 Output: Python is awesome

www.careerin.co.in
 You can also use the + character to add a variable to
another variable:
Example
 x = "Python is "
y = "awesome"
z =  x + y
print(z)

 Output: Python is awesome

www.careerin.co.in
 For numbers, the + character works as a mathematical
operator:
 Example

x=5
y = 10
print(x + y)

 Output: 15

www.careerin.co.in
 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'
www.careerin.co.in
Python Data Types

www.careerin.co.in
PYTHON DATA TYPES

 Python has the following data types built-in by default,


in these categories:
 Text Type: str

 Numeric Types: int, float, complex

 Sequence Types: list, tuple, range

 Mapping Type: dict

 Set Types: set, frozenset

 Boolean Type: bool

 Binary Types: bytes, bytearray, memoryview

www.careerin.co.in
 Getting the Data Type
 You can get the data type of any object by using the
type() function:
 Example

 Print the data type of the variable x:

x=5
print(type(x))

 Output: ​<class 'int'>

www.careerin.co.in
PYTHON NUMBERS

 There are three numeric types in Python:


 int

 float

 Complex

 Example
 x = 1    # int
y = 2.8  # float
z = 1j   # complex

www.careerin.co.in
INT

 Int, or integer, is a whole number, positive or negative,


without decimals, of unlimited length.
 Example

 Integers:

x=1
y = 35656222554887711
z = -3255522

www.careerin.co.in
FLOAT

 Float, or "floating point number" is a number, positive or


negative, containing one or more decimals.

 Example
 Floats:

 x = 1.10
y = 1.0
z = -35.59

www.careerin.co.in
COMPLEX

 Complex numbers are written with a "j" as the imaginary


part

 Example
 Complex:

 x = 3+5j
y = 5j
z = -5j

www.careerin.co.in
RANDOM NUMBER

 Python has a built-in module called random that can be


used to make random numbers

 Example
 Import the random module, and display a random
number between 1 and 9:
 import random

print(random.randrange(1,10))

www.careerin.co.in
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)

www.careerin.co.in
 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

www.careerin.co.in
 Example
 Integers:

 x = int(1)   # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3

www.careerin.co.in
 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

www.careerin.co.in
 Strings:
 x = str("s1") # x will be 's1'
y = str(2)    # y will be '2'
z = str(3.0)  # z will be '3.0'

www.careerin.co.in
PYTHON STRINGS

www.careerin.co.in
PYTHON STRINGS

 Strings in python are surrounded by either single


quotation marks, or double quotation marks.

 'hello' is the same as "hello".

 Example
 print("Hello")
print('Hello')

www.careerin.co.in
 Assigning a string to a variable is done with the variable
name followed by an equal sign and the string:
 a = "Hello"
print(a)

 You can assign a multiline string to a variable by using


three quotes:

www.careerin.co.in
 a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.""“

print(a)

www.careerin.co.in
STRINGS ARE ARRAYS

 Python does not have a character data type, a single


character is simply a string with a length of 1.
 Square brackets can be used to access elements of the
string.

 a = "Hello, World!"
print(a[1])
 Output: e

www.careerin.co.in
STRING SLICING

 You can return a range of characters by using the slice


syntax.
 Specify the start index and the end index, separated by a
colon, to return a part of the string.
 b = "Hello, World!"
print(b[2:5])

Output: llo

www.careerin.co.in
NEGATIVE INDEXING

 Use negative indexes to start the slice from the end of


the string: Example
 Get the characters from position 5 to position 1, starting
the count from the end of the string:
 b = "Hello, World!"
print(b[-5:-2])

 Output: orl

www.careerin.co.in
STRING LENGTH

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

 a = "Hello, World!"
print(len(a))

 Output:13

www.careerin.co.in
STRING METHODS

 The strip() method removes any whitespace from the


beginning or the end:
 a = " Hello, World! "
print(a.strip())
 The lower() method returns the string in lower case:

 a = "Hello, World!"
print(a.lower())

www.careerin.co.in
 The upper() method returns the string in upper case:
 a = "Hello, World!"
print(a.upper())

 The replace() method replaces a string with another


string:
 a = "Hello, World!"
print(a.replace("H", "J"))

www.careerin.co.in
 The split() method splits the string into substrings if it
finds instances of the separator:
 a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']

www.careerin.co.in
CHECK STRING

 To check if a certain phrase or character is present in a


string, we can use the keywords in or not in
 Example

 Check if the phrase "ain" is present in the following text:

 txt = "The rain in Spain stays mainly in the plain"


x = "ain" in txt
print(x)
 output: True

www.careerin.co.in
 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

www.careerin.co.in
STRING FORMAT

 we can combine strings and numbers by using the


format() method!
 The format() method takes the passed arguments,
formats them, and places them in the string where the
placeholders {}
 age = 36
txt = ("My name is John, and I am {}“)
print(txt.format(age))

www.careerin.co.in
 Output:
 My name is John, and I am 36

www.careerin.co.in
 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(myorder.format(quantity, itemno, price))

www.careerin.co.in
 Output:
 I want 3 pieces of item 567 for 49.95 dollars.

www.careerin.co.in
 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(myorder.format(quantity, itemno, price))

www.careerin.co.in
 Output:

 I want to pay 49.95 dollars for 3 pieces of item 567

www.careerin.co.in
PYTHON
BOOLEANS

www.careerin.co.in
PYTHON BOOLEANS

 Booleans represent one of two values: True or False.


 In programming you often need to know if an expression
is True or False.
 You can evaluate any expression in Python, and get one
of two answers, True or False.
 When you compare two values, the expression is
evaluated and Python returns the Boolean answer

www.careerin.co.in
 print(10 > 9)
print(10 == 9)
print(10 < 9)

 Output:
 True
False
False

www.careerin.co.in
 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

www.careerin.co.in
EVALUATE VALUES AND VARIABLES

 The bool() function allows you to evaluate any value,


and give you True or False in return,
 Example

 Evaluate a string and a number:

 print(bool("Hello"))
print(bool(15))
 Output:

 True
True

www.careerin.co.in
 Almost any value is evaluated to True if it has some sort
of content.
 Any string is True, except empty strings.

 Any number is True, except 0.

 Example

 The following will return True:

 bool("abc")
bool(123)

www.careerin.co.in
 Output:True
True
True

www.careerin.co.in
 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

 The following will return False:

 bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
www.careerin.co.in
bool({})
 Output:
 False
False
False
False
False
False
False

www.careerin.co.in
PYTHON
OPERATORS

www.careerin.co.in
PYTHON OPERATORS

 operators are used to perform operations on variables


and values.
 Python divides the operators in the following groups:

 Arithmetic operators

 Assignment operators

 Comparison operators

www.careerin.co.in
 Logical operators
 Identity operators

 Membership operators

 Bitwise operators

www.careerin.co.in
PYTHON ARITHMETIC OPERATORS

 Operator Name Example output


 + Addition 5+ 6 11
 - Subtraction 8–4 4
 * Multiplication 2 * 3 6
 / Division 6/2 3
 % Modulus 7% 3 1
 ** Exponentiation 2** 5 32
 // Floor division 15//7 2

www.careerin.co.in
PYTHON ASSIGNMENT OPERATORS

www.careerin.co.in
PYTHON COMPARISON OPERATORS

www.careerin.co.in
PYTHON LOGICAL OPERATORS

www.careerin.co.in
PYTHON IDENTITY OPERATORS

 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 x is y
if both variables are
the same object
 is not Returns True if both x is not y
variables are not the same object

www.careerin.co.in
 x = ["apple", "banana"]
 y = ["apple", "banana"]

 z=x

 print(x is z)

 # returns True because z is the same object as x

 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 www.careerin.co.in
 x = ["apple", "banana"]
 y = ["apple", "banana"]

 z=x

 print(x is not z)

 # returns False because z is the same object as x

 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 www.careerin.co.in
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

www.careerin.co.in
 x = ["apple", "banana"]
 print("banana" in x)

 # returns True because a sequence with the value


"banana" is in the list

 x = ["apple", "banana"]
 print("pineapple" not in x)

 # returns True because a sequence with the value


"pineapple" is not in the list

www.careerin.co.in
PYTHON BITWISE OPERATORS

www.careerin.co.in
INDENTATION IN YTHON

 Indentation in Python refers to the spaces and tabs that


are used at the beginning of a statement. The statements
with the same indentation belong to the same group
called a suite
 Example:

 if a==1:

 print(a)
 if b==2:
 print(b)
 print('end')

www.careerin.co.in
PYTHON USER INPUT

 Python allows for user input.


 That means we are able to ask the user for input.

 Python 3.6 uses the input() method.

 Python 2.7 uses the raw_input() method.

 EXAMPLE:
 username = input("Enter username:")
print("Username is: " + username)

www.careerin.co.in
 OUTPUT:

 Enter the user name: careerIN


 Username is careerIN

www.careerin.co.in
INTEGER AS AN INPUT
 EXAMPLE:
 x = int(input("Enter a number: "))

 Print(x)

 y = int(input("Enter second number: "))

 Print(y)

 Output:
 Enter a number: 22

 22

 Enter second number: 25

 25 www.careerin.co.in
PYTHON
CONDITIONAL
STATEMENTS

www.careerin.co.in
PYTHON IF ... ELSE

 An "if statement" is written by using the if keyword.


 a = 33
b = 200
if b > a:
  print("b is greater than a")
 Output:

 b is greater than a

www.careerin.co.in
ELIF

 The elif keyword is pythons way of saying "if the


previous conditions were not true, then try this
condition"..
 a = 33
b = 33
if b > a:
  print("b is greater than a")
elif a == b:
  print("a and b are equal")
 Output:

 a and b are equal

www.careerin.co.in
ELSE

 The else keyword is used when the previous conditions


are not satisfied.
 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")

Output: a is greater than b www.careerin.co.in


PYTHON WHILE
LOOPS

www.careerin.co.in
PYTHON WHILE LOOPS

 The while loop can execute a set of statements as long


as a condition is true.

 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
www.careerin.co.in
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

www.careerin.co.in
THE CONTINUE STATEMENT

the continue statement stops the current iteration, and


continue with the next
i=0
while i < 6:
  i += 1
  if i == 3:
    continue
  print(i)

 Output: 1 2 4 5 6

www.careerin.co.in
THE ELSE STATEMENT

 The else statement runs a block of code once when the


condition in the while loop no longer is true.
i=1
while i < 6:
  print(i)
  i += 1
else:
  print("i is no longer less than 6")
 Output: 1 2 3 4 5

 i is no longer less than 6

www.careerin.co.in
PYTHON FOR
LOOPS

www.careerin.co.in
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

 For[new variable]in[iterating variable]:

 Example

 Print each fruit in a fruit list:

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


for x in fruits:
  print(x)
 Output: apple banana cherry

www.careerin.co.in
LOOPING THROUGH A STRING
 Even strings are iterable objects, they contain a sequence of
characters
 Example

 Loop through the letters in the word "banana":

 for x in "banana":
  print(x)
 Output: b

 a
 n
 a
 n
 a
www.careerin.co.in
THE BREAK STATEMENT
 The break statement stops the loop before it has looped
through all the items
 Example

 Exit the loop when x is "banana":

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


for x in fruits:
  print(x)
  if x == "banana":
    break
 Output: apple

 banana

www.careerin.co.in
THE CONTINUE STATEMENT
 The continue statement stops the current iteration of the
loop, and continue with the next
 Example

 Do not print banana:

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


for x in fruits:
  if x == "banana":
    continue
  print(x)
 Output: apple

 cherry
www.careerin.co.in
THE RANGE() FUNCTION

 To loop through a set of code a specified number of times, we can


use the range() function
 Example

 Using the range() function:

 for x in range(6):
  print(x)
 Output: 0 1 2 3 4 5

 Example

 Using the start parameter:

 for x in range(2, 6):


  print(x)
 Output: 2 3 4 5

www.careerin.co.in
 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

 Increment the sequence with 3 (default is 1):

 for x in range(2, 30, 3):


  print(x)
 Output : 2 5 8 11 14 17 20 23 26 29

www.careerin.co.in
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

 Print all numbers from 0 to 5, and print a message when


the loop has ended:
 for x in range(6):
  print(x)
else:
  print("Finally finished!")
 Output: 0 1 2 3 4 5

 finally finished
www.careerin.co.in
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

 adj = ["red", "big", "tasty"]


fruits = ["apple", "banana", "cherry"]
for x in adj:
  for y in fruits:
    print(x, y)
 Output: red apple red banana red cherry big apple
big banana big cherry tasty apple tasty banana
tasty cherry
www.careerin.co.in
THE PASS STATEMENT

 The for loops cannot be empty, but if you for some


reason have a for loop with no content, put in the pass
statement to avoid getting an error.
 Example

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


  pass

www.careerin.co.in
PYTHON
FUNCTIONS

www.careerin.co.in
PYTHON FUNCTIONS

 A function is a structuring element in programming


languages to group a set of statements so they can be
utilized more than once in a program.
 A function is a block of code which only runs when it is
called.You can pass data, known as parameters, into a
function.
 A function can return data as a result.

www.careerin.co.in
CREATING A FUNCTION

 In Python a function is defined using the def keyword

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

www.careerin.co.in
CALLING A FUNCTION

 To call a function, use the function name followed by


parenthesis
 Example

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

my_function()
 output: Hello from a function

www.careerin.co.in
ARGUMENTS

 Information can be passed into functions as arguments.


 Arguments are specified after the function name, inside
the parentheses. You can add as many arguments as you
want, just separate them with a comma.
 The following example has a function with one argument
(fname). When the function is called, we pass along a
first name, which is used inside the function to print the
full name

www.careerin.co.in
 Example
 def my_function(fname):
  print(fname + " kumar")

my_function(“Muthu")
my_function(“Ramesh")
my_function(“Raj")
 Output: muthu kumar

 Ramesh kumar
 Raj kumar

www.careerin.co.in
ARGUMENT TYPE
 The Function arugments are of four types
 Required arguments

 Keyword arguments

 Default arguments

 Variable-length arguments

www.careerin.co.in
REQUIRED ARGUMENTS

 Required arguments are the arguments passed to a


function in correct positional order. Here, the number of
arguments in the function call should match exactly with
the function definition.
 Example:

 def printme( str ):

 print (str )
 printme(“hello”)

 Output: hello
www.careerin.co.in
KEYWORD ARGUMENTS

 Keyword arguments are related to the function calls.


When you use keyword arguments in a function call, the
caller identifies the arguments by the parameter name.
 This allows you to skip arguments or place them out of
order because the Python interpreter is able to use the
keywords provided to match the values with parameters.

www.careerin.co.in
 Example
 def printinfo( name, age ):

 print ("Name: ", name)

 print ("Age ", age)

 printinfo( age=50, name="miki" )

 Output:
 Name: miki

 Age 50

www.careerin.co.in
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:

 def printinfo( name, age = 35 ):

 print("Name: ", name )


 print("Age ", age)
 printinfo( age=50, name="miki" )

 printinfo( name="miki" )

www.careerin.co.in
VARIABLE-LENGTH ARGUMENTS
 A function for more arguments than you specified while
defining the function. These arguments are called
variable-length arguments
 Example:

 def printinfo( arg1, *vartuple ):

 print ("Output is: “)


 print (arg1)
 for var in vartuple:

 print (var)
 printinfo( 10 )

 printinfo( 70, 60, 50 )

www.careerin.co.in
 Output:
 10

 70 60 50

www.careerin.co.in
THE RETURN STATEMENT

 The statement return [expression] exits a function,


optionally passing back an expression to the caller.
 Example:

 def sum( arg1, arg2 ):

 total = arg1 + arg2


 print(“sum : ", total)
 return total
 abc = sum( 10, 20 )

 print (“Addition : ", abc )

www.careerin.co.in
 Output:
 Sum:30

 abc: 30

www.careerin.co.in
PYTHON LISTS

www.careerin.co.in
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"]

www.careerin.co.in
ACCESS ITEMS IN A LIST

 A list can be accessed by referring to the index number


to be accessed.

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

www.careerin.co.in
NEGATIVE INDEXING
 Negative indexing means beginning from the end, -1
refers to the last item, -2 refers to the second last item etc
 Example:

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


print(thislist[-1])

 Output: cherry

www.careerin.co.in
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
 Example:

 thislist = ["apple", "banana", "cherry", "orange", "kiwi",


"melon", "mango"]
print(thislist[2:5])
 Output: ['cherry', 'orange', 'kiwi']

www.careerin.co.in
 Example:
 thislist = ["apple", "banana", "cherry", "orange", "kiwi",
"melon", "mango"]
print(thislist[:4])

 Output: ['apple', 'banana', 'cherry', 'orange']


 The item in index 4 is NOT included

www.careerin.co.in
 thislist = ["apple", "banana", "cherry", "orange", "kiwi",
"melon", "mango"]
print(thislist[2:])

 Output: ['cherry', 'orange', 'kiwi', 'melon', 'mango']


 This will return the items from index 2 to the end

www.careerin.co.in
RANGE OF NEGATIVE INDEXES

 negative indexing means starting from the end of the list.


 Specify negative indexes if you want to start the search
from the end of the list
 Example:

 thislist = ["apple", "banana", "cherry", "orange", "kiwi",


"melon", "mango"]
print(thislist[-4:-1])

www.careerin.co.in
 This example returns the items from index -4 (included)
to index -1 (excluded)

 Output:
 ['orange', 'kiwi', 'melon']

www.careerin.co.in
CHANGE ITEM VALUE

 To change the value of a specific item, refer to the index


number
 Example

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


thislist[1] = "blackcurrant"
print(thislist)

 Output: ['apple', 'blackcurrant', 'cherry']

www.careerin.co.in
LOOP THROUGH A LIST

 A list can be looped by using for loop and it prints all


items in the list, one by one
 thislist = ["apple", "banana", "cherry"]
for x in thislist:
  print(x)

 Output:
 apple
banana
cherry

www.careerin.co.in
CHECK IF ITEM EXISTS

 To determine if a specified item is present in a list use


the in keyword

 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

www.careerin.co.in
LIST LENGTH

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


function

 Example
 Print the number of items in the list:

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


print(len(thislist)
 Output: 3

www.careerin.co.in
ADD ITEMS

 To add an item to the end of the list, use the append()


method

Example
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
Output:
['apple', 'banana', 'cherry', 'orange']

www.careerin.co.in
INSERT() METHOD
 To add an item at the specified index, use the insert()
method
 Example

 Insert an item as the second position:

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


thislist.insert(1, "orange")
print(thislist)
 Output:

 ['apple', 'orange', 'banana', 'cherry']

www.careerin.co.in
REMOVE ITEM

 The item in a list can be removed by using remove( ),


pop( ) , clear( ) and del keywords.
 Example

 The remove() method removes the specified item:

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


thislist.remove("banana")
print(thislist)

Output:['apple', 'cherry']

www.careerin.co.in
 The pop() method removes the specified index, (or the
last item if index is not specified)
 Example

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


thislist.pop()
print(thislist)

 Output: ["apple", "banana"]

www.careerin.co.in
 The del keyword removes the specified index
 thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)

 Output: ["banana", "cherry"]

www.careerin.co.in
 The clear() method empties the list:
 Example

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


thislist.clear()
print(thislist)

 Output: [ ]

www.careerin.co.in
COPY A LIST

 The copy of a list can be made by using list( ) and


copy( )
 Example :

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


mylist = thislist.copy()
print(mylist)

 Output: ["apple", "banana", "cherry"]

www.careerin.co.in
 thislist = ["apple", "banana", "cherry"]
mylist = list(thislist)
print(mylist)

 Output: ["apple", "banana", "cherry"]

www.careerin.co.in
JOIN TWO LISTS

 There are several ways to join, or concatenate, two or


more lists in Python.
 One of the easiest ways are by using the + operator

 Example

 Join two list:

 list1 = ["a", "b" , "c"]


list2 = [1, 2, 3]

list3 = list1 + list2


print(list3)

www.careerin.co.in
 Output: ['a', 'b', 'c', 1, 2, 3]

 the extend() method can be used to add elements from one


list to another list
 Example

 Use the extend() method to add list2 at the end of list1:

 list1 = ["a", "b" , "c"]


list2 = [1, 2, 3]

list1.extend(list2)
print(list1)

www.careerin.co.in
 Output:
 ['a', 'b', 'c', 1, 2, 3]

www.careerin.co.in
THE LIST() CONSTRUCTOR

 It is also possible to use the list() constructor to make a


new list
 Example

 Using the list() constructor to make a List:

 thislist = list(("apple", "banana", "cherry"))


print(thislist)
 Output: ['apple', 'banana', 'cherry']

www.careerin.co.in
PYTHON SETS

www.careerin.co.in
PYTHON SETS

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


In Python sets are written with curly brackets.
 Example

 Create a Set:

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


print(thisset)

 Output: {'banana', 'cherry', 'apple'}

www.careerin.co.in
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

 Loop through the set, and print the values:

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


for x in thisset:
  print(x)

www.careerin.co.in
 Output: cherry
banana
apple
 Example

 Check if "banana" is present in the set:

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


print("banana" in thisset)
 Output: True

www.careerin.co.in
CHANGE ITEMS IN A SET

 Once a set is created, you cannot change its items, but


you can add new items

 To add one item to a set use the add() method.


 To add more than one item to a set use the update()
method.
 To determine how many items a set has, use the len()
method.

www.careerin.co.in
 Example:
 thisset = {"apple", "banana", "cherry"}

thisset.add("orange")

print(thisset)

 Output: {'cherry', 'banana', 'apple', 'orange'}

www.careerin.co.in
 Add multiple items to a set, using the update() method:
 Example:

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

thisset.update(["orange", "mango", "grapes"])

print(thisset)
Output:{'grapes', 'mango', 'orange', 'apple', 'cherry',
'banana'}

www.careerin.co.in
 To determine how many items a set has, use the len()
method.
 Example

 Get the number of items in a set:

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

print(len(thisset))

 Output: 3

www.careerin.co.in
REMOVE ITEM
 To remove an item in a set, use the remove(), or the
discard() method.
 Example

 Remove "banana" by using the remove() method:

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


thisset.remove("banana")
print(thisset)
 Output: {"apple", "cherry"}

 Note: If the item to remove does not exist, remove() will


raise an error.
www.careerin.co.in
 Example
 thisset = {"apple", "banana", "cherry"}
thisset.discard("banana")
print(thisset)

 Output: {'cherry', 'apple'}

 Note: If the item to remove does not exist, discard() will


NOT raise an error.

www.careerin.co.in
 Remove the last item by using the pop() method:
 Example

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


x = thisset.pop()
print(x)
 print(thisset)

 Output: apple
{'banana', 'cherry'}

www.careerin.co.in
 The clear() method empties the set:

 Example:
 thisset = {"apple", "banana", "cherry"}
thisset.clear()
print(thisset)

 Output: set()

www.careerin.co.in
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 = set1.union(set2)
print(set3)

www.careerin.co.in
 Output:
 {2, 'a', 1, 3, 'c', 'b'}

 The update() method inserts the items in set2 into set1


 Example:

 set1 = {"a", "b" , "c"}

 set2 = {1, 2, 3}

 set1.update(set2)

 print(set1

www.careerin.co.in
 Output: {3, 'a', 'b', 1, 2, 'c'}

 Note: Both union() and update() will exclude any


duplicate items.

www.careerin.co.in
 The set() Constructor
 It is also possible to use the set() constructor to make a
set.
 Example

 Using the set() constructor to make a set:

 thisset = set(("apple", "banana", "cherry")) # note the


double round-brackets
print(thisset)
 output: {'banana', 'apple', 'cherry'}

www.careerin.co.in
PYTHON TUPLES

www.careerin.co.in
PYTHON TUPLES

 A tuple is a collection which is ordered and


unchangeable. In Python tuples are written with round
brackets
 Example

 Create a Tuple:

 thistuple = ("apple", "banana", "cherry")


print(thistuple)

 Output: ('apple', 'banana', 'cherry')

www.careerin.co.in
ACCESS TUPLE ITEMS

 Tuple items can be accessed by referring to the index


number, inside square brackets
 Example

 Print the second item in the tuple:

 thistuple = ("apple", "banana", "cherry")


print(thistuple[1])
 Output:

 banana

www.careerin.co.in
NEGATIVE INDEXING

 Negative indexing means beginning from the end, -1


refers to the last item, -2 refers to the second last item etc
 Example

 Print the last item of the tuple:

 thistuple = ("apple", "banana", "cherry")


print(thistuple[-1])
 Output:

 cherry

www.careerin.co.in
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
tuple with the specified items
 Example

 thistuple = ("apple", "banana", "cherry", "orange",


"kiwi", "melon", "mango")
print(thistuple[2:5]
 Output:('cherry', 'orange', 'kiwi')

www.careerin.co.in
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

 x = ("apple", "banana", "cherry")


y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
www.careerin.co.in
 Output:("apple", "kiwi", "cherry")

 Loop Through a Tuple


 You can loop through the tuple items by using a for loop.

 Example

 thistuple = ("apple", "banana", "cherry")


for x in thistuple:
  print(x)
 Output:apple
banana
cherry
www.careerin.co.in
CHECK IF ITEM EXISTS

 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

www.careerin.co.in
ADD ITEMS

 Once a tuple is created, you cannot add items to it.


Tuples are unchangeable
 Example

 thistuple = ("apple", "banana", "cherry")


thistuple[3] = "orange"
print(thistuple)

 Output: TypeError: 'tuple' object does not support item


assignment

www.careerin.co.in
REMOVE ITEMS

 Tuples are unchangeable, so you cannot remove items


from it, but you can delete the tuple completely

 Example:
 The del keyword can delete the tuple completely:

 thistuple = ("apple", "banana", "cherry")


del thistuple
print(thistuple)
 Output:NameError: name 'thistuple' is not defined

www.careerin.co.in
JOIN TWO TUPLES

 To join two or more tuples you can use the + operator


 Example

 tuple1 = ("a", "b" , "c")


tuple2 = (1, 2, 3)

tuple3 = tuple1 + tuple2


print(tuple3)
 Output:('a', 'b', 'c', 1, 2, 3)

www.careerin.co.in
THE TUPLE() CONSTRUCTOR

 It is also possible to use the tuple() constructor to make a


tuple

 Example:
 thistuple = tuple(("apple", "banana", "cherry"))
print(thistuple)

 Output:('apple', 'banana', 'cherry')

www.careerin.co.in
PYTHON-
DICTIONARIES

www.careerin.co.in
PYTHON DICTIONARIES

 A dictionary is a collection which is unordered,


changeable and indexed. In Python dictionaries are
written with curly brackets, and they have keys and
values.

 Dict_name = { “key1”: “value1”, “key2”:”value2”}

 Dictionaries belong to the built-in mapping type

www.careerin.co.in
 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.

www.careerin.co.in
 Ouput:
 {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

www.careerin.co.in
ACCESSING ITEMS IN DICTIONARY

 The items of a dictionary can be accessed by referring to


the dictionary name followed by key name, inside
square brackets
 Example

 Create and print a dictionary:

 thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
 x = thisdict["model"]

 Print(x) www.careerin.co.in
 Output: Mustang

 There is also a method called get() that will give you the
same result

 x = thisdict.get("model")
 Print(x)

 Output: Mustang

www.careerin.co.in
CHANGE VALUES IN A DICTIONARY

 The value of specific item in dictionary can be changed


by referring to its key name
 Example:

 capital ={"Austria":"Vienna", "Switzerland":"Bern",


"Germany":“Munich", "Netherlands":"Amsterdam"}
 Capital[“Germany”]=“Berlin”

 print (Capital)

www.careerin.co.in
 Output:
 {"Austria":"Vienna", "Switzerland":"Bern",
"Germany":"Berlin", "Netherlands":"Amsterdam"}

www.careerin.co.in
LOOP THROUGH A DICTIONARY

 The dictionary can be looped through by using the for


loop. While looping a dictionary there are two separate
ways to access the keys and values
 Example: To access the keys.

 capital ={"Austria":"Vienna", "Switzerland":"Bern",


"Germany":“Munich", "Netherlands":"Amsterdam"}
 For x in capital:
 Print(x)

www.careerin.co.in
 Output
 Austria

 Switzerland

 Germany

 Netherlands

www.careerin.co.in
 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

www.careerin.co.in
 You can also use the values() function to return values of
a dictionary

 Example:
 for x in capital.values():
  print(x)

www.careerin.co.in
 Loop through both keys and values, by using the items()
function:
 Example:

 for x, y in thisdict.items():
  print(x, y)

www.careerin.co.in
CHECK IF KEY EXISTS

 To determine if a specified key is present in a dictionary


use the in keyword
 Example: Check if Germany is present

 capital ={"Austria":"Vienna", "Switzerland":"Bern",


"Germany":“Berlin", "Netherlands":"Amsterdam"}
 if Germany in capital:

 print(“Germany is present”)
 Else:

 print(“germany is not present”)

www.careerin.co.in
 Output:
 Germany is present

www.careerin.co.in
ADDING NEW ITEMS TO A
DICTIONARY

 Adding an item to the dictionary is done by using a new


index key and assigning a value to it
 Example:

 capital ={"Austria":"Vienna", "Switzerland":"Bern",


"Germany":“Berlin", "Netherlands":"Amsterdam"}
 capital[“India”] = “Newdelhi”

 Print(capital)

www.careerin.co.in
 Output:
 {"Austria":"Vienna", "Switzerland":"Bern",
"Germany":“Berlin", "Netherlands":"Amsterdam“
“India” : “Newdelhi”}

www.careerin.co.in
REMOVING ITEMS

 The items in a dictionary can be removed by the


keyword pop( ) and del, the pop( ) removes the item
with the specified key name in a dictionary and the del
removes the entire contents in dictionary.
 Example: pop( )

 thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}

www.careerin.co.in
 thisdict.pop("model")
print(thisdict)
 Output: {'brand': 'Ford', 'year': 1964}

 Example: del keyword

 thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}

www.careerin.co.in

del thisdict
print(thisdict)

Output: NameError: name 'thisdict' is not defined

www.careerin.co.in
NESTED DICTIONARIES

 A dictionary that contains several dictionary is known as


nested dictionary.
 trainings = { "course1":{"title":"Python Training Course
for Beginners", "location":“Nagercoil",
"trainer":“Ramesh"}, "course2":{"title":"Intermediate
Python Training", "location":"Berlin", "trainer":“Arun"},
"course3":{"title":"Python Text Processing Course",
"location":"München", "trainer":“Ravi"} }
 Print( trainings)

www.careerin.co.in
 Output:

 { "course1":{"title":"Python Training Course for


Beginners", "location":“Nagercoil",
"trainer":“Ramesh"},"course2":{"title":"Intermediate
Python Training", "location":"Berlin", "trainer":“Arun"},
"course3":{"title":"Python Text Processing Course",
"location":"München", "trainer":“Ravi"} }

www.careerin.co.in
UPDATE: MERGING DICTIONARIES

 The update method update() merges the keys and values


of one dictionary into another, overwriting values of the
same key
 Example: We consider two separate dictionaries
knowledge and knowledge 2 and merge it by update()
 knowledge = {"Frank": {"Perl"}, "Monica":{"C","C+
+"}}
 knowledge2 = {"Guido":{"Python"}, "Frank":{"Perl",
"Python"}}

www.careerin.co.in
knowledge.update(knowledge2)
 Print(knowledge)

 Output:
 {'Frank': {'Python', 'Perl'}, 'Guido': {'Python'}, 'Monica':
{'C', 'C++'}}

www.careerin.co.in
LISTS FROM DICTIONARIES

 It's possible to create lists from dictionaries by using the


methods items(), keys() and values().
 As the name implies the method keys() creates a list,
which consists solely of the keys of the dictionary.
values() produces a list consisting of the values. items()
 Example:

 pets = {“Dog":“pug", “fish":“ goldfish", “bird":“parrot"}

items_view = pets.items()

www.careerin.co.in
 items = list(items_view) >>>
 Print( items)

 Output: [(dog,pug),(fish, goldfish),(bird,parrot)]

 Example: To view keys alone in a list


 keys_view = pets.keys()

 print(keys)

 Output: [‘dog’, ‘fish’, ‘bird’]

www.careerin.co.in
THE DICT() CONSTRUCTOR

 It is also possible to use the dict() constructor to make a


new dictionary
 Example:

 Thisdict = dict(brand="Ford", model="Mustang",


year=1964)
 print(thisdict)

 Output: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

www.careerin.co.in
PYTHON– OBJECT
ORIENTED
PROGRAMMING

www.careerin.co.in
PYTHON - OOPS

 Python Class

 Python is an object oriented programming language.


 Almost everything in Python is an object, with its
properties and methods.
 A Class is like an object constructor, or a "blueprint" for
creating objects.

www.careerin.co.in
CREATE A CLASS

 To create a class, use the keyword class


 Example

 Create a class named MyClass, with a property named x:

 class MyClass:
 x=5
 Create Object

 Now we can use the class named MyClass to create


objects

www.careerin.co.in
 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

www.careerin.co.in
THE __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

The __init__() function is called automatically every time


the class is being used to create a new object

www.careerin.co.in
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:

www.careerin.co.in
 EXAMPLE:
 class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

www.careerin.co.in
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):
    self.name = name
    self.age = age

p1 = Person("John", 36)

print(p1.name)
print(p1.age)
www.careerin.co.in
 OUTPUT:
 John
36

www.careerin.co.in
OBJECT METHODS
 The method in object refers to the functions in the object
 Example:

 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()
www.careerin.co.in
 OUTPUT:
 Hello my name is John

www.careerin.co.in
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

 class Person:
  pass

www.careerin.co.in
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

www.careerin.co.in
CREATE A PARENT CLASS

 Any class can be a parent class, so the syntax is the same


as creating any other clas
 EXAMPLE:

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

  def printname(self):
    print(self.firstname, self.lastname)
 x = Person("John", "Doe")
x.printname()
www.careerin.co.in
 OUTPUT:
 John Doe

www.careerin.co.in
CREATE A CHILD CLASS

 create a class that inherits the functionality from another


class, send the parent class as a parameter when creating
the child class

 The syntax is class child_class(Parent_class)

www.careerin.co.in
 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):
 pass

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

 x.printname()

www.careerin.co.in
 Output : Mike olsen

www.careerin.co.in
TYPES OF INHERITANCE

 Single Inheritance

 Multiple Inheritance

 Multilevel Inheritance

 Hybrid Inheritance

 Hierarchical Inheritance

www.careerin.co.in
SINGLE INHERITANCE

 In Single inheritance there is one base class and one


derived class

 The example we had learned previously is the single


inheritance

www.careerin.co.in
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

www.careerin.co.in
EXAMPLE

www.careerin.co.in
OUTPUT
 45

 25

www.careerin.co.in
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.

www.careerin.co.in
EXAMPLE

www.careerin.co.in
OUTPUT
 45

www.careerin.co.in
HYBRID INHERITANCE

www.careerin.co.in
EXAMPLE

www.careerin.co.in
OUTPUT
 M( ) from class d
 M( ) from class b

M( ) from class a
M( ) from class a

www.careerin.co.in
FILE HANDLING IN
PYTHON

www.careerin.co.in
FILE HANDLING IN PYTHON
 File handling is an important part of any web
application.
 The file handling performs three important functions

 i) Read files

 ii) Write/create files

 iii) Delete files.

www.careerin.co.in
 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
www.careerin.co.in
 TO open a file use the below syntax.
 Create a text file using notepad.

 f = open( “filename.txt”)

www.careerin.co.in
PYTHON READ FILES
 f = open("demofile.txt", "r")
print(f.read())

 Output: the above code opens the contents in the file. Let
us assume that it has the below text
 Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!

www.careerin.co.in
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

 Return the 5 first characters of the file:

 f = open("demofile.txt", "r")
print(f.read(5))

 Output:Hello

www.careerin.co.in
READLINE()
 The readline() method returns one line from the text file.
 Example

 Read one line of the file:

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

 Output: Hello! Welcome to demofile.txt

www.careerin.co.in
TO READ TWO LINES
 By calling readline() two times, you can read the two
first lines
 Example

 Read two lines of the file:

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

 Hello! Welcome to demofile.txt


This file is for testing purposes.
www.careerin.co.in
CLOSE FILES

 It is a good practice to always close the file when you are


done with it.
 Example

 Close the file when you are finish with it:

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

Output: Hello! Welcome to demofile.txt

www.careerin.co.in
PYTHON FILE WRITE

 To write to an existing file, you must add a parameter to


the open() function:

 "a" - Append - will append to the end of the file

 "w" - Write - will overwrite any existing content

www.careerin.co.in
 Example
 f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
f = open("demofile2.txt", "r")
print(f.read())
 Output:

 Hello! Welcome to demofile2.txt


This file is for testing purposes.
Good Luck!Now the file has more content!

www.careerin.co.in
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("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()

f = open("demofile3.txt", "r")
print(f.read())

www.careerin.co.in
 Output:
 Woops! I have deleted the content!

www.careerin.co.in
APPEND TEXT TO A FILE

 “a" - Append - will append to the end of the file


 Example

 f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
f = open("demofile2.txt", "r")
print(f.read())

www.careerin.co.in
OUTPUT

 Hello! Welcome to demofile2.txt


This file is for testing purposes.
Good Luck!Now the file has more content!

www.careerin.co.in
CREATE A NEW FILE

 Example
 Create a file called "myfile.txt":

 f = open("myfile.txt", "x")

 Result: a new empty file is created!

 Example
 Create a new file if it does not exist:

 f = open("myfile.txt", "w")

www.careerin.co.in
PYTHON DELETE FILE

 To delete a file, you must import the OS module, and run


its os.remove() function

 Example
 Remove the file "demofile.txt":

 import os
os.remove("demofile.txt")

www.careerin.co.in
CHECK IF FILE EXIST:

 import os
if os.path.exists("demofile.txt"):
  os.remove("demofile.txt")
else:
  print("The file does not exist")

www.careerin.co.in
DELETE FOLDER

 To delete an em foptylder, use the os.rmdir() method:


 Example

 Remove the folder "myfolder":

 import os
os.rmdir("myfolder")

www.careerin.co.in
PYTHON DATE AND
TIME

www.careerin.co.in
PYTHON DATETIME

 Python has a module named datetime to work with dates


and times
 Example : Get Current Date and Time

 import datetime

 datetime_object = datetime.datetime.now()
print(datetime_object)

 OUTPUT: 2020-04-07 10:26:03.478039

www.careerin.co.in
GET CURRENT DATE

 EXAMPLE:

 import datetime
 date_object = datetime.date.today() print(date_object)

 OUTPUT
 2020-04-07

www.careerin.co.in
DATE TIME CLASS
 Commonly used classes in the datetime module are:

 date Class
 time Class

 datetime Class

 timedelta Class

www.careerin.co.in
DATETIME.DATE CLASS
 The date class accepts a date from the user
 Example

 import datetime

 d = datetime.date(2020, 4, 07)

 print(d)

 OUTPUT
 2020-04-07

www.careerin.co.in
PRINT TODAY'S YEAR, MONTH AND
DAY

 EXAMPLE
 from datetime import date

 today = date.today( )

 print("Current year:", today.year)

 print("Current month:", today.month) print("Current


day:", today.day)
 OUTPUT:

 Current year: 2020

 Current month: 04

 Current DAY: 07
www.careerin.co.in
DATETIME.TIME CLASS

 A time object instantiated from the time class represents the


local time
 EXAMPLE:

 from datetime import time

 a = time( )

 print("a =", a)

 b = time(11, 34, 56)

 print("b =", b)

 c = time(hour = 11, minute = 34, second = 56) print("c =", c)

 d = time(11, 34, 56, 234566) print("d =", d)

www.careerin.co.in
 OUTPUT
 a = 00:00:00

 b = 11:34:56

 c = 11:34:56

 d = 11:34:56.234566

www.careerin.co.in
PRINT HOUR, MINUTE, SECOND AND MICROSECOND

 EXAMPLE:
 from datetime import time

 a = time(11, 34, 56)

 print("hour =", a.hour)

 print("minute =", a.minute)

 print("second =", a.second)

 print("microsecond =", a.microsecond)

www.careerin.co.in
OUTPUT
 hour = 11
 minute = 34

 second = 56

 microsecond = 0

www.careerin.co.in
DATETIME.DATETIME CLASS

 EXAMPLE:

 from datetime import datetime


 a = datetime(2020, 11, 28)

 print(a)

 b = datetime(2020, 11, 28, 23, 55, 59, 342380) print(b)

www.careerin.co.in
 OUTPUT

 2020-11-28 00:00:00

 2020-11-28 23:55:59.342380

www.careerin.co.in
DATETIME.TIMEDELTA

 A timedelta object represents the difference between two


dates or times.
 EXAMPLE:

 from datetime import datetime, date

 t1 = date(year = 2018, month = 7, day = 12)

 t2 = date(year = 2017, month = 12, day = 23)

 t3 = t1 - t2 print("t3 =", t3)

 t4 = datetime(year = 2018, month = 7, day = 12, hour =


7, minute = 9, second = 33)

www.careerin.co.in
 t5 = datetime(year = 2019, month = 6, day = 10, hour =
5, minute = 55, second = 13)
 t6 = t4 - t5

 print("t6 =", t6)

 OUTPUT:
 t3 = 201 days, 0:00:00

 t6 = -333 days, 1:14:20

www.careerin.co.in
DIFFERENCE BETWEEN TWO TIMEDELTA
OBJECTS

 EXAMPLE

 from datetime import timedelta


 t1 = timedelta(weeks = 2, days = 5, hours = 1, seconds =
33)
 t2 = timedelta(days = 4, hours = 11, minutes = 4, seconds
= 54)
 t3 = t1 - t2

 print("t3 =", t3)

www.careerin.co.in
 OUTPUT

 t3 = 14 days, 13:55:39

www.careerin.co.in
PYTHON STRFTIME()

 The strftime() method is defined under classes date,


datetime and time. The method creates a formatted string
from a given date, datetime or time object.
 %Y - year [0001,..., 2018, 2019,..., 9999]

 %m - month [01, 02, ..., 11, 12]

 %d - day [01, 02, ..., 30, 31]

 %H - hour [00, 01, ..., 22, 23

 %M - minute [00, 01, ..., 58, 59]

 %S - second [00, 01, ..., 58, 59]

www.careerin.co.in
 EXAMPLE
 From datetime import datetime

 now = datetime.now()

 t = now.strftime("%H:%M:%S")

 print("time:", t)

 s1 = now.strftime("%m/%d/%Y, %H:%M:%S")

 print("s1:", s1)

 s2 = now.strftime("%d/%m/%Y, %H:%M:%S")

 print("s2:", s2)

www.careerin.co.in
 OUTPUT:

 time: 04:34:52
 s1: 04/07/2018, 04:34:52

 s2: 07/04/2018, 04:34:52

www.careerin.co.in
PYTHON STRPTIME() - STRING TO DATETIME

 The strptime() method creates a datetime object from a


given string (representing date and time).

 The strptime() method takes two arguments:


 i)a string representing date and time

 ii)format code equivalent to the first argument

 By the way, %d, %B and %Y format codes are used for


day, month(full name) and year respectively.

www.careerin.co.in
 EXAMPLE:
 from datetime import datetime

 date_string = "21 June, 2018"

 print("date_string =", date_string)

 date_object = datetime.strptime(date_string, "%d %B,


%Y")
 print("date_object =", date_object)

www.careerin.co.in
 OUTPUT:
 date_string = 21 June, 2018

 date_object = 2018-06-21 00:00:00

www.careerin.co.in
PYTHON
EXCEPTION
HANDLING
www.careerin.co.in
PYTHON EXCEPTION HANDLING
 When an error occurs, or exception as we call it, Python
will normally stop and generate an error message

 These exceptions can be handled using the


try, except, finally

www.careerin.co.in
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")

 Output: An exception occured


www.careerin.co.in
 We can define as many exception blocks as you want,
e.g. if you want to execute a special block of code for a
special kind of error

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"
www.careerin.co.in
 OUTPUT:

 Variable x is not defined

www.careerin.co.in
 We can use the else keyword to define a block of code to
be executed if no errors were raised
 Example

 In this example, the try block does not generate any


error:
 try:
  print("Hello")
except:
  print("Something went wrong")
else:
  print("Nothing went wrong")
www.careerin.co.in
 Output:
 Hello


Nothing went wrong

www.careerin.co.in
FINALLY BLOCK

 The finally block, if specified, will be executed


regardless if the try block raises an error or not.
 Example

 try:
  print(x)
except:
  print("Something went wrong")
finally:
  print("The 'try except' is finished")

www.careerin.co.in
 Output:

 Something went wrong


The 'try except' is finished

www.careerin.co.in
RAISE AN EXCEPTION

 As a Python developer you can choose to throw an


exception if a condition occurs.
 To throw (or raise) an exception, use the raise keyword

 EXAMPLE:

 Example

 x = -1
if x < 0:
  raise Exception("Sorry, no numbers below zero")

www.careerin.co.in
 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

www.careerin.co.in
 Example
 Raise a TypeError if x is not an integer:

 x = "hello"

if not type(x) is int:


  raise TypeError("Only integers are allowed")

www.careerin.co.in
 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

www.careerin.co.in
PYTHON- MY
SQL
www.careerin.co.in
PYTHON MYSQL DATABASE CONNECTION

 The  mysql.connector.connect()  method of MySQL


Connector Python with required parameters to connect
MySQL.

 Use the connection object returned by


a  connect()  method to create a cursor object to perform
Database Operations.

www.careerin.co.in
 The cursor.execute() to execute SQL queries from
Python

 Close the Cursor object using a cursor.close() and


MySQL database connection using connection.close()
after your work completes.

www.careerin.co.in
PYTHON EXAMPLE TO CONNECT MYSQL DATABASE

 Create Database in MySQL


 The syntax to create data base is to use

 Create database database_name;

 You need to know the following detail of the MySQL server to


perform the connection from Python.
 Username –  i.e., the username that you use to work with MySQL
Server. The default username for the MySQL database is a root
 Password – Password is given by the user at the time of installing
the MySQL database. If you are using root then you won’t need the
password.

www.careerin.co.in
 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. 127.0.0.0
 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

www.careerin.co.in
EXAMPLE TO CREATE A DATABASE
CONNECTION
Create database Electronics;
import mysql.connector from mysql.connector import
Error
try: connection = mysql.connector.connect(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 =
connection.cursor( )
cursor.execute("select database( );")
record = cursor.fetchone() www.careerin.co.in
 print("You're connected to database: ", record)

 except Error as e:
 print("Error while connecting to MySQL", e)
 finally:

 if (connection.is_connected( )):
 cursor.close( )
 connection.close( )
 print("MySQL connection is closed")

www.careerin.co.in
OUTPUT
 Connected to MySQL Server version 5.7.19

 You're connected to database: ('electronics',)

 MySQL connection is closed

www.careerin.co.in
UNDERSTAND THE PYTHON MYSQL
DATABASE CONNECTION PROGRAM

 import mysql.connector
 This line imports the MySQL Connector Python module
in your program so you can use this module’s API to
connect MySQL.
 from mysql.connector import Error

 mysql connector Error object is used to show us an


error when we failed to connect Databases or if any other
database error occurred while working with the database.
Example ACCESS DENIED ERROR when username or
password is wrong.

www.careerin.co.in
 mysql.connector.connect()
 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.

www.careerin.co.in
 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()

 is_connected() is the method of the MySQLConnection


class through which we can verify is our python
application connected to MySQL.
 

www.careerin.co.in
 connection.cursor()
 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.

 cursor.close()
 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.
   www.careerin.co.in
 connection.close()
 At last, we are closing the MySQL database connection
using a close() method of MySQLConnection class.

www.careerin.co.in
PYTHON MYSQL CREATE TABLE

 import mysql.connector
 from mysql.connector import Error

 try: connection =
mysql.connector.connect(host='localhost',
 database='Electronics', user='pynative',

 password='pynative@#29')

www.careerin.co.in
 mySql_Create_Table_Query = """CREATE TABLE
Laptop ( Id int(11) NOT NULL, Name
 varchar(250) NOT NULL, Price float NOT

 NULL, Purchase_date Date NOT NULL,

 PRIMARY KEY (Id)) ""“

 cursor = connection.cursor()

 result = cursor.execute(mySql_Create_Table_Query)

 print("Laptop Table created successfully ")

www.careerin.co.in
 except mysql.connector.Error as error: print("Failed to
create table in MySQL: {}".format(error))
 finally:

 if (connection.is_connected( )):
 cursor.close( )
 connection.close( )
 print("MySQL connection is closed")

www.careerin.co.in
OUTPUT
 Laptop Table created successfully

 MySQL connection is closed

www.careerin.co.in
PYTHON INSERT INTO MYSQL TABLE

 import mysql.connector from mysql.connector

 import Error from mysql.connector


 import errorcode

 try:

 connection = mysql.connector.connect(host='localhost',
database='electronics', user='root', password=‘ ‘)

www.careerin.co.in
 mySql_insert_query = """INSERT INTO Laptop (Id,
Name, Price, Purchase_date) VALUES (10, 'Lenovo
ThinkPad P71', 6459, '2019-08-14') """
 cursor = connection.cursor()

 cursor.execute(mySql_insert_query)

 connection.commit( )

 print(cursor.rowcount, "Record inserted successfully into


Laptop table") cursor.close()

www.careerin.co.in
 except mysql.connector.Error as error: print("Failed to
insert record into Laptop table {}".format(error))
 finally:

 if (connection.is_connected( )):

 connection.close( )

 print("MySQL connection is closed")

www.careerin.co.in
OUTPUT
 Record inserted successfully into Laptop table

 MySQL connection is closed

www.careerin.co.in
PYTHON SELECT FROM MYSQL
TABLE

 SQL SELECT query to fetch all rows from a Laptop


table.

 a cursor.fetchall( )  method we can fetch all the records


present under a “Laptop” table.

 cursor.fetchone() to fetch single row.

www.careerin.co.in
EXAMPLE FOR MY SQL SELECT
 import mysql.connector
 from mysql.connector import Error

 try:
 connection = mysql.connector.connect(host='localhost',
database='Electronics', user=‘root', password=‘ ‘)

www.careerin.co.in
 sql_select_Query = "select * from Laptop"
 cursor = connection.cursor( )
cursor.execute(sql_select_Query)
 records = cursor.fetchall( )

 print("Total number of rows in Laptop is: ",


cursor.rowcount)
 print("\nPrinting each laptop record")

www.careerin.co.in
 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)

www.careerin.co.in
 finally:
 if (connection.is_connected()):

 connection.close( )

 cursor.close( )

 print("MySQL connection is closed")

www.careerin.co.in
OUTPUT
 Total number of rows in Laptop is: 7
 Printing each laptop record

 Id = 1

 Name = Lenovo ThinkPad P71


 Price = 6459.0

 Purchase date = 2019-08-14

www.careerin.co.in
PYTHON UPDATE MYSQL TABLE

 SQL UPDATE query to update a “Price” column of a


Laptop table. The update query contains the column
value to be updated

 use a cursor.rowcount method to get the number of


rows affected. here it will return 1 because we are
updating one row

www.careerin.co.in
 import mysql.connector
 from mysql.connector import Error

 try:
 connection = mysql.connector.connect(host='localhost',
database='Electronics', user=‘root', password=‘ ‘)

www.careerin.co.in
 cursor = connection.cursor( )
 print("Before updating a record ") sql_select_query =
"""select * from Laptop where id = 1"""

 cursor.execute(sql_select_query)

 record = cursor.fetchone() print(record)

www.careerin.co.in
 sql_update_query = """Update Laptop set Price = 7000
where id = 1"""
 cursor.execute(sql_update_query)

 connection.commit( )

 print("Record Updated successfully ") print("After


updating record ")

 cursor.execute(sql_select_query)

 record = cursor.fetchone() print(record)


www.careerin.co.in
 except mysql.connector.Error as error:
 print("Failed to update table record: {}".format(error))

 finally:
 if (connection.is_connected()):
 connection.close( )
 print("MySQL connection is closed")

www.careerin.co.in
OUTPUT
 Before updating a record
 (1, 'Lenovo ThinkPad P71', 6459.0, datetime.date(2019,
8, 14))
 Record Updated successfully

 After updating record


 (1, 'Lenovo ThinkPad P71', 7000.0, datetime.date(2019,
8, 14))
 MySQL connection is closed

www.careerin.co.in
PYTHON DELETE DATA FROM MYSQL
TABLE

 import mysql.connector
 from mysql.connector import Error

 try:
 connection = mysql.connector.connect(host='localhost',
database='Electronics', user=‘root', password=‘ ‘)

www.careerin.co.in
 cursor = connection.cursor( )
 delete_table_query = """DROP TABLE Laptop"""
cursor.execute(delete_table_query)
delete_database_query = """DROP DATABASE
Electronics""" cursor.execute(delete_database_query)
connection.commit( )
 print("Table and Database Deleted successfully ")

www.careerin.co.in
 except mysql.connector.Error as error:
 print("Failed to Delete table and database:
{}".format(error))
 finally:

 if (connection.is_connected( )):

 cursor.close( ) connection.close( )
 print("MySQL connection is closed")

www.careerin.co.in
OUTPUT
 Table and Database Deleted successfully

 MySQL connection is closed

www.careerin.co.in

You might also like