Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 32

A

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.

false await else import pass


none break except in raise
true class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield

You can get a list of available keywords by using help()


>>> Help(“keywords”)
COMMENTS
Python has commenting capability for the purpose of in code documentation.
Syntax: The hash (#) symbol denotes the staring of a comment in Python.
Ex: # This is a comment in Python
Print(“hello python”) # Comment two

You can comment multiple lines in python using (triple quotes) doc strings (“”” “””) or (‘’’ ‘’’)
Ex:
print(“Hello, this is an example of doc string”)

“”” This is a comment

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.

Set1 = set() #Declaring an empty set


Set2 = {‘a’,’b’,1,2,4,’c’} #Declaring a set with multiple values

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’>

2. Explicit Type Casting


In Explicit Type Casting, users convert the data type of an object to required data type. We use the predefined functions like int(), float(), str(),
list(), set(), etc,. to perform explicit type conversion.
X = 23
Y = “56”
Z = X + int(Y)
X = str(X) # Converting X (int) into String
L = [1,2,5,2,5,6]
S = set(L) #Conveting List into set
OPERATORS :

Operators are used to perform operations on variables and values.


Python divides the operators into the following groups:
 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Identity operators
 Membership operators
 Bitwise operators
INPUT OUTPUT STATEMENTS:

 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

2. Transfer Control statements


 break
 continue
 pass

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..

1. User Defined functions


The functions which are defined by the user(Programmer) are called as user defined functions by using def keyword
Syntax:
def function_name:
……………………..
Body of the functions
……………………..
Return value

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:

It is an encapsulation mechanism to group related modules into a single unit.

package is nothing but folder or directory which represents collection of Python modules.

Ex:file [file1,file2 ] group of modules…


FILE HANDLING:
As the part of programming requirement, we have to store our data permanently for future purpose. For this requirement we should go for files.

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:

 Generator is a function which is responsible to generate a sequence of values.


 We can write generator functions just like ordinary functions, but it uses yield keyword to return values.
 Example:
 def f1():
 yield 1
 yield 2
 yield 3
 result = f1()
 for value in result:
 print(value)
EXCEPTION HANDLING

In any programming language there are 2 types of errors are possible.


1. Syntax Errors
2. Runtime Errors
1. Syntax Errors:
The errors which occurs because of invalid syntax are called syntax errors.
print "Hello“;
Syntax Error: Missing parentheses in call to 'print’:

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

2. User defines Exceptions:


Sometimes we have to define and raise exceptions explicity to indicate that something goes wrong,such type of exceptions are
called user defines exceptions
eg:
class TooYoungException(Exception):
def __init__(self,arg):
self.msg=arg
class TooOldException(Exception):
def __init__(self,arg):
self.msg=arg
age=int(input("Enter Age:"))
if age>60:
raise TooYoungException("Plz wait some more time you will get best match soon!!!")
elif age<18:
raise TooOldException("Your age already crossed marriage age...no chance of getting marriage")
else:
PYTHON LOGGING:

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:

A class is a blueprint for the object.


In python we can define a class by using the keyword ”class” followed by class name

eg: class Parrot:


pass

The above example is an empty class named Parrot

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

You might also like