Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Python Unit1

Object-Oriented Programming (OOP) is a programming paradigm that utilizes objects and classes to model real-world entities, emphasizing concepts such as encapsulation, inheritance, and polymorphism. Python supports OOP principles, allowing for the creation of classes and objects, and promotes code reusability and security through encapsulation and data hiding. The document also compares OOP with procedural programming, highlighting the advantages of OOP in terms of design, maintainability, and problem-solving capabilities.

Uploaded by

deepthi.it
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python Unit1

Object-Oriented Programming (OOP) is a programming paradigm that utilizes objects and classes to model real-world entities, emphasizing concepts such as encapsulation, inheritance, and polymorphism. Python supports OOP principles, allowing for the creation of classes and objects, and promotes code reusability and security through encapsulation and data hiding. The document also compares OOP with procedural programming, highlighting the advantages of OOP in terms of design, maintainability, and problem-solving capabilities.

Uploaded by

deepthi.it
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Object Oriented Programming (OOPs) Concept

Object-oriented Programming (OOPs) is a programming paradigm that uses objects and


classes in programming. It aims to implement real-world entities like inheritance,
polymorphisms, encapsulation, etc. in the programming. The main concept of object-
oriented Programming (OOPs) or oops concepts in Python is to bind the data and the
functions that work together as a single unit so that no other part of the code can access
this data.
OOPS concepts are as follows:
 Class
 Object
 Encapsulation
 Inheritance
 Polymorphism
 Abstraction
Python Class

A class is a collection of objects. A class contains the blueprints or the prototype from which
the objects are being created. It is a logical entity that contains some attributes and
methods.

Some points on Python class:


 Classes are created by keyword class.
 Attributes are the variables that belong to a class.
 Attributes are always public and can be accessed using the dot (.) operator. Eg.:
Myclass.Myattribute

Class Definition Syntax:

class ClassName:
# Statement-1
.
.
.
# Statement-N

Python Objects
In object oriented programming Python, The object is an entity that has a state and
behavior associated with it. It may be any real-world object like a mouse, keyboard, chair,
table, pen, etc. Integers, strings, floating-point numbers, even arrays, and dictionaries, are
all objects. More specifically, any single integer or any single string is an object. The number
12 is an object, the string “Hello, world” is an object, a list is an object that can hold other
objects, and so on. You’ve been using objects all along and may not even realize it.

An object consists of:


 State: It is represented by the attributes of an object. It also reflects the properties of
an object.
 Behavior: It is represented by the methods of an object. It also reflects the response of
an object to other objects.
 Identity: It gives a unique name to an object and enables one object to interact with
other objects.

Creating an Object

This will create an object named obj of the class ClassName defined above.

Obj= ClassName()

Python Inheritance

Inheritance is the capability of one class to derive or inherit the properties from another
class. The class that derives properties is called the derived class or child class and the class
from which the properties are being derived is called the base class or parent class.
The benefits of inheritance are:
 It represents real-world relationships well.
 It provides the reusability of a code. We don’t have to write the same code again and
again. Also, it allows us to add more features to a class without modifying it.
 It is transitive in nature, which means that if class B inherits from another class A, then
all the subclasses of B would automatically inherit from class A.

Types of Inheritance

 Single Inheritance: Single-level inheritance enables a derived class to inherit


characteristics from a single-parent class.

 Multilevel Inheritance: Multi-level inheritance enables a derived class to inherit


properties from an immediate parent class which in turn inherits properties from his
parent class.

 Hierarchical Inheritance: Hierarchical-level inheritance enables more than one


derived class to inherit properties from a parent class.

 Multiple Inheritance: Multiple-level inheritance enables one derived class to inherit


properties from more than one base class.
 Hybrid Inheritance: Hybrid inheritance is a combination of multiple inheritance and
multilevel inheritance.

Python Polymorphism

Polymorphism simply means having many forms. For example, we need to determine if the
given species of birds fly or not, using polymorphism we can do this using a single function.
Polymorphism in Python.

Python Encapsulation
Encapsulation is one of the fundamental concepts in object-oriented programming (OOP).
It describes the idea of wrapping data and the methods that work on data within one unit.
This puts restrictions on accessing variables and methods directly and can prevent the
accidental modification of data. To prevent accidental change, an object’s variable can only
be changed by an object’s method. Those types of variables are known as private variables.
A class is an example of encapsulation as it encapsulates all the data that is member
functions, variables, etc.
Data Abstraction
It hides unnecessary code details from the user. Also, when we do not want to give out
sensitive parts of our code implementation and this is where data abstraction came.

Data Abstraction in Python can be achieved by creating abstract classes.


Advantages of OOP

1. Re-usability (class – method, inheritance)


It means reusing some facilities rather than building them again and again. This
is done with the use of class and inheritance. We can use it ‘n’ number of times
as per our need.
2. Security (Data hiding – private)
With the use of data hiding and abstraction mechanism, we are filtering out
limited data to exposure, which means we are maintaining security and providing
necessary data to view.
3. Easy Debugging (Encapsulation, Dividing problem into sub problems –
sub problem error rectification is easy)
Let’s witness some common issues or problems any developers face in their work.
 Is this the problem in the widget file?
 Is the problem is in the WhaleFlumper?
 Will I have to trudge through that ‘sewage.c’ file?
 Commenting on all these issues related to code.
So, many times, something has gone wrong, which later becomes so
brainstorming for the developers to look where the error is. Relax! Working with
OOP language, you will know where to look for. This is the advantage of using
encapsulation in OOP; all the objects are self-constrained. With this modality
behavior, the IT teams get a lot of work benefits as they are now capable of
working on multiple projects simultaneously with an advantage that there is no
possibility of code duplicity.
4. Data Redundancy (Method reusing and Inheritance)
Through inheritance, we can eliminate redundant code and extend the use of
existing classes.

5. Code Maintenance
This feature is more of a necessity for any programming languages; it helps users
from doing re-work in many ways. It is always easy and time-saving to maintain
and modify the existing codes by incorporating new changes into them.
6. Design Benefits
If you are practicing on OOPs, the design benefit a user will get is in terms of
designing and fixing things easily and eliminating the risks (if any). Here the
Object-Oriented Programs forces the designers to have a long and extensive
design phase, which results in better designs and fewer flaws. After a time when
the program has reached some critical limits, it is easier
7. Better productivity
With the above-mentioned facts of using the application definitely enhances its
users overall productivity. This leads to more work done, finishing a better
program, having more inbuilt features, and easier reading, writing and
maintaining. An OOP programmer cans stitch new software objects to make
completely new programs. A good number of libraries with useful functions in
abundance make it possible.
8. Polymorphism Flexibility
Let’s see a scenario to better explain this behavior.
You behave in a different way if the place or surrounding gets change. A person
will behave like a customer if he is in a market, the same person will behave like
a student if he is in a school and as a son/daughter if put in a house. Here we can
see that the same person showing different behavior every time the surroundings
are changed. This means polymorphism is flexible and helps developers in a
number of ways.
 It’s simplicity
 Extensibility
9. Problems solving
Decomposing a complex problem into smaller chunks or discrete components is
a good practice. OOP is specialized in this behavior, as it breaks down your
software code into bite-sized – one object at a time. The broken components can
be reused in solutions to different other problems (both less and more complex),
or either they can be replaced by the future modules that relate to the same
interface with implementations details.
A general relatable real-time scenario – at a high level, a car can be decomposed
into wheels, engine, and chassis soon. Each of those components can be further
broken down into even smaller atomic components like screws and bolts. The
engine’s design doesn’t need to know anything about the tires’ size to deliver a
certain amount of power (as output) has little to do with each other.
APPLICATION OF OOP:
The most popular application of oops up to now, has been in the area of user
interface design such as windows. There are hundreds of windowing systems
developed using oop techniques.
Real business systems are often much more complex and contain many more
objects with complicated attributes and methods. Oop is useful in this type of
applications because it can simplify a complex problem. The promising areas
for application of oop includes.
1. Real – Time systems.
2. Simulation and modelling
3. Object oriented databases.
4. Hypertext, hypermedia and expert text.
5. Al and expert systems.
6. Neural networks and parallel programming.
7. Decision support and office automation systems.
8. CIM / CAM / CAD system.
POP VS OOP:
OOP:
 In the object oriented approach, large programs are divided into smaller
programs known as objects.
 In OOP, the major emphasis is on data rather than procedure (function).
 It ties data more closely to the function that operates on it, and protects it
from accidental modification from outside functions.

POP:
 In the procedure oriented approach, large programs are divided into smaller
programs known as functions.
 In POP, a program is written as a sequence of procedures or functions.
 While we concentrate on the development of functions, we give very little
attention to the data that are being used by various functions.
OOP and POP Difference
Let’s dive deep into the comparison points between the two programming
paradigms in terms of certain parameters.

Parameters OOP POP

Basic OOP is object-oriented POP is structure or procedure-


Definition programming. oriented programming.

Program The program is divided into The program is divided into


Division objects. functions.

Approach Bottom-Up approach Top-down approach

Access control is done with No access modifiers supported


Access control
access modifiers. .

Every function has different


Data in each object is
Data Control data, so there’s no control
controlled on its own.
over it.

Data can be hidden using No data hiding. Data is


Data Hiding
Encapsulation. accessible globally.

Inheritance is supported in
Inheritance three modes: public, private Inheritance is not supported.
& protected.

Code The existing code can be


No code reusability.
Reusability reused.
Overloading Overloading functions,
or constructors, and operators Overloading is not possible.
Polymorphism are done.

Object functions are linked Parts of a program are linked


Entity Linkage
through message passing. through parameter passing.

Adding new data and Expanding data and function


Expansion
functions is easy. is not easy.

Problem Used for solving big Not suitable for solving big
Solving problems. problems.

C++, JAVA, VB.NET,


Example C, VB, FORTRAN, Pascal
C#.NET , python

Python Features
Python is a dynamic, high-level, free open source, and interpreted programming
language. It supports object-oriented programming as well as procedural-oriented
programming. In Python, we don’t need to declare the type of variable because it
is a dynamically typed language. For example, x = 10 Here, x can be anything
such as String, int, etc.
Features in Python
There are many features in Python, some of which are discussed below as follows:
1. Free and Open Source
Python language is freely available at the official website and you can download
it from the given download link below click on the Download
Python keyword. Download Python Since it is open-source, this means that
source code is also available to the public. So you can download it, use it as well
as share it.
2. Easy to code
Python is a high-level programming language. Python is very easy to learn the
language as compared to other languages like C, C#, Javascript, Java, etc. It is
very easy to code in the Python language and anybody can learn Python basics in
a few hours or days. It is also a developer-friendly language.
3. Easy to Read
As you will see, learning Python is quite simple. As was already established,
Python’s syntax is really straightforward. The code block is defined by the
indentations rather than by semicolons or brackets.
4. Object-Oriented Language
One of the key features of Python is Object-Oriented programming. Python
supports object-oriented language and concepts of classes, object encapsulation,
etc.
5. GUI Programming Support
Graphical User interfaces can be made using a module such as PyQt5, PyQt4,
wxPython, or Tk in python. PyQt5 is the most popular option for creating
graphical apps with Python.
6. High-Level Language
Python is a high-level language. When we write programs in Python, we do not
need to remember the system architecture, nor do we need to manage the memory.
7. Extensible feature
Python is an Extensible language. We can write some Python code into C or C++
language and also we can compile that code in C/C++ language.
8. Easy to Debug
Excellent information for mistake tracing. You will be able to quickly identify
and correct the majority of your program’s issues once you understand how
to interpret Python’s error traces. Simply by glancing at the code, you can
determine what it is designed to perform.
9. Python is a Portable language
Python language is also a portable language. For example, if we have Python code
for windows and if we want to run this code on other platforms such as Linux,
Unix, and Mac then we do not need to change it, we can run this code on any
platform.
10. Python is an Integrated language
Python is also an Integrated language because we can easily integrate Python with
other languages like C, C++, etc.
11. Interpreted Language:
Python is an Interpreted Language because Python code is executed line by line
at a time. like other languages C, C++, Java, etc. there is no need to compile
Python code this makes it easier to debug our code. The source code of Python is
converted into an immediate form called bytecode.
12. Large Standard Library
Python has a large standard library that provides a rich set of modules and
functions so you do not have to write your own code for every single thing. There
are many libraries present in Python such as regular expressions, unit-testing, web
browsers, etc.
13. Dynamically Typed Language
Python is a dynamically-typed language. That means the type (for example- int,
double, long, etc.) for a variable is decided at run time not in advance because of
this feature we don’t need to specify the type of variable.
14. Frontend and backend development
With a new project py script, you can run and write Python codes in HTML with
the help of some simple tags <py-script>, <py-env>, etc. This will help you do
frontend development work in Python like javascript. Backend is the strong forte
of Python it’s extensively used for this work cause of its frameworks
like Django and Flask.
15. Allocating Memory Dynamically
In Python, the variable data type does not need to be specified. The memory is
automatically allocated to a variable at runtime when it is given a value.
Developers do not need to write int y = 18 if the integer value 15 is set to y. You
may just type y=18.
DATA TYPES IN PYTHON
What is a Data Type?
Data type represents the different kinds of values that we store in the
variable.
What is a variable?
Variable is the name of the memory location where we store different types
of values.
type()
It is a built-in function that returns the type of the objects/data elements
stored in any data type.
Syntax:
type(object)
• In python, the data types are:

Note: We do not need to specify the data type explicitly, the interpreter
automatically defines the data type during run time. Python is a dynamically
typed language.
1.NUMERIC
Numeric data type represents the data which has numeric value. Numeric
value can be integer, floating number or even complex numbers.
• Integers:
This value is represented by “int” class. It contains positive or negative
whole numbers (without fraction or decimal).
For example: 5,-10
• Complex:
Complex number is represented by “complex” class. It is specified as (real
part) + (imaginary part)j.
For example – 2+3j

• Float:
This value is represented by float class.
It is a real number with floating point representation. It is specified by a
decimal point.
/* Python program to demonstrate numeric value*/
a=5
print(“Type of a: “,type(a))
b=5.0
print(“Type of b: “,type(b))
c=2+4j
print(“Type of c: “,type(c))

OUTPUT:
Type of a: <class ‘int’>
Type of b: <class ‘float’>
Type of c: <class ‘complex’>

2.DICTIONARY
Python dictionary is an unordered collection of items. Each item of a dictionary has
a key pair.
In Python, a Dictionary can be created by placing a sequence of elements within
curly {} braces, separated by ‘comma’. Values in a dictionary can be of any
datatype and can be duplicated, whereas keys can’t be repeated and must be
immutable (value of the object cannot be changed overtime).
Example: {1: ‘a’, 2: ‘b’}
/* Python program to demonstrate Dictionary*/
a = {1: ‘Anurag’, 2: ‘University’, 3: ‘IT-B’}
print(“Type of a: “,type(a))

OUTPUT:
Type of a: <class ‘dict’>

3.BOOLEAN
Python boolean type is one of the built-in data types, which represents one of the
two values i.e. True or False.
Generally, it is used to represent the truth values of the expressions.
For example, 1==1 is True whereas 2<1 is False.
/* Python program to demonstrate Boolean*/
a=True
print(“Type of a: “,type(a))
b=False
print(“Type of b: “,type(b))

OUTPUT:
Type of a: <class ‘bool’>
Type of b: <class ‘bool’>

4.SET
A Set is an unordered collection data type that is iterable, mutable and has no
duplicate elements.
For example:
{2,4,6}
/* Python program to demonstrate set*/
a={45,56,12}
print(“Type of a: “,type(a))
b={“apple”,”kiwi”,”banana”}
print(“Type of b: “,type(b))

OUTPUT:
Type of a: <class ‘set’>
Type of b: <class ‘set’>

5.SEQUENCE
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.
• String:
Strings in python are surrounded by either single quotation marks, or double
quotation marks.
Example: ‘hello’ is same as “hello”
• List:
Lists are used to store multiple items in a single variable.
The items in the list are separated with the comma (,) and enclosed with the
square brackets [ ].
Example:
[2,’a’,5.7]
• Tuple
Tuples are used to store multiple items in a single variable.
Tuples are written with round brackets
The key difference between tuples and lists is that while the tuples are
immutable objects, lists are mutable. This means that tuples cannot be
changed while lists can be modified.
Example: (3,4.5,’b’)
/* Python program to demonstrate Sequences*/
a=[3,5.6,”hello”]
print(“Type of a: “,type(a))
b=(3,5.6,”hello”)
print(“Type of b: “,type(b))

OUTPUT:
Type of a: <class ‘list’>
Type of b: <class ‘tuple’>
***OPERATORS***

OPERATOR: It is a Symbol.
* It is used to perform the operation on operands.
* Based on no. of operands, it is clarified into 2 types...
(1).Unary operator. (2).Binary operator.
* Operators are divided into 7 types.
*Arithmatic operator:
Arithmetic operators are used to perform mathematical
operations like addition, subtraction, multiplication and
division.
There are 7 arithmetic operators in Python :

1. Addition Operator : In Python, + is the addition operator. It


is used to add 2 values.
Example :
a= 2

b= 3

print(a+b)

Output :
5

2. Subtraction Operator : In Python, – is the subtraction


operator. It is used to subtract the second value from the first
value.
Example :
a= 2
b= 3
print(a-b)

Output :
-1

3. Multiplication Operator : In Python, * is the multiplication


operator. It is used to find the product of 2 values.
Example :
a= 2
b= 3
print(a*b)

Output :
6

4. Division Operator : In Python, / is the division operator. It is


used to find the quotient when first operand is divided by the
second.
Example :
a= 3
b= 2
print(a/b)

Output :
1.5
5. Modulus Operator : In Python, % is the modulus operator.
It is used to find the remainder when first operand is divided
by the second.
Example :
a= 3
b=2
print(a%b)
Output :
1

6. Exponentiation Operator : In Python, ** is the


exponentiation operator. It is used to raise the first operand
to power of second.
Example :
a= 2
b= 3
print(a**b)

Output :
8

7. Floor division : In Python, // is used to conduct the floor


division. It is used to find the floorof the quotient when first
operand is divided by the second.
Example :
a=3
b= 2
print(a//b)
Output :

Operator Description Syntax


+ Addition: adds two operands x+y
– Subtraction: subtracts two operands x–y
* Multiplication: multiplies two operands x*y
Division (float): divides the first operand by the
/ x/y
second
Division (floor): divides the first operand by the
// x // y
second
Modulus: returns the remainder when first operand is
% x%y
divided by the second
** Power : Returns first raised to power second x ** y

*Assignment operator:
1) Assign: This operator is used to assign the value of the right
side of the expression to the left side operand.
Syntax:
x=y+z
Example:
a=3
b=5
c=a+b
print(c)
Output:
8
2) Add and Assign: This operator is used to add the right side
operand with the left side operand and then assigning the
result to the left operand.
syntax:
x += y
Example:
a=3
b=5
a += b
print(a)
Output:
8
3) Subtract and Assign: This operator is used to subtract the
right operand from the left operand and then assigning the
result to the left operand.
Syntax:
x -= y
Example:
a=3
b=5
a -= b
print(a)
Output:
-2
4) Multiply and Assign: This operator is used to multiply the
right operand with the left operand and then assigning the
result to the left operand.
Syntax:
x *= y
Example:
a=3
b=5
a *= b
print(a)
Output: 15
5) Divide and Assign: This operator is used to divide the left
operand with the right operand and then assigning the result
to the left operand.
Syntax:
x /= y
Example:
a=3
b=5
a /= b
print(a)
Output:
0.6
6) Modulus and Assign: This operator is used to take the
modulus using the left and the right operands and then
assigning the result to the left operand.
Syntax:
x %= y
Example:
a=3
b=5
a %= b
print(a)
Output:
3
7) Divide (floor) and Assign: This operator is used to divide the
left operand with the right operand and then assigning the
result(floor) to the left operand.
Syntax:
x //= y
Example:
a=3
b=5
a //= b
print(a)
Output:
0
8) Exponent and Assign: This operator is used to calculate the
exponent(raise power) value using operands and then
assigning the result to the left operand.
Syntax:
x **= y
Example:
a=3
b=5
a **= b
print(a)
Output:
243
9) Bitwise AND and Assign: This operator is used to perform
Bitwise AND on both operands and then assigning the result
to the left operand.
Syntax:
x &= y
Example:
a=3
b=5
a &= b
print(a)
Output:
1
10) Bitwise OR and Assign: This operator is used to perform
Bitwise OR on the operands and then assigning result to the
left operand.
Syntax:
x |= y
Example:
a=3
b=5
a |= b
print(a)
Output:
7
11) Bitwise XOR and Assign: This operator is used to perform
Bitwise XOR on the operands and then assigning result to the
left operand.
Syntax:
x ^= y
Example:
a=3
b=5
a ^= b
print(a)
Output:
6
12) Bitwise Right Shift and Assign: This operator is used to
perform Bitwise right shift on the operands and then assigning
result to the left operand.
Syntax:
x >>= y
Example:
a=3
b=5
a >>= b
print(a)
Output:
0
13) Bitwise Left Shift and Assign: This operator is used to
perform Bitwise left shift on the operands and then assigning
result to the left operand.
Syntax:
x <<= y
Example:
a=3
b=5
a <<= b
print(a)
Output:
96

*Comparision operator(Relational operator) : comparision


operators are used for comparing the values. It either returns True or False
according to the condition. These operators are also known as Comparison
Operator

Operator Description Syntax

Greater than: True if the left operand is greater than


>
the right x>y

Less than: True if the left operand is less than the


<
right x<y
Operator Description Syntax

==
Equal to: True if both operands are equal x == y

!=
Not equal to – True if operands are not equal x != y

Greater than or equal to: True if left operand is


>=
greater than or equal to the right x >= y

Less than or equal to: True if left operand is less


<=
than or equal to the right x <= y

Programs:
a =9
b = 5
print((a > b),(a<b),(a<=b),(a>=b),(a==b),(a!=b))

output:?

* Logical operator: In Python, Logical operators are used on conditional


statements (either True or False). They perform Logical AND, Logical
OR and Logical NOT operations.

OPERATOR DESCRIPTION SYNTAX

And Logical AND: True if both the operands are true x and y

Logical OR: True if either of the operands is


Or true x or y

Not Logical NOT: True if operand is false not x

1)Logical AND operator:


• Logical operator returns True if both the operands are True else it
returns False.
Program:
a = 10
b = 12
c = 0

if a and b and c:
print("All the numbers have boolean value as True")
else:
print("Atleast one number has boolean value as False")

output:?
2) Logical or operator:

.Logical or operator returns True if either of the operands is True.


Program:
a = 10
b = 12
c= 0

if a or b or c:
print("Atleast one number has boolean value as True")
else:
print("All the numbers have boolean value as False")

output:?

3)Logical not operator:


• Logical not operator work with the single boolean value. If the boolean
value is True it returns False and vice-versa.
Program:
a = 10

if not a:
print("Boolean value of a is True")

if not (a%3 == 0 or a%5 == 0):


print("10 is not divisible by either 3 or 5")
else:
print("10 is divisible by either 3 or 5")

output:?

*Identity operator:
• is and is not are the identity operators both are used to check if two
values are located on the same part of the memory. Two variables that
are equal do not imply that they are identical.
• is : True if the operands are identical
• is not : True if the operands are not identical
program:
a = 10
b = 20
c = a

print(a is not b)
print(a is c)

output:?

*Membership operator:
• in and not in are the membership operators; used to test whether a
value or variable is in a sequence.
• in : True if value is found in the sequence
• not in : True if value is not found in the sequence

program:
x = 24
y = 20
list = [10, 20, 30, 40, 50]

if (x not in list):
print("x is NOT present in given list")
else:
print("x is present in given list")

if (y in list):
print("y is present in given list")
else:
print("y is NOT present in given list")
output: ?
*Bitwise operator: In Python, bitwise operators are used to performing
bitwise calculations on integers. The integers are first converted into binary
and then operations are performed on bit by bit, hence the name bitwise
operators. Then the result is returned in decimal format.

• Bitwise operators are used to compare (binary) numbers.

Operator Example Meaning


& a & b Bitwise AND
| a | b Bitwise OR
^ a ^ b Bitwise XOR (exclusive OR)
~ ~a Bitwise NOT
<< a << n Bitwise left shift
>> a >> n Bitwise right shift

Example:

AND Bitwise:

• 12 & 14 = 1100 & 1110 = 1100 = 12

OR Bitwise:

• 1|1=1

• 1|0=1

XOR Python:

• 1010 ^ 1011 will result in 0001.


Control flow Statements
Python Conditions and If statements

Python supports the usual logical conditions from mathematics:

● Equals: a == b
● Not Equals: a != b
● Less than: a < b
● Less than or equal to: a <= b
● Greater than: a > b
● Greater than or equal to: a >= b

These conditions can be used in several ways, most commonly in "if


statements" and loops.

1) Simple if
if statement is the most simple decision-making statement. It is used to
decide whether a certain statement or block of statements will be executed
or not i.e. if a certain condition is true then a block of statement is executed
otherwise not.

Syntax-

if condition:
statement 1
statement 2
.
.
.
Statement n

Example
if statement:

a = 33
b = 200
if b > a:
print("b is greater than a")
EXPLANATION: In this example we use two variables, a and b,
which are used as part of the if statement to test whether b is greater than a.
As a is 33, and b is 200, we know that 200 is greater than 33, and so we print
to screen that "b is greater than a".

2) if else
The if statement alone tells us that if a condition is true it will execute a
block of statements and if the condition is false it won’t. But what if we
want to do something else if the condition is false. Here comes
the else statement. We can use the else statement with if statement to
execute a block of code when the condition is false.

Syntax-

if condition:
statement 1
statement 2
.
.
Statement n
else:
statement 1
statement 2
.
.
Statement n

Example
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
3) Else if ladder
The elif keyword is pythons way of saying "if the previous conditions were
not true, then try this condition".

Here, a user can decide among multiple options. The if statements are
executed from the top down. As soon as one of the conditions controlling
the if is true, the statement associated with that if is executed, and the rest
of the ladder is bypassed. If none of the conditions is true, then the final
else statement will be executed.

Syntax-

if condition:

statement 1
statement 2
.
.
Statement n
elif:
statement 1
statement 2
.
.
Statement n

Example
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")

EXPLANATION: In this example a is equal to b, so the first condition is


not true, but the elif condition is true, so we print to screen that "a and b
are equal".
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")

EXPLANATION: In this example a is greater than b, so the first condition is


not true, also the elif condition is not true, so we go to the else condition
and print to screen that "a is greater than b".

You can also have an else without the elif:

Programs using Control flow statements:


1)Program to read a no. 143 and display a message “I hate you “

a=int(input(“enter number”)

if a==143:

print(“I hate you”)

OUTPUT:

enter number

143
I hate you

2)Biggest of 2 no.s

a=int(input("enter a no."))
b=int(input("enter a no."))

if(a>b):

print(a,"is biggest")

else:

print(b,"is biggest")

OUTPUT:

enter a no.4
enter a no.5

5 is biggest

3)Program to find whether a no. Is even or odd

a=int(input("enter a no."))

if(a%2==0):
print(a,"is even")

else:

print(a,"is odd")

OUTPUT:

enter a no.5

5 is odd

4)WAP to read number x and y and say whether y is a factor of x or


not
x=int(input("enter a no."))

y=int(input("enter a no."))

if(x%y==0):
print(y,"is a factor")

else:

print(y,"is not a factor")

OUTPUT:
enter a no.6

enter a no.3

3 is a factor

5)WAP to read selling price and cost price and tell whether it is
profit or loss
sp=int(input("enter a no."))

cp=int(input("enter a no."))

if(sp>cp):
print("profit")

else:

print("loss")

OUTPUT:

enter a no.65

enter a no.75
loss

6)WAP to read a character and say it whether it is a vowel or


consonant

ch=input("enter a character")

if((ch=='a') or (ch=='e') or (ch=='i') or (ch=='o') or (ch=='u')):


print(ch," is a vowel")

else:

print(ch,"is a consonant")
OUPUT:

enter a character

a is a vowel

7)WAP to check whether an year is leap year or not

year=int(input("enter the value"))

if((year%400==0) and (year%100!=0) or (year%400==0)):

print("leap year")

else:

print("not a leap year")

OUTPUT:

enter the value2022

not a leap year


8)WAP to find biggest of 5 numbers.

a=int(input("enter the value"))

b=int(input("enter the value"))

c=int(input("enter the value"))

d=int(input("enter the value"))


e=int(input("enter the value"))

if(a>b and a>c and a>d and a>e):

print(a,"is biggest")

elif(b>c and b>d and b>e):

print(b,"is biggest")

elif(c>d and c>e):

print(c,"is biggest")
elif(d>e):

print(d,"is biggest")

else:
print(e,"is biggest")

OUTPUT:

enter the value3

enter the value4


enter the value5

enter the value5

enter the value6


6 is biggest

9)WAP to read two numbers and perform the following operations

1)ADD 2)SUB 3)MUL 4)DIV

a=int(input("enter a no"))
b=int(input("enter a no "))

k=int(input("enter choice from 1 to 4"))

print("1.ADD\n 2.SUb\n 3.MUL\n 4.Div\n")


if(k==1):

print(a+b)

elif(k==2):

print(a-b)

elif(k==3):

print(a*b)
elif(k==4):

print(a/b)

OUTPUT:

enter a no4

enter a no 5

enter choice from 1 to 4 3

1.ADD
2.SUb

3.MUL

4.Div
20

10)WAP to display weekdays

a=int(input("enter a no"))
if(a==1):

print("sunday")

elif(a==2):
print("monday")

elif(a==3):

print("tuesday")

elif(a==4):
print("wednesday")

elif(a==5):

print("thursday")
elif(a==6):

print("friday")

elif(a==7):

print("saturday")

OUTPUT:

enter a no5
thursday

11)WAP to read a number and display individual digits

n=int(input("enter a no"))

while(n!=0):

r=n%10

print(r)
n=n//10

OUTPUT:

enter a no376
6

11)WAP to display sum of digits

s=0

n=int(input("enter a no"))
while(n!=0):

r=n%10

s=s+r

n=n//10
print("sum of digits",s)

OUTPUT:

enter a no467
sum of digits 17

12)WAP to find reverse of a number

s=0

n=int(input("enter a no"))

while(n!=0):

r=n%10
s=s*10+r

n=n//10

print("reverse of a number",s)

OUPUT:

enter a no467

reverse of a number 764

13)Palindrone

s=0

n=int(input("enter a no"))
k=n

while(n!=0):

r=n%10

s=s*10+r
n=n//10

if(k==s):

print("palindrone")
else:

print("not palindrone")

OUTPUT:

enter a no2647
not palindrome
14)Armstrong

n=int(input("enter a no"))

k=n

while(n!=0):

r=n%10
s=s+(r*r*r)

n=n//10

if(k==s):

print("Armsrtong")

else:

print("not Armstrong")

OUTPUT:
enter a no153

Armsrtong
LOOPS
In general, statements are executed sequentially: the first statement in a
function is executed first, followed by the second, and so on. There may be
a situation when you need to execute a block of code several number of times.

Programming languages provide various control structures that allow for more

complicated execution paths.

A loop statement allows us to execute a statement or group of statements


multiple times. The following diagram illustrates a loop statement:s.

Python programming language provides following types of loops to handle


looping requirements
While loop

A while loop statement in Python programming language repeatedly executes a target


statement as long as a given condition is True.

The syntax of a while loop in Python programming language is:

while expression:

statement(s)

Here, statement(s) may be a single statement or a block of statements.


The condition may be any expression, and true is any non-zero value. The loop
iterates while the condition is true. When the condition becomes false, program control
passes to the line immediately following theloop.
In Python, all the statements indented by the same number of character spaces after a
programming construct are considered to be part of a single block of code. Python uses
indentation as its method of grouping statements.
Example:

Q) Write a program to display factorial of a given number.


Program:

n=input("Enter the number: ")


f=1
while n>0:
f=f*n
n=n-1

Output:
print "Factorial is",f
Enter the number: 5
Factorial is 120
The for loop:
The for loop is useful to iterate over the elements of a sequence. It means, the for loop
can be used to execute a group of statements repeatedly depending upon the number of
elements in the sequence. The for loop can work with sequence like string, list, tuple, range
etc.
The syntax of the for loop is given below:
for var in sequence:
statement (s)

The first element of the sequence is assigned to the variable written after „for‟ and
then the statements are executed. Next, the second element of the sequence is assigned to the
variable and then the statements are executed second time. In this way, for each element of
the sequence, the statements are executed once. So, the for loop is executed as many times as
there are number of elements in thesequence.
Examples

printletter

Q) Write a program to display the factorial of given number.


Program:

n=input("Enter the number: ")


f=1for i in range(1,n+1):
f=f*i

print "Factorial is",f


Output:

Enter the number: 5


Factorial is 120
Nested Loop:
It is possible to write one loop inside another loop. For example, we can write a for
loop inside a while loop or a for loop inside another for loop. Such loops are called ―nested
loops‖.

print ""

print " ",


print""

print " ",


print""

print " ",


print""
print""

print " ",


print""

print""

print ""
a=1
for i in range(1,5):
for j in range(1,i+1):
print a,

a=a+1
print ""

You might also like