A Powerpoint Presentation ON Python
A Powerpoint Presentation ON Python
A Powerpoint Presentation ON Python
POWERPOINT PRESENTATION
ON
PYTHON
By
Durga Prasad Kopanathi
CONTENTS:
Introduction Flow Control
Features of Python Functions
Identifiers Modules
Keyword S Packages
Lines and Indentations Decorators
Comment Generators
Data Types File Handling
Variables Exception Handling
Type Casting Python Logging
Operators Object Oriented Programming
Input and Output Statements
INTRODUCTION:
Python is an Interpreted, Object-oriented, High-level programming language.
It was developed by Guido Van Rossam in 1989 and made available to public in 1991
It was implemented based on procedure oriented, Object oriented, Modular programming languages and
Scripting Language.
Beginners Language
USE OF PYTHON:
► The most common important application areas of Python are
► Web Applications
► Web development
► Game Development
► Desktop Applications,
► Data Science
► Machine learning
► Artificial Intelligence
► Data visualization
► and in many more.
FEATURES OF PYTHON
Simple and easy to learn
Freeware and Open Source
High Level Programming language
Platform Independent
Portability
Dynamically Typed
Both Procedure Oriented and Object Oriented
Interpreted
Embedded
IDENTIFIERS
An identifier is a name given to entities like class, functions, variables, etc. It helps to differentiate one entity from another.
Rules of Identifiers:
An identifier name must start with a letter or the underscore character,.
Class must start with uppercase remaining lower case
An identifier name can’t start with number
An identifier name only contain alpha-numeric and underscores.
Identifier names are case sensitive.
Single underscore private
Two underscore strongly private
Examples:
cash,cash123,cash_123
KEYWORDS:
A keyword is a reserved word whose meaning is already defined.
Keywords cannot be used as a variable.
As of python 3.8 there are 35 keywords.
You can comment multiple lines in python using (triple quotes) doc strings (“”” “””) or (‘’’ ‘’’)
Ex:
print(“Hello, this is an example of doc string”)
written in
more than just one line “””
print(“end”)
DATA TYPES & VARIABLES:
A data type is a classification that tells a computer which kind of value can be assigned to a variable.
It also tells which operations can be performed on that variable.
Once the data is stored, we can retrieve it using the variable name.
Built-in Data Types of Python:
Following are the standard or built-in data type of Python:
• Numeric int, float, complex
• Sequence Type String, List, Tuple
• Boolean
• Set
• Dictionary
VARIABLE:
Variables are containers for storing data values, A variable is only a name given to a memory
location, all the operations done on the variable effects that memory location
A variable is created the moment we first assign a value to it.
Rules for creating variables in Python:
• 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 (name, Name and NAME are three different variables).
• The reserved words(keywords) cannot be used naming the variable.
Ex:
Price = 100.23, Name = “Apples”, Q = 3
Python is a dynamically typed language and therefore data type is set when you assign a value
to a variable.. Since there is no need to mention data type in python when a variable is declare.
NUMERIC DATA TYPES:
Numeric data types handle numerical values used in mathematical computations and in other purposes which use numeric values.
There are three distinct numeric data types in Python:
1. Integer
Int, or integer, is a whole number, positive or negative, without decimals of unlimited length.
X = 12
Y = -30
2. Float
The float type in Python designates a floating-point number. float values are specified with a decimal point.
X = 53.0454
Y – 24E
Z = -40/3434
3. complex
Complex numbers have real and imaginary parts, which are each floating-point number. The imaginary part is written with the
letter ‘j’.
X = 3+5j
Y = 5j
Z = -6j
SEQUENCE TYPE:
In Python, sequence is the ordered collection of similar or different data types. Sequences allows to store multiple
values in an organized and efficient fashion. There are several sequence types in Python.
1. String:
In Python, Strings are arrays of bytes representing Unicode characters. A string is a collection of one or
more characters put in a single quote, double-quote or triple quote.
String1 = “Welcome”
String2 = ‘Python Data types’
2. List:
Lists are just like the arrays, declared in other languages which is a ordered collection of data. It is very
flexible as the items in a list do not need to be of the same type.
List1 = [] #Declaring an empty list.
List2 = [‘This’, ‘is’, “a”, “Python”, ‘List’, 1,2,5,2]
3. Tuple:
Just like list, tuple is also an ordered collection of Python objects. The only difference between tuple
and list is that tuples are immutable i.e. tuples cannot be modified after it is created.
Tuple1 = () #Declaring an Empty tuple.
Tuple2 = (1, 2, 4, ‘Python’, “Tuple”)
Tuple3 = (“tuple”,) # A tuple with a single value even had to end with comma (,).
BOOLEAN:
Data type with one of the two built-in values, True or False is called as Boolean.
X = True
Y = False
SET:
In Python, Set is an unordered collection of data type that is iterable, mutable and has no
duplicate elements. The order of elements in a set is undefined though it may consist of
various elements.
Dictionary:
Dictionary in Python is an unordered collection of data values, used to store data values like
a map, which unlike other Data Types that hold only single value as an element, Dictionary
holds key:value pair. Key-value is provided in the dictionary to make it more optimized. Each
key-value pair in a Dictionary is separated by a colon(:) whereas each key is separated by a
‘comma’(,).
Dict1 = {} #Creating an empty dictionay
Dict2 = {1:’Stock’, 2: ‘Items’, Items: [‘pen’, ‘pencil’, ‘eraser’], pen: 2 rupees }
TYPE CASTING:
Type Casting is the method to convert the variable data type into a certain data type in order to the operation required to be performed by
users.
There can be two types of Type Casting in Python –
1. Implicit Type Casting
In this, Python converts data type into another data type automatically.
a=7
b = 2.2
print(type(a)) #prints <class ‘int’>
a = a+b # Python automatically converts the “a” (int) to float data type after addition.
print(type(a) ) # prints <class ‘float’>
Python provides us with the two inbuilt functions as input() and output().
We use the print() function to output data to the standard output device (screen).
a=5
print(a)#5
The value of variables was defined or hard coded into the source code
Input ()
A=“Durga”
a=input(“”)
Default it takes string
FLOW CONTROL:
Flow control describes the order in which statements will be executed at runtime.
Flow control is of 3 types in python
1. Conditional Statements
if
else
elif
3. Iterative Statements
for
while
FUNCTIONS:
A function is a block of organized, reusable code that is used to perform a single, related action.
If a group of statements is repeatedly required then it is recommended to write as a single unit which we can call
it many no.of times by it’s name with or without passing parameters based on our requirement. And this unit is
nothing but a function.
In python there are two types of functions:In python there are two types of functions:
--Built in Functions
--User defined Functions
1. Built in Functions:
The functions which comes by default with the Python software are called as Built in functions.
Ex: id(),Type() etc,..
Filter() function;filter(function,sequence)—conditional stmt
Lambda function:l=[0,5,10]
d=list(filter(lambda x:x%2==0,l)]
[0,10] like reduce() etc..some functions are there..
Ex:
def wish():
Print(“Hello! Good Morning”)
wish()
wish()
MODULES:
A group of functions, variables and classes saved to a file, which is nothing but module.
Every Python file (.py) acts as a module.
ex: test.py a=5,b=4
def sum()
return a+b
another file: import test
ptint( test.sum())
output:9
PACKAGES:
package is nothing but folder or directory which represents collection of Python modules.
Opening a File:
Before performing any operation (like read or write) on the file,first we have to open that file.For this we should use Python's inbuilt
function open()
f.open(filename,mode)
Mode: r, w, a, r+, w+, a+, x
Closing a File:
After completing our operations on the file,it is highly recommended to close the file.
f.close()
DECORATORS:
Decorator is a function which can take a function as argument and extend its functionality and returns modified function with extended functionality.
Example:
def login_required(f1):
def inner(name,is_login):
if is_login==False:
print('Kindly login!')
return
return f1(name,is_login)
return inner
@login_required
def home(name,is_login):
print("Welcome to home page of our website!")
@login_required
def orders(name,is_login):
print("Welcome to orders page of our website!")
def about(name,is_login):
print("Welcome to website!")
home('user',False)
home('user',True)
GENERATORS:
2.Runtime Errors:
Also known as exceptions.
While executing the program if something goes wrong because of end user input or programming logic or memory problems etc then we will get Runtime Errors.
Eg: print(10/0) ==>ZeroDivisionError: division by zero/
RUN TIME ERRORS TWO TYPES:
1. Predefined Exceptions:
These will be raised automatically by python virtual machine whenever a particular event occurs
Eg:
try:
print(10/0) ==>ZeroDivisionError: division by zero
except Exception as e:
print(str(e))
It is highly recommended to store complete application flow and exceptions information to a file. This process is called logging.
The main advantages of logging are:
We can use log files while performing debugging
We can provide statistics like number of requests per day etc
To implement logging, Python provides one inbuilt module logging.
Eg:
logging.info(message)
logging.warning(message)
logging.error(message)
OBJECT ORIENTED PROGRAMMING
Python is a multi-paradigm programming language. It supports different programming approaches.
One of the approach to solve a programming problem by creating objects
An object has two characteristics:
1. Attributes
2. Behavior
Class:
Object:
An object (instance) is an instantiation of a class.
The example for object of parrot class can be:
Obj=Parrot()
Here obj is an object of class Parrot
METHODS:
Methods are functions defined inside the body of a class. They are used to define the behaviors of an object.
class Parrot:
# instance attributes
def __init__(self, name, age):
self.name = name
self.age = age
# instance method
def sing(self, song):
return "{} sings {}".format(self.name, song)
def dance(self):
return "{} is now dancing".format(self.name)
# instantiate the object
blu = Parrot("Blu", 10)
# call our instance methods
print(blu.sing("'Happy'"))
print(blu.dance())
INHERITANCE:
Inheritance is a way of creating a new class for using details of an existing class without modifying it. The newly formed class
is a derived class (or child class). Similarly, the existing class is a base class (or parent class).
class Bird:
def __init__(self):
print("Bird is ready")
def whoisThis(self):
print("Bird")
def swim(self):
print("Swim faster")
class Penguin(Bird):
def __init__(self):
# call super() function
super().__init__()
print("Penguin is ready")
def whoisThis(self):
print("Penguin")
def run(self):
print("Run faster")
peggy = Penguin()
peggy.whoisThis()
peggy.swim()
peggy.run()
ENCAPSULATION:
Using OOP in Python, we can restrict access to methods and variables.
This prevents data from direct modification which is called encapsulation.
In Python, we denote private attributes using underscore as the prefix i.e single _ or double __.
class Computer:
def __init__(self):
self.__maxprice = 900
def sell(self):
print("Selling Price: {}".format(self.__maxprice))
def setMaxPrice(self, price):
self.__maxprice = price
c = Computer()
c.sell()
# change the price
c.__maxprice = 1000
c.sell()
# using setter function
c.setMaxPrice(1000)
c.sell()
POLYMORPHISM:
Polymorphism is an ability (in OOP) to use a common interface for multiple forms (data types).
class Parrot:
def fly(self):
print("Parrot can fly")
def swim(self):
print("Parrot can't swim")
class Penguin:
def fly(self):
print("Penguin can't fly“)
def swim(self):
print("Penguin can swim")
# common interface
def flying_test(bird):
bird.fly()
#instantiate objects
blu = Parrot()
peggy = Penguin()
# passing the object
flying_test(blu)
flying_test(peggy)
KEY POINTS TO REMEMBER:
Object-Oriented Programming makes the program easy to understand as well as efficient.
Since the class is sharable, the code can be reused.
Data is safe and secure with data abstraction.
Polymorphism allows the same interface for different objects, so programmers can write efficient code.
Thank you