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

(CA) Python Unit-4

B.com (CA)

Uploaded by

keerthu2000k
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

(CA) Python Unit-4

B.com (CA)

Uploaded by

keerthu2000k
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

UNIT – 4

4.1. Object in Python


Python is an object-oriented programming language. Everything is in Python treated as an
object, including variable, function, list, tuple, dictionary, set, etc. Every object belongs to its
class. For example - An integer variable belongs to integer class. An object is a real-life entity.
An object is the collection of various data and functions that operate on those data. An object
contains the following properties.

o State - The attributes of an object represent its state. It also reflects the properties of
an object.
o Behavior - The method of an object represents its behavior.
o Identity - Each object must be uniquely identified and allow interacting with the other
objects.

Let's understand the object in the aspect of classes.

The classes and objects are the essential key to the object-oriented programming. Classes are
the blueprint of the object. Classes are used to bundling the data and functionality together.
Each newly created class must have its object. Let's understand real-life example of class and
object.

A human is a class which may have may attributes such as walking, sleeping, thinking, etc.
Suppose we want to name and age of 100 humans, so we don't need to create a class for every
person. We just need to instantiate the multiple objects of that perticular class.

The class contains the user-defined data structure that holds the own data members such as
variables, constructs, and member functions, which can be accessed by creating an object of
the class.

The syntax of creating a class is given below. The syntax of creating a class is given below.

1
Syntax:

class ClassName:
#statement_suite
The class keyword is used to define the class and the user-define class name replaces
ClassName.

Creating an Object of class

The object is essential to work with the class attributes. Instantiate is a term used when we
create the object of any class, and the instance is also referred to as an object. The object is
created using the class name. The syntax is given below.

Syntax:

<object-name> = <class-name>(<arguments>)

In the following example, we have created the object of Person class.

Example -

class Person:
name = "John"
age = 24 def
display (self):
print("Age: %d \nName: %s"%(self.age,self.name))
# Creating a emp instance of Employee
class per = Person() per.display()

Output:

Age: 24
Name: John

Explanation:

In the above code, we have created a Person class which consisted of two attributes age, name
and display function. We created the object of person class called per . Using the object along
with the .dot operator, we accessed the class function.

2
4.2. Turtle Graphics
Turtle is a Python library to draw graphics. After we import Turtle we can give
commands like forward, backward, right, left etc. These commands will draw different shapes
when we. When We combine Search commands, we can create many nice graphics in the below
example we will see some simple scenarios and then some Complex ones where nice graphics
is created.

Turtle Attributes Commands


• forward(10) It moves the turtle (arrow) forward by 10 pixels.
• backward(5) It moves the turtle (arrow) backward by 5 pixels
• right(35) It moves the turtle (arrow) clockwise by an angle of 35 degrees.
• left(55) It moves the turtle (arrow) counter-clockwise by an angle of 55
degrees
• goto(x,y) It moves the turtle (arrow) to the position x, y dot() It creates a
dot in the current position.
• shape(‘circle’) It draws a circle shape.

Some turtle method


METHOD PARAMETER DESCRIPTION

Turtle() None It creates and returns a new turtle object

forward() amount It moves the turtle forward by the specified amount

backward() amount It moves the turtle backward by the specified amount

right() angle It turns the turtle clockwise

left() angle It turns the turtle counter clockwise

penup() None It picks up the turtle’s Pen

pendown() None Puts down the turtle’s Pen

up() None Picks up the turtle’s Pen

down() None Puts down the turtle’s Pen

color() Color name Changes the color of the turtle’s pen

fillcolor() Color name Changes the color of the turtle will use to fill a polygon

3
heading() None It returns the current heading

position() None It returns the current position

goto() x, y It moves the turtle to position x,y

begin_fill() None Remember the starting point for a filled polygon

end_fill() None It closes the polygon and fills with the current fill color

dot() None Leaves the dot at the current position

stamp() None Leaves an impression of a turtle shape at the current location

shape() shapename Should be ‘arrow’, ‘classic’, ‘turtle’ or ‘circle’

Examples

Let’s see some drawings using some simple commands.

Draw a Star
In the below program we draw a start. We choose appropriate steps to move the cursor
forward and then right continuously to get this result.

Example

import turtle star =


turtle.Turtle() for i
in range(100):
star.forward(100)
star.right(144)
turtle.done()

Running the above code gives us the following result


Output

4
Multiple Squares
In the next example we see the drawing of multiple squares all starting from a common point.
We sue the usual simple commands to go forward, backward and then turn 90 degrees.

Example
import turtle
mult_square=turtle.Turtle() def
Multiple_Squares(length, colour):
mult_square.pencolor(colour)
mult_square.pensize(2)
mult_square.forward(length)
mult_square.right(90)
mult_square.forward(length)
mult_square.right(90)
mult_square.forward(length)
mult_square.right(90)
mult_square.forward(length)
mult_square.right(90)
mult_square.setheading(360)
for i in range(60,120,15):
Multiple_Squares(i,"blue")
turtle.done

Running the above code gives us the following result


Output

5
A spiral hexagon
This is a very interesting example where we use turtle to create a spiral structure. The final
shape is a hexagon and there are various colours used in producing the sides of the hexagon.

Example

import turtle colors = [


"pink","yellow","blue","green","white","red"]

sketch = turtle.Pen()
turtle.bgcolor("black")
for i in range(200):
sketch.pencolor(colors[i % 6])
sketch.width(i/100 + 1)
sketch.forward(i)
sketch.left(59)

Running the above code gives us the following result

4.3. Python Modules


What is Python Module?
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.

6
Create a simple Python module
Let’s create a simple calc.py in which we define two functions, one add and another subtract.

# A simple module, calc.py


def add(x, y): return
(x+y)

def subtract(x, y):


return (x-y) Import
Module in Python
We can import the functions, and classes defined in a module to another module using the
import statement in some other Python source file.
When the interpreter encounters an import statement, it imports the module if the module is
present in the search path. A search path is a list of directories that the interpreter searches for
importing a module. For example, to import the module calc.py, we need to put the following
command at the top of the script.

Syntax of Python Import import


module

Note: This does not import the functions or classes directly instead imports the module only.
To access the functions inside the module the dot(.) operator is used.

Importing modules in Python


Now, we are importing the calc that we created earlier to perform add operation.

# importing module calc.py import


calc

print(calc.add(10, 2))

Output: 12

The from-import Statement in Python


Python’s from statement lets you import specific attributes from a module without importing
the module as a whole.

7
Importing specific attributes from the module

Here, we are importing specific sqrt and factorial attributes from the math module.

# importing sqrt() and factorial from the


# module math
from math import sqrt, factorial

# if we simply do "import math", then


# math.sqrt(16) and math.factorial() #
are required. print(sqrt(16))
print(factorial(6))

Output:
4.0
720

Import all Names


The * symbol used with the from import statement is used to import all the names from a
module to a current namespace.
Syntax: from module_name
import *

From import * Statement

The use of * has its advantages and disadvantages. If you know exactly what you will be
needing from the module, it is not recommended to use *, else do so.

# importing sqrt() and factorial from the


# module math from
math import *

# if we simply do "import math", then


# math.sqrt(16) and math.factorial() #
are required. print(sqrt(16))
print(factorial(6))

Output
4.0
720

8
Locating Python Modules
Whenever a module is imported in Python the interpreter looks for several locations. First, it
will check for the built-in module, if not found then it looks for a list of directories defined in
the sys.path. Python interpreter searches for the module in the following manner – First, it
searches for the module in the current directory.
• If the module isn’t found in the current directory, Python then searches each
directory in the shell variable PYTHONPATH. The PYTHONPATH is an
environment variable, consisting of a list of directories.
• If that also fails python checks the installation-dependent list of directories
configured at the time Python is installed.

Directories List for Modules


Here, sys.path is a built-in variable within the sys module. It contains a list of directories that
the interpreter will search for the required module.

# importing sys module import


sys

# importing sys.path print(sys.path)

Output:
[‘/home/nikhil/Desktop/gfg’, ‘/usr/lib/python38.zip’, ‘/usr/lib/python3.8’,
‘/usr/lib/python3.8/lib-dynload’, ”, ‘/home/nikhil/.local/lib/python3.8/site-packages’,
‘/usr/local/lib/python3.8/dist-packages’, ‘/usr/lib/python3/dist-packages’,
‘/usr/local/lib/python3.8/dist-packages/IPython/extensions’, ‘/home/nikhil/.ipython’]

Python built-in modules


There are several built-in modules in Python, which you can import whenever you like.

# importing built-in module math import


math

# using square root(sqrt) function contained


# in math module
print(math.sqrt(25))

# using pi function contained in math module print(math.pi)

9
# 2 radians = 114.59 degrees
print(math.degrees(2))

# 60 degrees = 1.04 radians


print(math.radians(60))

# Sine of 2 radians print(math.sin(2))

# Cosine of 0.5 radians


print(math.cos(0.5))

# Tangent of 0.23 radians


print(math.tan(0.23))

# 1 * 2 * 3 * 4 = 24
print(math.factorial(4))

# importing built in module random


import random

# printing random integer between 0 and 5


print(random.randint(0, 5))

Output:
5.0
3.14159265359
114.591559026
1.0471975512
0.909297426826
0.87758256189
0.234143362351
24
3

10
4.4. Top-Down Design Model:
In the top-down model, an overview of the system is formulated without going into detail for
any part of it. Each part of it then refined into more details, defining it in yet more details
until the entire specification is detailed enough to validate the model. if we glance at a haul as
a full, it’s going to appear not possible as a result of it’s so complicated For example: Writing
a University system program, writing a word processor. Complicated issues may be resolved
victimization high down style, conjointly referred to as Stepwise refinement where,
1. We break the problem into parts,
2. Then break the parts into parts soon and now each of parts will be easy to do.

Advantages:
• Breaking problems into parts help us to identify what needs to be done.
• At each step of refinement, new parts will become less complex and therefore
easier to solve.
• Parts of the solution may turn out to be reusable.
• Breaking problems into parts allows more than one person to solve the problem.

Bottom-Up Design Model:


In this design, individual parts of the system are specified in detail. The parts are linked to
form larger components, which are in turn linked until a complete system is formed.
Objectoriented language such as C++ or java uses a bottom-up approach where each object is
identified first.
Advantage:
• Make decisions about reusable low-level utilities then decide how there will be
put together to create high-level construct. ,

Difference between Bottom-Up Model and Top-Down Model

S.
No.
TOP DOWN APPROACH BOTTOM UP APPROACH

In this approach We focus on In bottom up approach, we solve smaller


breaking up the problem into smaller problems and integrate it as whole and
parts. complete the solution.
1.

Mainly used by structured Mainly used by object oriented


programming language such as programming language such as C++, C#,
COBOL, Fortran, C, etc. Python.
2.

11
Each part is programmed separately Redundancy is minimized by using data
therefore contain redundancy. encapsulation and data hiding.
3.

In this the communications is less


among modules.
4. In this module must have communication.

It is used in debugging, module


documentation, etc.
5. It is basically used in testing.

In top down approach, In bottom up approach composition takes


decomposition takes place. place.
6.

In this top function of system might In this sometimes we can not build a
be hard to identify. program from the piece we have started.
7.

12

You might also like