Python
Introduction
History:
Author : Guido van Rossum
Year:1991
use:
1.Web Development
2.Software Development
3.Mathematics
4.System Scripting
What?
• It is used on a server to create web applications.
• It create workflows
• It connects with database system, to read and modify files.
• It handles Big data and performs Complex mathematical operations.
• It is used for rapid-prototyping.
Escape Characters
Code Result
' Single Quote
 Backslash
n New Line
r Carriage Return
t Tab
b Backspace
f Form Feed
ooo Octal value
xhh Hex value
Special Operators -Escape
• "t" is a tab,
• “n “ New Line
Arithmetic Operators
Operator Name Example
+ Addition x + y
- Subtraction x - y
* Multiplication x * y
/ Division x / y
% Modulus x % y
** Exponentiation x ** y
// Floor division x // y
Ex
x = 5
y = 3
print(x + y)
print(x - y)
print(x * y)
print(x / y)
print(x % y)
print(x ** y)
print(x //y)
Assignment Operators
Operator Example Same As
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x = x & 3
|= x |= 3 x = x | 3
^= x ^= 3 x = x ^ 3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
Comparison Operators
Operator Name Example
== Equal x == y
!= Not equal x != y
> Greater than x > y
< Less than x < y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
Booleans
Boolean Values:
• When you compare two values, the expression is
evaluated and Python returns the Boolean answer:
Example:
print(10 > 9)
print(10 == 10)
print(10 < 9)
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
Evaluate Values and Variables
• The bool() function allows you to evaluate any
value, and give you True or False in return,
• Ex:
print(bool("Hello"))
print(bool(15))
x = "Hello"
y = 15
print(bool(x))
print(bool(y))
True:
bool("abc")
bool(123)
bool(["apple", "cherry", "banana"])
False:
bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
bool({})
String Coding's
Concatenation
Upper
Lower
Count
Find
Center
Title
Split
IsalNum
Len
Replace
Strip
Rfind
Isdigit
Expandtabs
endswith
Python Data Types
Types
• List
• Tuple
• Set
• Dictionary
Declaration
• List Variable Name =[“ “,----]
• Tuple Variable Name = (“ “,-----------)
• Set Variable Name = {“ “, ------------- }
• Dict Variable Name = {Key:Value,------------}
List
• Lists are used to store multiple items in a single variable.
Ex:
List Items:
1. Ordered
2. Changeable
3. Allow duplicates
List Coding’s
Ratio [::]
Append
Extend
Remove
Pop
Len
Sort
Reverse
Clear
Copy
Join
Sets
• Sets are used to store multiple items in a single variable.
• Set Items are:
Unordered
Unindexed
Unchangeable
Duplicates not allowed
• Sets are written with curly [ { } ]brackets.
Set Coding’s
Type
Add
Update
Remove
Union
Intersection_update
Symmetric _update [It will keep only the
elements that are NOT present in both sets.]
Tuples
• Tuples are used to store multiple items in a single variable.
• Tuple items :
1.Ordered
2.Unchangeable
3.Allow Duplicate values
Tuples Coding’s
Type
Len
Min
Max
Join
Change data Type
Multiple [Asterisk* - you can the * Operator the
values will be assigned Multi Times ]
Dictionaries
• It is used to store data values in key:value pairs.
• Dictionary Items are:
Ordered
Changeable
Duplicates not allowed
A={"brand": “Window 10,"model": “DellArm", "year": 2020
}
print(A)
Dictionary Coding’s
Insert
Update
Pop – [Removes the item with the specified key name]
PopItems – [It removes the last inserted item]
Del
Copy
Clear
Get
Functions
• A function is a block of code which only runs
when it is called.
• Parameters which contains the arguments.
• Return the result as data.
Ex:
def my_function():
print("Hello from a function")
Function Call
def my_function():
print("Hello from a function")
my_function()
Arguments:
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Return
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
Pass
• function definitions cannot be empty.
• But due to some reason have a function
definition without content, use pass
statement to avoid an error.
Ex:
def myfunction():
pass
Class and object
• It is an Object Oriented Programming.
• Class:
Collection of objects.
Blueprint for creating objects.
• Object:
Basic Run time entity.
Class creation:
class MyClass:
x = 5
print(MyClass)
Object Creation:
c1=Myclass
Ex:
class MyClass:
x = 5
c1 = MyClass()
print(c1.x)
__init__()
• All classes have a function called __init__()
• It is executed when the class is being initiated.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
Object methods
• Objects can also contain methods.
• Methods in objects are functions that belong to the object.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
Inheritance
• 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.
Parent Class:
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()
Child Class:
class Student(Person):
pass
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()
__init__() Function
• add the __init__() function to the child class (instead of
the pass keyword).
Ex:
class Student(Person):
def __init__(self, fname, lname):
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
super() Function
• super() function that will make the child class inherit all the
methods and properties from its parent:
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
Iterators
• An iterator is an object that contains a countable number of values.
• Methods to iterate:
__iter__()
__next__()
Iterator vs Iterable
Lists, tuples, dictionaries, and sets are all iterable objects.
Ex:
mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)
print(next(myit))
print(next(myit))
print(next(myit))
Looping Through an Iterator
• for loop to iterate through an iterable object:
mytuple = ("apple", "banana", "cherry")
for x in mytuple:
print(x)
mystr = "banana"
for x in mystr:
print(x)
Create an Iterator
• __iter__() and __next__() methods used to create an
object/class as an iterator.
• __init__() used to do some initialization when an object being
created.
• __iter__() - you can do operations (initializing etc.), but must
always return the iterator object itself.
• __next__() - method also allows you to do operations, and
must return the next item in the sequence.
StopIteration
• To prevent the iteration to go on forever, we can use
the StopIteration statement.
• __next__() – Add an termination condition to raise an error, if
the iteration is done a specified number of times.
class MyNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
if self.a <= 20:
x = self.a
self.a += 1
return x
else:
raise StopIteration
myclass = MyNumbers()
myiter = iter(myclass)
for x in myiter:
print(x)
Scope of Variables
• A variable is only available from inside the
region it is created. This is called scope.
• Two types:
Local
Global
Local:
A variable created inside a function, and can be used
inside the function.
Ex:
def myfunc():
x = 300
print(x)
myfunc()
Function Inside Function [Inner Func]
def myfunc():
x = 300
def myinnerfunc():
print(x)
myinnerfunc()
myfunc()
Global Scope:
A variable created in the main body of the Python code is
a global variable.
Ex:
x = 300
def myfunc():
print(x)
myfunc()
print(x)
Naming Variables:
When we use the same variable name inside and outside
of a function, Python will treat them as two separate variables.
x = 300
def myfunc():
x = 200
print(x)
myfunc()
print(x)
Global Keyword:
It represents a Global Scope.
The keyword used to change the value of a global
variable.
def myfunc():
global x
x = 300
myfunc()
print(x)
File Handling
• File handling is an important part of any web
application.
• Functions:
Creating
Reading
Updating
Deleting
File Open
• Function : open()
• Parameters: filename, and mode.
• Modes:
“r” – Read
“a” – Append
“w” – Write
“x” – Create
• Syntax:
f = open(“SS.txt")
f = open(“SS.txt", "rt")
Read Files:
• Function: read()
• f = open("demofile.txt", "r")
print(f.read())
• f = open("D:myfileswelcome.txt", "r")
print(f.read())
Reading a part of file:
• f = open("demofile.txt", "r")
print(f.read(5))
Read Lines
• f = open("demofile.txt", "r")
print(f.readline())
readline()
• f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())
Loop:
• f = open("demofile.txt", "r")
for x in f:
print(x)
Close Files:
• f = open("demofile.txt", "r")
print(f.readline())
f.close()
Write to an Existing File
• "a" - Append
• "w" - Write
• f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
f = open("demofile2.txt", "r")
print(f.read())
• f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()
f = open("demofile3.txt", "r")
print(f.read())
Create a New File
• "x" - Create - will create a file, returns an error if
the file exist
• f = open("myfile.txt", "x")
• "a" - Append - will create a file if the specified file
does not exist
• "w" - Write - will create a file if the specified file
does not exist
• f = open("myfile.txt", "w")
Delete File
• To delete a file, you must import the OS module.
• Function: os.remove()
• import os
os.remove("demofile.txt")
Check if File exist:
import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")
Delete Folder
• To delete an entire folder, use
the os.rmdir() method:
• import os
os.rmdir("myfolder")

Python programming language advanced level model explanation

  • 1.
  • 2.
    Introduction History: Author : Guidovan Rossum Year:1991 use: 1.Web Development 2.Software Development 3.Mathematics 4.System Scripting What? • It is used on a server to create web applications. • It create workflows • It connects with database system, to read and modify files. • It handles Big data and performs Complex mathematical operations. • It is used for rapid-prototyping.
  • 3.
    Escape Characters Code Result 'Single Quote Backslash n New Line r Carriage Return t Tab b Backspace f Form Feed ooo Octal value xhh Hex value
  • 4.
    Special Operators -Escape •"t" is a tab, • “n “ New Line
  • 5.
    Arithmetic Operators Operator NameExample + Addition x + y - Subtraction x - y * Multiplication x * y / Division x / y % Modulus x % y ** Exponentiation x ** y // Floor division x // y
  • 6.
    Ex x = 5 y= 3 print(x + y) print(x - y) print(x * y) print(x / y) print(x % y) print(x ** y) print(x //y)
  • 7.
    Assignment Operators Operator ExampleSame As = x = 5 x = 5 += x += 3 x = x + 3 -= x -= 3 x = x - 3 *= x *= 3 x = x * 3 /= x /= 3 x = x / 3 %= x %= 3 x = x % 3 //= x //= 3 x = x // 3 **= x **= 3 x = x ** 3 &= x &= 3 x = x & 3 |= x |= 3 x = x | 3 ^= x ^= 3 x = x ^ 3 >>= x >>= 3 x = x >> 3 <<= x <<= 3 x = x << 3
  • 8.
    Comparison Operators Operator NameExample == Equal x == y != Not equal x != y > Greater than x > y < Less than x < y >= Greater than or equal to x >= y <= Less than or equal to x <= y
  • 9.
    Booleans Boolean Values: • Whenyou compare two values, the expression is evaluated and Python returns the Boolean answer: Example: print(10 > 9) print(10 == 10) print(10 < 9)
  • 10.
    a = 200 b= 33 if b > a: print("b is greater than a") else: print("b is not greater than a")
  • 11.
    Evaluate Values andVariables • The bool() function allows you to evaluate any value, and give you True or False in return, • Ex: print(bool("Hello")) print(bool(15)) x = "Hello" y = 15 print(bool(x)) print(bool(y))
  • 12.
  • 13.
  • 14.
    Python Data Types Types •List • Tuple • Set • Dictionary Declaration • List Variable Name =[“ “,----] • Tuple Variable Name = (“ “,-----------) • Set Variable Name = {“ “, ------------- } • Dict Variable Name = {Key:Value,------------}
  • 15.
    List • Lists areused to store multiple items in a single variable. Ex: List Items: 1. Ordered 2. Changeable 3. Allow duplicates
  • 16.
  • 17.
    Sets • Sets areused to store multiple items in a single variable. • Set Items are: Unordered Unindexed Unchangeable Duplicates not allowed • Sets are written with curly [ { } ]brackets.
  • 18.
    Set Coding’s Type Add Update Remove Union Intersection_update Symmetric _update[It will keep only the elements that are NOT present in both sets.]
  • 19.
    Tuples • Tuples areused to store multiple items in a single variable. • Tuple items : 1.Ordered 2.Unchangeable 3.Allow Duplicate values
  • 20.
    Tuples Coding’s Type Len Min Max Join Change dataType Multiple [Asterisk* - you can the * Operator the values will be assigned Multi Times ]
  • 21.
    Dictionaries • It isused to store data values in key:value pairs. • Dictionary Items are: Ordered Changeable Duplicates not allowed A={"brand": “Window 10,"model": “DellArm", "year": 2020 } print(A)
  • 22.
    Dictionary Coding’s Insert Update Pop –[Removes the item with the specified key name] PopItems – [It removes the last inserted item] Del Copy Clear Get
  • 23.
    Functions • A functionis a block of code which only runs when it is called. • Parameters which contains the arguments. • Return the result as data. Ex: def my_function(): print("Hello from a function")
  • 24.
    Function Call def my_function(): print("Hellofrom a function") my_function() Arguments: def my_function(fname): print(fname + " Refsnes") my_function("Emil") my_function("Tobias") my_function("Linus")
  • 25.
    Return def my_function(x): return 5* x print(my_function(3)) print(my_function(5)) print(my_function(9))
  • 26.
    Pass • function definitionscannot be empty. • But due to some reason have a function definition without content, use pass statement to avoid an error. Ex: def myfunction(): pass
  • 27.
    Class and object •It is an Object Oriented Programming. • Class: Collection of objects. Blueprint for creating objects. • Object: Basic Run time entity.
  • 28.
    Class creation: class MyClass: x= 5 print(MyClass) Object Creation: c1=Myclass Ex: class MyClass: x = 5 c1 = MyClass() print(c1.x)
  • 29.
    __init__() • All classeshave a function called __init__() • It is executed when the class is being initiated. class Person: def __init__(self, name, age): self.name = name self.age = age p1 = Person("John", 36) print(p1.name) print(p1.age)
  • 30.
    Object methods • Objectscan also contain methods. • Methods in objects are functions that belong to the object. class Person: def __init__(self, name, age): self.name = name self.age = age def myfunc(self): print("Hello my name is " + self.name) p1 = Person("John", 36) p1.myfunc()
  • 31.
    Inheritance • a classthat 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.
  • 32.
    Parent Class: 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() Child Class: class Student(Person): pass
  • 33.
    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()
  • 34.
    __init__() Function • addthe __init__() function to the child class (instead of the pass keyword). Ex: class Student(Person): def __init__(self, fname, lname): class Student(Person): def __init__(self, fname, lname): Person.__init__(self, fname, lname)
  • 35.
    super() Function • super()function that will make the child class inherit all the methods and properties from its parent: class Student(Person): def __init__(self, fname, lname): super().__init__(fname, lname)
  • 36.
    Iterators • An iteratoris an object that contains a countable number of values. • Methods to iterate: __iter__() __next__() Iterator vs Iterable Lists, tuples, dictionaries, and sets are all iterable objects. Ex: mytuple = ("apple", "banana", "cherry") myit = iter(mytuple) print(next(myit)) print(next(myit)) print(next(myit))
  • 37.
    Looping Through anIterator • for loop to iterate through an iterable object: mytuple = ("apple", "banana", "cherry") for x in mytuple: print(x) mystr = "banana" for x in mystr: print(x)
  • 38.
    Create an Iterator •__iter__() and __next__() methods used to create an object/class as an iterator. • __init__() used to do some initialization when an object being created. • __iter__() - you can do operations (initializing etc.), but must always return the iterator object itself. • __next__() - method also allows you to do operations, and must return the next item in the sequence.
  • 39.
    StopIteration • To preventthe iteration to go on forever, we can use the StopIteration statement. • __next__() – Add an termination condition to raise an error, if the iteration is done a specified number of times.
  • 40.
    class MyNumbers: def __iter__(self): self.a= 1 return self def __next__(self): if self.a <= 20: x = self.a self.a += 1 return x else: raise StopIteration myclass = MyNumbers() myiter = iter(myclass) for x in myiter: print(x)
  • 41.
    Scope of Variables •A variable is only available from inside the region it is created. This is called scope. • Two types: Local Global
  • 42.
    Local: A variable createdinside a function, and can be used inside the function. Ex: def myfunc(): x = 300 print(x) myfunc()
  • 43.
    Function Inside Function[Inner Func] def myfunc(): x = 300 def myinnerfunc(): print(x) myinnerfunc() myfunc()
  • 44.
    Global Scope: A variablecreated in the main body of the Python code is a global variable. Ex: x = 300 def myfunc(): print(x) myfunc() print(x)
  • 45.
    Naming Variables: When weuse the same variable name inside and outside of a function, Python will treat them as two separate variables. x = 300 def myfunc(): x = 200 print(x) myfunc() print(x)
  • 46.
    Global Keyword: It representsa Global Scope. The keyword used to change the value of a global variable. def myfunc(): global x x = 300 myfunc() print(x)
  • 47.
    File Handling • Filehandling is an important part of any web application. • Functions: Creating Reading Updating Deleting
  • 48.
    File Open • Function: open() • Parameters: filename, and mode. • Modes: “r” – Read “a” – Append “w” – Write “x” – Create • Syntax: f = open(“SS.txt") f = open(“SS.txt", "rt")
  • 49.
    Read Files: • Function:read() • f = open("demofile.txt", "r") print(f.read()) • f = open("D:myfileswelcome.txt", "r") print(f.read()) Reading a part of file: • f = open("demofile.txt", "r") print(f.read(5)) Read Lines • f = open("demofile.txt", "r") print(f.readline())
  • 50.
    readline() • f =open("demofile.txt", "r") print(f.readline()) print(f.readline()) Loop: • f = open("demofile.txt", "r") for x in f: print(x)
  • 51.
    Close Files: • f= open("demofile.txt", "r") print(f.readline()) f.close()
  • 52.
    Write to anExisting File • "a" - Append • "w" - Write • f = open("demofile2.txt", "a") f.write("Now the file has more content!") f.close() f = open("demofile2.txt", "r") print(f.read()) • f = open("demofile3.txt", "w") f.write("Woops! I have deleted the content!") f.close() f = open("demofile3.txt", "r") print(f.read())
  • 53.
    Create a NewFile • "x" - Create - will create a file, returns an error if the file exist • f = open("myfile.txt", "x") • "a" - Append - will create a file if the specified file does not exist • "w" - Write - will create a file if the specified file does not exist • f = open("myfile.txt", "w")
  • 54.
    Delete File • Todelete a file, you must import the OS module. • Function: os.remove() • import os os.remove("demofile.txt") Check if File exist: import os if os.path.exists("demofile.txt"): os.remove("demofile.txt") else: print("The file does not exist")
  • 55.
    Delete Folder • Todelete an entire folder, use the os.rmdir() method: • import os os.rmdir("myfolder")