Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 51

What will be the output of the following Python code?

i = 1
while True:
if i%3 == 0:
break
print(i)
i + = 1

OUTPUT
1
2
What will be the output of the following Python code?
i = 0
while i < 5:
print(i)
i += 1
if i == 3:
break
else:
print(0)
OUTPUT
0
1
2
What will be the output of the following Python code?
i = 0
while i < 3:
print(i)
i += 1
else:
print(0)

OUTPUT
0
1
2
0
What will be the output of the following Python code?
x="abcdef"
while i in x:
print(i, end=" ")

OUTPUT
NameError: name 'i' is not defined
What will be the output of the following Python code?
x="abcdef"
for i in x:
print(i, end=" ")

OUTPUT
a b c d e f
What will be the output of the following Python code?
x = 'abcd'
for i in range(x):
print(i)

OUTPUT
for i in range(x):
TypeError: 'str' object cannot be interpreted
as an integer
What will be the output of the following Python code?
x = 'abcd'
for i in range(len(x)):
print(i)

OUTPUT
0
1
2
3
What will be the output of the following Python code?

x = 123
for i in x:
print(i)

OUTPUT
for i in x:
TypeError: 'int' object is not iterable
What will be the output of the following Python code?

for i in range(2.0):
print(i)

OUTPUT
for i in range(2.0):
TypeError: 'float' object cannot be interpreted
as an integer
What will be the output of the following Python code?

string = "my name is x"


for i in string:
print (i, end=", ")

OUTPUT
m, y, , n, a, m, e, , i, s, , x,
What will be the output of the following Python code?

string = "my name is x"


for i in string.split():
print (i, end=", ")

OUTPUT
my, name, is, x,
Write a python program to count number of characters,
words in the given string

string = input(“Enter a string”)


count=0
for i in string.split():
count=count+1
print("String length: ",len(string))
print("Total words count: ",count)
Write Python code to print following pattern?
* for i in range(5):
* * for j in range(5):
* * * if(j<=i):
print("*",end=" ")
* * * * print()
* * * * *

* * * * * for i in range(5):
* * * * for j in range(5):
* * * if(j>=i):
* * print("*",end=" ")
* print()
Write Python code to print following pattern?
* * * * * for i in range(5):
* * * * for j in range(5):
* * * if(j<i):
print(" ",end=" ")
* * if(j>=i):
* print("*",end=" ")
print()

* * * * * for i in range(5):
* * for j in range(5):
if(i==0 or j==0 or i==4 or j==4):
* * print("*",end=" ")
* * else:
* * * * * print(" ",end=" ")
print()
Write Python code to print following pattern?
* * * * * for i in range(5):
for j in range(5):
* * if((i==j)or i==0 or j==0 ):
* * print("*",end=" ")
else:
* * print(" ",end=" ")
* * print()

* * for i in range(5):
* * for j in range(5):
if((i==j)or i==4 or j==4 ):
* * print("*",end=" ")
* * else:
* * * * * print(" ",end=" ")
print()
Write Python code to print following pattern?
* * for i in range(5):
for j in range(5):
* * if((i+j==4)or i==4 or j==0 ):
* * print("*",end=" ")
else:
* * print(" ",end=" ")
* * * * * print()

* * * * * for i in range(5):
* for j in range(5):
if(i==0 or j==0 or i==4 or i==2):
* * * * * print("*",end=" ")
* else:
* * * * * print(" ",end=" ")
print()
A Modular Approach to Program
Organization
Need for Modules
So far, we have learnt 2 ways of executing Python code:
1. By typing Python instructions directly into the
interpreter and getting it executed immediately.
2. By storing Python instructions in a file and running it as
a scripting.
Cont..

When we write bigger pieces of code, we observe the


following:
1. Our program might become too long and we want a way
to organise it into manageable chunks (files).
2. We might have multiple Python scripts with various
functions already defined that we wish to use in another
piece of work.
The solution for both the problems above is modules!
Cont..

• A module is a reusable piece of Python code that


can be used by other Python programs (and
modules).
• In fact, when we run a Python script, it is
assumed to be running as a default module called
__main__.
• The name of the current module is available in
the variable __name__.
>>> print(__name__)
__main__
Cont..

By storing a Python script as a module, we gain the


following abilities:
1. The contents of the module can be reused by other
Python scripts.
2. The module is considered to be a separate logical unit,
having it's own symbol table where identifiers are
stored, preventing clashes with other modules that
might have the same name(s) for their identifiers.
Importing Built-in Modules
• To gain access to the variables and functions from a module,
you have to import it.
• For example, want to use functions in module math, use this
import statement
>>> import math
• Importing a module creates a new variable with that name.
That variable refers to an object whose type is module:
>>> type(math)
<class 'module'>
Cont..
Once imported a module, you can use built-in function help to see what it contains. Here is the

first part of the help output:

>>> help(math)
Help on module math:
NAME
math

MODULE REFERENCE
http://docs.python.org/3.3/library/math
The following documentation is automatically generated from the Python
source files. It may be incomplete, incorrect or include features that are
considered implementation detail and may vary between Python
implementations. When in doubt, consult the module reference at the location
listed above.

DESCRIPTION
This module is always available. It provides access to the mathematical
functions defined by the C standard.

FUNCTIONS
acos(...)
Cont..
• The statement import math creates a variable called
math that refers to a module object.
• In that object are all the names defined in that module.
Each of them refers to a function object:
Cont..

• Following code can now use all the standard


mathematical function to calculate a square root.
>>> math.sqrt(9)
3.0
• The dot is an operator, just like + and ** are operators.
• In math.sqrt(9), Python finds math in the
current namespace, looks up the module object that
math refers to, finds function sqrt inside that module
and then executes the function call.
Cont..
• Modules can contain more than just functions. Module math, for
example, also defines some variables like pi. Once the module has
been imported, you can use these variables like any others:
>>> import math
>>> math.pi
3.141592653589793

>>> radius = 5
>>> print('area is', math.pi * radius ** 2)
area is 78.53981633974483
Defining Your Own Modules
• Any Python script can be considered to be a module.
• For example, create a module that defines a function
factorial to find the factorial of an integer.
fact.py

# Module to find the factorial of an integer


def factorial(n):
if n==0:
return 1
return n*factorial(n-1)
Cont..
• Let us now write a Python script that reuses the module
fact defined earlier.
• In order to use a module, the module has to be imported.
• Importing a module makes the module name available to
us in our script, and using the module name we will be
able to access the module contents, The syntax for
importing a module is:

import moduleName
Write a program to find the combination using the factorial function of
the fact module
#Program to find the combination of 2 integers
using modules.
import fact
def ncr(n,r):
return int(fact.factorial(n)/
(fact.factorial(r)*fact.factorial(n-r)))

#driver code
x, y = input("Enter 2 integers:").split(' ')
x,y = int(x),int(y)
print(“Combination of {} and {} is {}
“ .format(x,y,ncr(x,y)))
OUTPUT: Enter 2 integers:5 3
The combination of 5 and 3 is 10
Modules, Classes, and Methods
Modules
• A Python module is a file containing Python definitions and
statements.
• A module can define functions, classes, and variables.
• A module can also include runnable code.
• Grouping related code into a module makes the code easier to
understand and use. It also makes the code logically organized.
What Is Object-Oriented Programming?

• Object-oriented programming (OOP) can be seen as a


method of encapsulating related properties and
behaviors using a special construct called classes into
single entities called objects.
• When we hear of OOP, the first thing that comes to mind
is Classes and Objects.
Let’s see a real-life example.
Imagine an architect who creates a blueprint of a house
that shows the dimensions, structure, number of rooms,
and other details of the house.
Python Classes And Objects
• We can think of the blueprint of a house as a class.
• The details of the house such as doors, windows, roof, walls, floor, etc.,
are the attributes of the class.
• House can have the following actions such as opening/closing the door
and window, shielding from the sun, etc., are the behaviours of the class.
• Each time a new house is built from this blueprint, we are actually creating
an instance of the class. These instances is known as Objects.
• Now, each house can have different values for its attributes like the color of
the walls, the thickness of the doors and windows, etc.
Object-Oriented Programming

• OOP permits us to bundle similar properties and


behaviors into containers.
• In Python, these containers are called Classes.
• A class presents to the real-world an instance of itself
called Objects.
• OOP was designed to address some important principles
like Modularity, Abstraction, and Encapsulation.
Cont..
Modularity
• Modularity in OOP refers to grouping components with related
functionality into a single unit. This helps
in robustness, readability, and reusability.
• As a real-world example, a mobile phone can be seen as a single unit.
But it can perform several functionalities like play music, dialing,
messaging, calling, etc. Each of these functionalities is a component that
is designed and maintained separately, however they are connected
together for the proper functionality of the mobile phone.
Cont..
Abstraction
• Abstraction is the process of hiding a method’s real
implementation and only exposing its required characteristics
and behavior.
• As a real-world example, let’s consider our mobile phones. In order
to make a call, we dial the number or select a contact and press the
call button.
• All we know is that a call is made but we don’t know and we may
not care about all the background processes that take place for the
call to be successful.
Cont..
Encapsulation
• Encapsulation in OOP allows programmers to restrict access to chosen
components (attributes and methods) from being accidentally accessed
or depended upon.
Class Definition
• In OOP, a class serves as a blueprint for its instances (objects), as
such, is the primary means for abstraction.
• The class provides a set of behavior in the form of methods and
attributes.
• The methods and attributes are common to all instances of that
class.
Syntax
class <class name> :
// class body

• It starts with the keyword, class, followed by the name of the


class, a colon(:), and then an indented block of code also known as
the body of the class.
Consider the below diagram of a class that prints a
string.
Example 1: Define a class that can add and subtract two numbers.

• The __init__ method is reserved in Python, also known as a constructor, it is called each
time when an object or instance is created from a class. It is commonly used to initialize
the attributes of the class for the created object.
• Each method of the class has the self-identifier, which identifies the instance upon which
a method is invoked. This allows us to create as many objects of a class as we wish.
Class Objects
• We already saw that a class is a blueprint. So, objects also known
as instances are known to be the realization of the blueprint,
containing actual values.
• In example 1 , the line of code
opp = add_sub(x,y)

• Creates an object of the class and passes two variables to


it; x and y.
• This will call the __init__ reserved methods which will receive
these parameters and initialize the class’s variables. Through this
object, we can access the class’s methods and public variables.
Modules, Classes, and Methods
Classes
• Python is an object-oriented programming language, and class is a basis for any
object oriented programming language.
• Class is a user-defined data type which binds data and functions together into
single entity.
• Class is just a prototype (or a logical entity/blue print) which will not consume
any memory.
• An object is an instance of a class and it has physical existence.

• One can create any number of objects for a class.

• A class can have a set of variables (also known as attributes, member variables)
and member functions (also known as methods).
Cont..

To take an example, we would suggest thinking of a car.


• The class ‘Car’ contains properties like brand, model, color, fuel,
and so.
• It also holds behavior like start(), halt(), drift(), speedup(), and
turn().
• An object Hyundai_Verna has the following properties then.

brand: ‘Hyundai’
model: ‘Verna’
color: ‘Black’
fuel: ‘Diesel’
Cont..
class Car:
def __init__(self,brand,model,color,fuel):
self.brand=brand
self.model=model
self.color=color
self.fuel=fuel
def start(self):
pass
def halt(self):
pass
def drift(self):
pass
def speedup(self):
pass
def turn(self):
pass
Cont..

let’s create an object blackverna from this class.

blackverna=Car('Hyundai','Verna','Black','Diesel')

This creates a Car object, called blackverna, with the a forementioned attributes.
Now, let’s access its fuel attribute. To do this, we use the dot operator in
Python(.).
blackverna.fuel

Output
‘Diesel’
Modules, Classes, and Methods
Methods
• A Python method is like a Python function, but it must be called
on an object.
• To create method, you must put it inside a class.
• Now in this Car class, we have five methods, namely, start(),
halt(), drift(), speedup(), and turn().
• In this example, we put the pass statement in each of these,
because we haven’t decided what to do yet.
Calling Methods the Object-Oriented Way
Example
class Try:
def __init__(self):
pass
def printhello(self,name):
print(f"Hello, {name}")
return name
obj=Try()
obj.printhello(‘ABCD’)

Output
Hello, ABCD

You might also like