0% found this document useful (0 votes)
2 views28 pages

Python Programming

This document provides an overview of Python programming, covering its definition, constants and variables, types of errors, building blocks of a program, operators, functions, conditional execution, loops, data structures like lists, tuples, and dictionaries, and object-oriented programming concepts. It explains key features such as syntax, error handling, and the advantages of OOP, including encapsulation, inheritance, and polymorphism. Additionally, it details the use of built-in functions, string manipulation, and the structure of classes and objects.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views28 pages

Python Programming

This document provides an overview of Python programming, covering its definition, constants and variables, types of errors, building blocks of a program, operators, functions, conditional execution, loops, data structures like lists, tuples, and dictionaries, and object-oriented programming concepts. It explains key features such as syntax, error handling, and the advantages of OOP, including encapsulation, inheritance, and polymorphism. Additionally, it details the use of built-in functions, string manipulation, and the structure of classes and objects.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

PYTHON NOTES

What is Python?
 Python is a high-level language like other high-level language such as Java, C++, PHP, Ruby,
Basic and Perl.
 Python is an object-oriented programming language.  Python provides security.
 The CPU understands a language which is called as Machine Language.
 Machine language is very complex and very troublesome to write because it is represented all
in zero’s and one’s.
 The actual hardware inside CPU does not understand any of these high-level languages.

Constants and Variables:


 Variables can have any name, but Python reserved words cannot be used.
 A variable provides a named storage that the program can manipulate.

Constants and Variables:


 Variables can have any name, but Python reserved words cannot
be used.
 A variable provides a named storage that the
program can manipulate.
 Variables are named memory location used to store data in
program which keeps on changing during execution.
 Programmers can decide the names of the variables.
 Fixed values used in programs such as numbers, letters and
strings are called “Constants”.
 Values of constants never change during program execution.
Mnemonic Variable Names:
 Use simple rules of variable naming and avoid reserved
words.
 While using simple rules, we have a lot of choice for variable
naming.
 Initially this choice can be confusing either in reading or writing the
program.
 The following two programs are identical in terms of what they
accomplish, but very different when you read and try to understand
them:
Eg 1: a=35.0
b=12.50
c=a*b print(c)
O/P: 437.5
Eg 2: hours=35.0
rate=12.50
pay=hours*rate
print(pay)
O/P: 437.5

Compilers and Interpreters:

 Compiler is a computer program(or a set of programs) that


transforms source code written in a programming language into
another computer language.
 Interpreters reads the source code of the program, line
by line, passes the source code, and interprets the instructions.
Types of errors:
A syntax error: It occurs when the “grammar” rules of Python are violated.

A logic error: It occurs when the program has good


syntax but there is a mistake in the order of the statements.
Eg:
 Using wrong variable name.
 Making a mistake in a Boolean expression.
 Indenting a block to the wrong level.
 Using integer division instead of floating-point
division.
A Semantic error: It occurs when the description of the steps to take is
syntactically perfect, but the program does not do what it was intended to do.

Building blocks of a Program:


These are some of the conceptual patterns that are used to construct a
program:

 Input: Input will come from the user typing data on the
keyboard.
 Output: Display the results of the program on a screen or
store them in a file.
 Sequential Execution: Perform statements one after another
in the order in which they are encountered in the script.
 Conditional Execution: Checks for certain
conditions and then execute or skip a sequence of
statements.
 Repeated Execution: Perform some set of
statements repeatedly, usually with some variation.
 Reuse: Write a set of instructions once then
reuse those instructions in the program.
Operators and its Precedence:
 Operators are used to manipulate the values of operands.
 There are various types of operators used in program:
o Comparison (relational) operators.
o Assignment operators.
o Logical operators.

Arithmetic Operators:
 Are the symbols that are used to perform arithmetic operations on
operands.

Types of Arithmetic operators:


o + ,- ,* ,/ ,%.

Comparison Operators:

 Compares the values of an operands and decide the relation


among them.
 They are also called as Relational Operators.

Types of Comparison Operators:

 < - less than.


 >- greater than.
 <= - less than equal to.
 >= - greater than equal to.
 == - equal to.
 != - not equal to.
Logical Operators:
 Are used to evaluate expressions and return a Boolean
value.

Types of Logical Operators:

o x && y: Performs a logical AND of the two operands.


o x || y: Performs a logical OR of the two operands.
o ! x: Performs a logical NOT of the operand.

2. Logical Operators (Contd..):

 There are three logical operators and, or and not.


 The semantics of these operators is similar to their meaning in
English.
 Eg: x>0 and x<10 (is true only if x is greater than 0 and less than
10).
 n %2==0 or n % 3==0(is true if either of the condition is
true).
 The not operator negates a Boolean expression.
 Eg: not(x>y) is true if x>y is false.
Operator Precedence:

 When we use multiple operators in an expression, program must


know which operator to execute first. This is called as “Operator
Precedence”.
 The following expression multiple operators but they will execute as
per precedence rule:
o X=1+2*3-4/5**6.
 Eg 1: b=10, a=5, b%a O/P: 0.
 Eg 2: b=10, a=5, b%a==5 O/P: False.

Comments:
 Comments helps in getting description about the code for
future reference.
 In Python, Comment starts with # symbol.
 Eg: # compute the percentage of the hour that has elapsed
percentage = (minute*100)/60.
 In the above case, the comment appears on a line by itself.
Comments can also be put at the end of a line.
 Percentage = (minute*100)/60.
# - Percentage of an hour.

3. Functions:
 In the context programming, defining a function means
declaring the elements of its structure.

 The following syntax can be used to define a function:

 Syntax:
def function_name (parameters): function_body
return [value].

 A function is a named sequence of statement that


performs an operation.
 After defining, the function can be executed by
calling it.

Built-in Functions:

 Python provides a number of important built-in functions


that can be used without needing to provide the function
definition.
 abs(), divmod(), str(), sum(), super(), int(), eval(), bin(), bool(), file(),
filter(), format(), type().
 Math module: It provides functions for specialized
mathematical operations.
Conditional Execution:
 There are situations where an action performed based on a
condition. This is known as “Conditional Execution”.
 The various conditional constructs are implemented
using
o If statement.
o If else statement.
o Chained statement.
o Nested statement.

If statement:
 Contains a logical expression using which data is compared and a
decision is made based on the result of comparison.
 Syntax: if condition:
action
Chained Conditions:
 Elif statement: Allows to heck multiple expressions for TRUE and
execute a block of code as soon as one of the conditions evaluates
to TRUE.
 Nested Conditions: There may be a situation when
there is need to check for another condition resolves
to true. In such a situation, the nested if construct is used.

Loop Pattern:
 Loops are generally used to:
o Iterate a list of items.
o View content of a file.
o Find the largest and smallest data.
 There are two types of loops:
o Infinite loops.
o Definite loops.
Infinite loops:
 Sequence of instructions in a computer program which loops
endlessly.
 Also known as endless loop or unproductive loop.
 Solution to an infinite loop is using break statement.

Break and Continue Statement:


 The break statement is used to exit from the loop.
 The break statement prevents the execution of the remaining
loop.

 The Continue Statement is used to skip all the subsequent


instructions and take the control back to the loop.

For loop:
 Used to execute a block of statements for a specific number of
times.
 Used to construct a definite loop.
 Syntax: for<destination> in <source>
statements print
<destination>

While loop:
 Is used to execute a set of instructions for a specified
number of times until the condition becomes False.
 Syntax: while(condition)
Executes code exit.

Working of While loop:


 Evaluate the condition, yielding True of False.
to true. In such a situation, the nested if construct is used.
 If the condition is false, exit the while statement and continue
execution at next statement.
 If the condition is true, execute the body and then go back to step 1.

4. String:
 A string is a sequence of characters.
 Single quotes or double quotes are used to represent strings.
 There are some special operators used in string.

5. Special String Operators:


 Concatenation (+): Adds values on either side of the operator.
 Repetition (*): Creates new strings, concatenating multiple
copies of the same string.
 Slice ([]): Gives the character from the given index.
 Range Slice ([:]): Gives the character from the given range.
 Membership (in): Returns True if a character exists in the given
string.
 Membership (not in): Returns True if a character
does not exists in the given string.
 Some of the built-in String Methods are as follows:

 Capitalize().
 isupper().
 istitle().
 len(string).
 lower()
 strip().
 upper().
Format Operator:
 “%” operator allows to construct strings, replacing parts of the
strings with the data stored in variables.
 “%” operator will work as modulus operator for strings.
 “%” operator works as a format operator if the
operand is string.

Exception Handling:
 An Exception is an event, which occurs during the execution of a
program that stops the normal flow of the program’s instructions.
 When Python script raises exception it must either handle or
terminate.
 Exceptions are handled using the try and except
keywords.
 Syntax:
try
//Code
except Exception 1:
//error message
except Exception 2:
//error message
else:
//error message
List:
 Most versatile datatype available in python.
 Defined as a sequence of values.
 Holds values between square brackets separated by commas.
 Holds Homogenous set of items.
 Indices start at 0.
 Lists are Mutable.
List Functions:
 sum( ): Using this function, we can add elements of the list. It will
work only with the numbers.
 min( ): Using this function, we can find the minimum value from the
list.
 max( ): Using this function, we can find the maximum value from the
list.
 len( ): Using this function, we can find the number of elements in
the list.

Tuples:
 A Tuple is an immutable List.
 A Tuple stores values, similar to a List, but uses different
syntax.
 A Tuple cannot be changed once it is created.
 Tuple uses parentheses, whereas lists use square brackets.
 A Tuples is a sequence of immutable Python objects.
Features of Tuples:
 Tuples are more efficient.
 Tuples are faster than Lists.
 Tuples are converted into Lists, and vice-versa.
 Tuples are used in String Formatting.
 Note: We cannot perform Add, Delete and Search operations on
Tuples.
Difference between List and Tuple
List Tuple
[] ()

Yes (can change) No (cannot change)

Slower Faster

More methods (append(), remove()) Fewer methods (count(), index())

More Less

Dynamic data Fixed data

[1, 2, 3] (1, 2, 3)

Dictionary:
It is a “bag” of values, each with its own label.
It contains the values in the form of key-value pair.
Every value in Dictionary is associated with a key.
Characteristics of Dictionary:
 Dictionaries are Python’s most powerful data collection.
 Dictionaries allows us to do fast database-like operations in
Python.
 Dictionaries have different names in different
languages.
o Associative Arrays- Perl/PHP.
o Properties or Map or HashMap- Java.
o Property Bag- C#/ .NET.
 Dictionary Keys can be of any Python data type. Because keys are
used for indexing, they should be immutable.
Object-Oriented Programming (OOPs) in
Python
What is OOPs?
Object-Oriented Programming (OOP) is a programming style where we create
objects and classes to organize code.
Instead of writing everything in functions, OOP helps us model real-world entities
like:
 Student
 Car
 Bank Account
 Employee
Each object contains:
 Data → Variables/Attributes
 Behavior → Functions/Methods

Class and Object


Class
A class is a blueprint/template for creating objects.
Example:
A class Car defines:
 color
 brand
 speed
But it is not a real car.

Object
An object is a real instance created from the class.
Example:
 BMW car
 Audi car
Both are objects of class Car.

Syntax
class ClassName:
# attributes
# methods
Constructor (__init__)
What is Constructor?
A constructor is a special method that automatically runs when an object is
created.
Used to initialize object data.
Syntax
def __init__(self):

Example
class Student:

def __init__(self, name, age):


[Link] = name
[Link] = age

s1 = Student("Kanny", 21)

print([Link])
print([Link])

Understanding self
self refers to the current object.
Example:
[Link]
means:
store value inside current object's name
Instance Variables
Variables created using self.
Each object has its own copy.

Example
class Car:

def __init__(self, brand):


[Link] = brand

c1 = Car("BMW")
c2 = Car("Audi")

print([Link])
print([Link])
Output
BMW
Audi

Methods in OOP
Methods are functions inside a class.

Example
class Student:

def __init__(self, name):


[Link] = name

def display(self):
print("Student Name:", [Link])
s1 = Student("Kanny")
[Link]()

Advantages of OOPs
Advantage Explanation

Reusability Code reuse through inheritance

Security Data hiding

Easy Maintenance Organized code

Scalability Easy to expand

Real-world Mapping Models real systems

Types of Inheritance
Type Meaning

Single One parent → One child

Multiple Multiple parents

Multilevel Grandparent → Parent → Child

Hierarchical One parent → Many children

1. Encapsulation
Definition
Binding data and functions together inside a class.
Used for:
 Data hiding
 Security
Example
class Employee:

def __init__(self):
self.__salary = 50000

def show_salary(self):
print(self.__salary)

e1 = Employee()
e1.show_salary()
Output
50000
2. Inheritance
Definition
A child class acquires properties and methods of parent class.
Used for:
 Code reuse
 Reducing duplicate code

Example
class Father:

def bike(self):
print("Father Bike")

class Son(Father):
pass

s1 = Son()
[Link]()
Output
Father Bike
[Link]
Definition
One method behaves differently in different classes.
Method Overriding
Child class changes parent method.
Example (Method Overriding)
class Animal:

def sound(self):
print("Animal Sound")

class Dog(Animal):

def sound(self):
print("Bark")

d1 = Dog()
[Link]()
Output
Bark
4. Abstraction
Definition
Hiding implementation details and showing only important features.
Used with:
 Abstract Classes
 Abstract Methods
Example
from abc import ABC, abstractmethod
class Vehicle(ABC):
@abstractmethod
def start(self):
pass
class Car(Vehicle):
def start(self):
print("Car Starts")
c1 = Car()
[Link]()

Output
Car Starts
Types of OOPs

OP Concept Meaning Main Purpose

Encapsulation Wrapping data and methods into one class Data security

Inheritance One class acquires properties of another class Code reusability

Polymorphism Same method behaves differently Flexibility

Abstraction Hiding internal implementation details Simplicity

Access Modifiers
Modifier Syntax Access

Public name Anywhere

Protected _name Inside class/subclass

Private __name Only inside class


super() Function in Python
What is super()?
super() is used to access:
 Parent class constructor
 Parent class methods
Mainly used in Inheritance.

Why use super()?


Without super(), child class cannot directly call parent constructor easily.
It helps:
 Reuse parent code
 Avoid duplicate code

Syntax
super().method_name()

Example 1 — Calling Parent Constructor


class Father:

def __init__(self):
print("Father Constructor")

class Son(Father):

def __init__(self):
super().__init__()
print("Son Constructor")

s1 = Son()
Output
Father Constructor
Son Constructor

Advantages of super()
Advantage Explanation

Reuse Code Uses parent methods directly

Cleaner Code No need to call parent class manually

Easy Maintenance Better inheritance handling

Magic Methods (Dunder Methods)


What are Magic Methods?
Magic methods are special methods with: ___ on both sides.
Also called:
 Dunder methods
 Special methods
Example:
__init__
__str__
__len__
Why are Magic Methods Used?
They allow objects to behave like:
 strings
 numbers
 lists
 operators
Python automatically calls them.
Common Magic Methods
Method Purpose
__init__ Constructor
__str__ String representation
__len__ Length of object
__add__ Addition using +
__del__ Destructor
__repr__ Official string representation

1. __init__ Method
Automatically runs when object is created.

Example
class Student:

def __init__(self, name):


[Link] = name

s1 = Student("Kanny")
print([Link])
2. __str__ Method
Controls what prints when object is displayed.
Example
class Student:
def __str__(self):
return "Student Object"
s1 = Student()
print(s1)
Output
Student Object
3. __len__ Method
Used when len() is called.

Example
class Demo:

def __len__(self):
return 5

d1 = Demo()

print(len(d1))
Output
5
4. __add__ Method
Defines behavior of + operator.

Example
class Number:

def __init__(self, num):


[Link] = num

def __add__(self, other):


return [Link] + [Link]

n1 = Number(10)
n2 = Number(20)
print(n1 + n2)
Output
30
5. __del__ Method
Destructor method.
Runs when object is destroyed.

Example
class Demo:

def __del__(self):
print("Object Destroyed")

d1 = Demo()

Difference Between super() and Magic Methods

Feature super() Magic Methods

Purpose Access parent class Special behavior for objects

Used In Inheritance Operator/object customization

Example super().__init__() __str__()

Called By Programmer Python automatically

You might also like