You are on page 1of 33

A

PowerPoint Presentation
on
Python
By
Durga Prasad Kopanathi
Contents:
 Introduction
 Features of Python
 Identifiers
 Keyword
 Lines and Indentations
 Comment
 Data Types
 Type Casting
 Operators
 Input and Output Statements
 Flow Control
 Functions
 Generators
 Modules
 Packages
 File Handling
 Exception Handling
 Python Logging
Introduction:
 Interpreted, Object-oriented, High-level programming language.
 It was developed by Guido Van Rassam 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 are
Web Applications , Developing games, Desktop Applications,
Database Application, MI and AI, data visualization and in
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”)
Comment
 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: “””
This is a comment
written in
more than just one line “””
Data Types
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
Str:

 String is a sequence of characters .


 It contains alphabets,numbers and special characters.Strings
are enclosed with sigle or double or triple quotes
 It is immutable in nature
ex:s1='durga prasad’
s1="""durga
prasad"“
In this slicing operations and It contains inbuilt functions

Len(),count(),strip() etc….
List:
 it is ordered and changeable allows duplicate members.
 List can be written as list of comma-separated values(items) between square brackets.
 Items in the list need not be of the same type.
 List indices start at ‘0’ in forward direction and with ‘-1’ in backward direction.
Eg: list1=[1,2,3]
List2=[1,’abc’,12.3]
It contains inbuilt functions like :len(),min().max(),append() etc..
Tuple:

 It is ordered and un changeable. Allows duplicate members.


 Tuple is exactly same as List except that it is immutable.

 The empty tuple is written as two parenthesis containing


nothing.
 Ex: tup1=()
 To write a tuple containing a single value you have to include
a comma, even though there is only one value.
 Ex: tup1=(20,)
 Tuple index starts from 0.
 It contains inbuilt functions like :len(),min(),max(),cmp()
etc..
Set:
 it is unordered and un indexed. No duplicate members.
 A set is a collection which is unordered and unindexed. In python sets are written with curly
brackets.
 Example: set1={‘a’,’b’,’c’}
 It has inbuilt functions like:
add(),update(),union().remove() etc..
Dictionary:
 It is unordered, changeable and indexed. No duplicate members.
 We can use List,Tuple and Set to represent a group of individual objects as a single entity. If we
want to represent a group of objects as key-value pairs then we should go for Dictionary.
 An empty dictionary without any items is written with just two curly braces, like this {}
ex:s = {100:'durga' ,200:'ravi', 300:'shiva’}

It has inbuild functions :len(),get(),pop() etc…


Type Casting
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
Logical operators
Identity operators
Membership operators
Bitwise operators
Input Output Statements

 Python provides us with the two inbuilt functions as input() and output().
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.
 Ifa 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.
 Inpython there are two types of functions:In python there
are two types of functions:
--Built in Functions
--User defined Functions
1.Builtin Functions:
The functions which comes by default with the Python software are called as Built
in functions.
Ex: id(),Type() etc,..
2.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
test.sum()
output:9
Packages
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()
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“;
SyntaxError: 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
TypeError: unsupported operand type(s) for /: 'int' and 'str’

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:def withdraw(amount):
if amount>=balnce:
raise In suficientfunds Exceptions
else:
process request
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.debug(message)
logging.info(message)
logging.warning(message)
logging.error(message)
logging.critical(message)
Object Oriented Programming
 Python is a multi-paradigm programming language. It supports different programming approaches.
 Python is a multi-paradigm programming language. It supports different programming approaches.
 An object has two characteristics:
• attributes;
• 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
Here 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)
 # instantiate the object
 blu = Parrot("Blu", 10)
 # call our instance methods
 print(blu.sing("'Happy'"))
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).
 # parent class
 class Bird:
 def __init__(self):
 print("Bird is ready")
 def whoisThis(self):
 print("Bird")
 # child class
 class Penguin(Bird):
 def __init__(self):
 # call super() function
 super().__init__()
 print("Penguin is ready")
 def run(self):
 print("Run faster")
 peggy = Penguin()
 peggy.whoisThis()
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.

You might also like