Monday, June 8, 2026

4.5 ERROR HANDLING IN PYTHON

 DOWNLOAD PDF

4.5 ERROR HANDLING IN PYTHON

Error Handling

Error handling in Python is the process of detecting and handling errors during program execution using try, except, else, and finally blocks so that the program does not stop suddenly.

 

Errors and Exceptions

 

Errors

An error is a problem in a program that prevents the program from completing its task properly.

Errors may occur due to wrong syntax, incorrect logic, or invalid operations.

 

Debugging

Debugging is the process of finding and correcting errors or bugs in a program.

 

Types of Errors

There are mainly three types of errors in Python.

1.      Syntax Errors

2.      Runtime Errors / Exceptions

3.      Logical Errors

 

1. Syntax Error

A syntax error is an error that occurs when the rules of Python syntax are violated while writing a program.

Syntax errors are detected before the program executes.

 

Causes of Syntax Error

·         Missing colon :

·         Missing brackets

·         Wrong indentation

·         Spelling mistakes in keywords

 

Example

if 5 > 2
    print("Hello")

 

Error

SyntaxError

 

2. Runtime Error / Exception

A runtime error is an error that occurs during the execution of a program after it has been successfully compiled.

An exception is a runtime error that interrupts the normal flow of a program.

 

Causes of Runtime Error

·         Division by zero

·         Invalid input

·         Accessing invalid index

·         File not found

 

Example

a = 10 / 0

Error

ZeroDivisionError

3. Logical Error

A logical error is an error in which the program runs successfully but produces incorrect output.

Logical errors are difficult to detect because no error message is shown.

 

Example

a = 5
b = 3
 
print(a - b)

Expected addition was intended, but subtraction was used.

 

Exception Handling

Exception handling is the process of handling errors in a program using try, except, else, and finally blocks to prevent the program from stopping unexpectedly.

 

Components of Exception Handling

1.      try Block

2.      except Block

3.      else Block

4.      finally Block

 

1. try Block

A try block is a block used to test a block of code for errors.

If an exception occurs, Python immediately transfers control to the except block.

 

Syntax

try:
    # risky code

 

Important Points

·         Used for code that may generate errors

·         Prevents sudden program crash

·         Must be followed by except or finally block

 

2. except Block

The except block is a block used to handle errors or exceptions that occur in the try block.

 

Syntax

except:
    # handling code

 

Important Points

·         Executes only when an error occurs

·         Prevents abnormal termination of program

·         Can handle specific exceptions

 

Example

try:
    a = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")

Output

Cannot divide by zero

 

3. else Block

The else block is a block that executes only when no exception occurs in the try block.

The else block is optional and must come after all except blocks.

 

Syntax

else:
    # code if no error occurs

 

Example

try:
    a = 10 / 2
except ZeroDivisionError:
    print("Error")
else:
    print(a)

 

Output

5.0

 

4. finally Block

The finally block is a block that always executes whether an exception occurs or not.

It is mainly used for cleanup tasks such as closing files, releasing resources, or ending database connections.

 

Syntax

finally:
    # cleanup code

 

Example

try:
    a = 10 / 0
except:
    print("Error")
finally:
    print("Program Ended")

 

Output

Error
Program Ended

 

Complete Example of Exception Handling

try:
    numerator = int(input("Enter numerator: "))
    denominator = int(input("Enter denominator: "))
 
    result = numerator / denominator
 
except ZeroDivisionError:
    print("Cannot divide by zero")
 
else:
    print("Result:", result)
 
finally:
    print("Program execution completed")

 

Output

Enter numerator: 10
Enter denominator: 0
Cannot divide by zero
Program execution completed

 

Advantages of Exception Handling

1.      Prevents program crash

2.      Improves program reliability

3.      Makes debugging easier

4.      Provides better user experience

5.      Handles errors gracefully

 

Disadvantages of Exception Handling

1.      Increases code length

2.      Slightly slows program execution

3.      Difficult for beginners

4.      Improper handling may hide actual errors

 

Main Types of Exceptions in Python

 

1. ZeroDivisionError

ZeroDivisionError occurs when a number is divided by zero.

Example

a = 10 / 0

2. NameError

NameError occurs when a variable or function name is incorrect or undefined.

Example

print(name)

3. TypeError

TypeError occurs when incompatible data types are used together.

Example

a = "5" + 2

4. ValueError

ValueError occurs when the correct type of data is used but with an invalid value.

Example

num = int("abc")

5. IndexError

IndexError occurs when an invalid index is used in a list or sequence.

Example

list1 = [1, 2, 3]
 
print(list1[5])

 

6. FileNotFoundError

FileNotFoundError occurs when a file being opened does not exist.

Example

open("data.txt")

7. Exception as e

Exception as e is used to capture the actual error object and display the error message.


Example

try:
    a = 10 / 0
except Exception as e:
    print(e)

Output

division by zero

 

Common Exam Mistakes

❌ Writing expect instead of except
❌ Forgetting colon : after try and except
❌ Wrong indentation
❌ Confusing syntax error and logical error
❌ Forgetting that finally always executes

 

4.4 GRAPHICS IN PYTHON USING TURTLE

                                                  DOWNLOAD PDF

4.4 GRAPHICS IN PYTHON USING TURTLE


Introduction to Turtle

Turtle is a Python module used to draw shapes, patterns, and pictures on the screen by moving a virtual pen called a turtle.

It is mainly used to teach programming concepts in a visual and interesting way.

It helps students learn programming through drawings and graphics.

It can draw shapes, lines, circles, patterns, and pictures easily.

 

Features of Turtle

Feature

Description

Easy Learning

Helps learn programming through drawings and graphics.

Fun Learning

Makes coding interesting by creating shapes and designs.

Creativity

Allows users to create different drawings and patterns.

Easy Error Detection

Mistakes can be identified easily by looking at the drawing.

Learn Shapes

Helps understand shapes, angles, and positions.

Better Thinking

Improves logical thinking by following drawing steps.


Basic Structure of a Turtle Program

import turtle
 
screen = turtle.Screen( )
pen = turtle.Turtle( )
 
# drawing commands
 
turtle.done( )

Explanation of Basic Turtle Statements

1. import turtle

Definition

import turtle is used to import the Turtle module so that Turtle graphics commands can be used in a Python program.

Simple Meaning

Python loads turtle graphics so drawing commands can work.

Without It

Turtle programs will not work.


2. import turtle as t

Definition

import turtle as t imports the Turtle module and gives it a short alias name t.

Simple Meaning

Instead of writing turtle every time, we can write only t.

Example

import turtle as t
 
pen = t.Turtle()

 

 

 

3. screen = turtle.Screen()

Definition

screen = turtle.Screen() creates a drawing window where the turtle can move and draw.

Simple Meaning

It opens a blank screen or canvas for drawing.

Used For

1.      Changing background color

2.      Setting window size

3.      Changing window title

4.      Detecting keyboard and mouse actions


4. pen = turtle.Turtle()

Definition

pen = turtle.Turtle() creates a turtle object and stores it in the variable pen.

Simple Meaning

It creates the drawing turtle that moves and draws on the screen.


5. turtle.done()

Definition

turtle.done() keeps the Turtle graphics window open until it is closed manually.

Simple Meaning

It prevents the drawing window from closing immediately after the program finishes.


6. turtle.mainloop()

Definition

turtle.mainloop() keeps the Turtle window open and waits for user actions.

Simple Meaning

It allows the program to keep running until the user closes the window.

Uses

1.      Keeps the window open

2.      Waits for keyboard or mouse events

3.      Prevents the program from ending immediately


Important Turtle Commands


1. Turtle Motion Commands

Turtle motion commands are used to move and turn the turtle on the screen.

Command

Definition

Syntax

Example

forward() / fd()

Moves the turtle forward by a specified distance.

forward(distance)

pen.forward(100)

backward() / bk() / back()

Moves the turtle backward by a specified distance.

backward(distance)

pen.backward(50)

right() / rt()

Turns the turtle clockwise by a specified angle.

right(angle)

pen.right(90)

left() / lt()

Turns the turtle anticlockwise by a specified angle.

left(angle)

pen.left(90)


 

 

 

 

2. Circle Command

Command

Definition

Syntax

Example

circle()

Draws a circle or arc with a specified radius.

circle(radius)

pen.circle(50)


3. Color and Style Commands

Color and style commands are used to change the appearance of drawings.

Command

Definition

Syntax

Example

color()

Sets the line color of the turtle pen.

color(color_name)

pen.color("red")

fillcolor()

Sets the color used to fill a closed shape.

fillcolor(color_name)

pen.fillcolor("yellow")

pencolor()

Sets only the outline color of the turtle pen.

pencolor(color_name)

pen.pencolor("blue")

pensize()

Sets the thickness of the turtle pen.

pensize(size)

pen.pensize(5)

speed()

Controls the drawing speed of the turtle.

speed(value)

pen.speed(0)


Turtle Speed Values

Speed Value

Meaning

0

Fastest

1

Slowest

3

Slow

5

Medium

10

Fast


4. Pen Control Commands

Pen control commands control whether the turtle draws while moving.

Command

Definition

Syntax

Example

penup() / pu() / up()

Lifts the pen and stops drawing.

penup()

pen.penup()

pendown() / pd() / down()

Puts the pen down and starts drawing.

pendown()

pen.pendown()


Example

pen.penup()
pen.forward(100)
pen.pendown()
pen.forward(100)

Explanation

The first movement draws nothing because the pen is up.
The second movement draws a line because the pen is down.


5. Position Commands

Position commands control the turtle’s location on the screen.

Command

Definition

Syntax

Example

goto()

Moves the turtle to a specific coordinate.

goto(x, y)

pen.goto(100, 50)

setpos() / setposition()

Moves the turtle to a specific coordinate.

setpos(x, y)

pen.setpos(50, 80)

home()

Returns the turtle to the starting position.

home()

pen.home()


Turtle Coordinate System

Direction

Coordinate Value

Right

Positive X (+X)

Left

Negative X (-X)

Up

Positive Y (+Y)

Down

Negative Y (-Y)

📌 The center of the Turtle screen is (0, 0).

6. Fill Commands

Fill commands are used to fill closed shapes with color.

Command

Definition

Syntax

Example

begin_fill()

Starts filling a shape with color.

begin_fill()

pen.begin_fill()

end_fill()

Ends filling and fills the shape.

end_fill()

pen.end_fill()


Example

pen.fillcolor("yellow")
pen.begin_fill()
 
for i in range(4):
    pen.forward(100)
    pen.right(90)
 
pen.end_fill()

7. Text Command

Command

Definition

Syntax

Example

write()

Displays text on the screen.

write(text)

pen.write("Hello Python")


Example

pen.write("Welcome to Turtle Graphics")

8. Screen and Turtle Control Commands

Command

Definition

Syntax

Example

clear()

Removes all drawings made by the turtle from the screen.

clear()

pen.clear()

reset()

Clears the screen and returns the turtle to its starting state.

reset()

pen.reset()

hideturtle()

Hides the turtle cursor.

hideturtle()

pen.hideturtle()

showturtle()

Displays the turtle cursor.

showturtle()

pen.showturtle()

bgcolor()

Changes the screen background color.

screen.bgcolor(color)

screen.bgcolor("lightblue")

title()

Sets the title of the Turtle window.

screen.title(title)

screen.title("My Drawing")


9. Shape Command

Definition

The shape() function is used to change the appearance of the turtle cursor.

Syntax

pen.shape("shape_name")

Example

pen.shape("turtle")

Common Turtle Shapes

Shape Name

Description

"arrow"

Default arrow cursor

"turtle"

Turtle-shaped cursor

"circle"

Circle-shaped cursor

"square"

Square-shaped cursor

"triangle"

Triangle-shaped cursor

"classic"

Classic turtle cursor


Common Exam Mistakes

1.      Forgetting to write import turtle

2.      Forgetting parentheses in commands

3.      Writing forward instead of forward( )

4.      Confusing penup() and pendown( )

5.      Forgetting turtle.done( )

6.      Using wrong indentation inside loops

7.      Confusing angle and distance