0% found this document useful (0 votes)
43 views20 pages

Python IDE and Basic Programming Exercises

The document outlines various Python experiments covering topics such as IDE usage, basic programming exercises (factorial, Armstrong number, area of a circle, Fibonacci), matrix operations, data structures, threading, exception handling, thread synchronization, and GUI design using Tkinter. Each section includes definitions, example programs, and expected outputs to illustrate the concepts. The document serves as a comprehensive guide for beginners to understand and practice fundamental Python programming skills.

Uploaded by

mahithapureti27
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)
43 views20 pages

Python IDE and Basic Programming Exercises

The document outlines various Python experiments covering topics such as IDE usage, basic programming exercises (factorial, Armstrong number, area of a circle, Fibonacci), matrix operations, data structures, threading, exception handling, thread synchronization, and GUI design using Tkinter. Each section includes definitions, example programs, and expected outputs to illustrate the concepts. The document serves as a comprehensive guide for beginners to understand and practice fundamental Python programming skills.

Uploaded by

mahithapureti27
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

EXPERIMENT -1.

Familiarize with python IDE


A Python IDE (Integrated Development Environment) is software that helps you write, run, and debug Python programs
easily.

Common Python IDEs


 IDLE (comes with Python)
 PyCharm
 Visual Studio Code
 Jupyter Notebook

Example: Python IDLE (Beginner Friendly)


Main Parts of Python IDE
1. Editor:
 Where you write Python code
2. Interpreter / Console:
 Executes Python commands and shows output
3. Run Button:
 Used to run the program
4. Debug Tools:
 Help find and fix errors

Simple Steps to Use Python IDE (IDLE)


1. Open IDLE
2. Click File → New File
3. Type a Python program:
4. print("Hello, Python")
5. Save the file with .py extension
6. Click Run → Run Module or press F5
7. Output appears in the console

Advantages of Using Python IDE


 Easy to write and edit code
 Shows syntax errors
 Faster program execution
 Good for beginners and professionals

EXPERIMENT-2
Exercise on Basic python programs(factorial,Armstrong number,area of the circle,Fibonacci)
1. Factorial
Definition:
Factorial of a number is the product of all positive integers from 1 to that number.
It is written as n!.
Example:
5! = 5 × 4 × 3 × 2 × 1 = 120
PROGRAM:
n = int(input("Enter a number: "))
fact = 1

for i in range(1, n + 1):


fact = fact * i
print("Factorial is:", fact)

OUTPUT:
Enter a number: 5
Factorial is: 120

2. Armstrong Number
Definition:
An Armstrong number is a number where the sum of the cubes of its digits is equal to the number itself.
Example:
153 = 1³ + 5³ + 3³ = 153
PROGRAM:
num = int(input("Enter a number: "))
temp = num
sum = 0

while temp > 0:


digit = temp % 10
sum = sum + digit**3
temp = temp // 10

if sum == num:
print("Armstrong Number")
else:
print("Not an Armstrong Number")

OUTPUT:
Enter a number: 153
Armstrong Number

3. Area of a Circle
Definition:
The area of a circle is the space inside the circle.
Formula:
Area = π × r²

PROGRAM:
r = float(input("Enter radius: "))
area = 3.14 * r * r
print("Area of circle:", area)

OUTPUT:
Enter radius: 12
Area of circle: 452.15999999999997

4. Fibonacci Series
Definition:
The Fibonacci series is a sequence of numbers where each number is the sum of the previous two
numbers.
Example:
0, 1, 1, 2, 3, 5, 8

PROGRAM:
n = int(input("Enter number of terms: "))
a, b = 0, 1
for i in range(n):
print(a, end=" ")
a, b = b, a + b

OUTPUT: Enter number of terms: 10


0 1 1 2 3 5 8 13 21 34

EXPERIMENT-3
AIM: Write a python programs to perform matrix addition and multiplication
What is a Matrix?
A matrix is a rectangular arrangement of numbers in rows and columns.
Example of a 2×2 matrix:
1 2
3 4
 Rows = 2
 Columns = 2

Matrix Addition

 Condition
 Matrix addition is possible only when both matrices have the same size.

PROGRAM:
A = [[1, 2],
[3, 4]]

B = [[5, 6],
[7, 8]]

result = [[0, 0],


[0, 0]]

for i in range(2):
for j in range(2):
result[i][j] = A[i][j] + B[i][j]

print("Matrix Addition:")
for row in result:
print(row)

OUTPUT:
Matrix Addition:
[6, 8]
[10, 12]

Matrix Multiplication
Condition
Number of columns of first matrix = number of rows of second matrix.

PROGRAM:
A = [[1, 2],
[3, 4]]
B = [[5, 6],
[7, 8]]

result = [[0, 0],


[0, 0]]

for i in range(2):
for j in range(2):
for k in range(2):
result[i][j] += A[i][k] * B[k][j]

print("Matrix Multiplication:")
for row in result:
print(row)

OUTPUT:
Matrix Multiplication: [1*5+2*7 ] [1*6+2*8]
[19, 22] [3*5+4*7] [3*6+4*8]
[43, 50]

EXPERIMENT-4

Write a python programs on various data structures.


Data Structure Key Feature
List Ordered, mutable
Tuple Ordered, immutable
Set Unique elements
Dictionary Key-value pairs
Stack LIFO
Queue FIFO
Linked List Node-based structure

1. List (Linear Data Structure)


Explanation:
A list stores multiple items in a single variable. It is ordered, changeable (mutable), and allows
duplicate values.

PROGRAM:
# Creating a list
numbers = [10, 20, 30, 40]

# Adding an element
[Link](50)

# Removing an element
[Link](20)

print(numbers)

OUTPUT:
[10, 30, 40, 50]

2. Tuple (Immutable Data Structure)


Explanation:
A tuple is similar to a list but cannot be changed after creation (immutable).
PROGRAM:
# Creating a tuple
fruits = ("apple", "banana", "cherry")

# Accessing elements
print(fruits[1])

OUTPUT: banana

3. Set (Unordered Collection)


Explanation:
A set stores unique elements only. It is unordered and does not allow duplicates.

PROGRAM:
# Creating a set
numbers = {1, 2, 3, 3, 4}

# Adding an element
[Link](5)
print(numbers)

OUTPUT: {1, 2, 3, 4, 5}

4. Dictionary (Key-Value Pair)


Explanation:
A dictionary stores data in key-value pairs. Keys are unique.

PROGRAM:
# Creating a dictionary
student = {"name": "Harish", "age": 25, "course": "Python"}

# Accessing value using key


print(student["name"])

OUTPUT: Harish

5. Stack (LIFO – Last In First Out)


Explanation:
A stack follows LIFO order. The last element added is removed first.

PROGRAM:
stack = []

# Push elements
[Link](10)
[Link](20)
[Link](30)

# Pop element
[Link]()
print(stack)

OUTPUT: [10, 20]

6. Queue (FIFO – First In First Out)


Explanation:
A queue follows FIFO order. The first element added is removed first.

PROGRAM:
from collections import deque
queue = deque()
# Enqueue elements
[Link](10)
[Link](20)
[Link](30)
# Dequeue element
[Link]()
print(queue)

OUTPUT: deque([20, 30])

7. Linked List (Simple Implementation)


Explanation:
A linked list consists of nodes. Each node contains data and a reference to the next node.

PROGRAM:
class Node:
def __init__(self, data):
[Link] = data
[Link] = None

# Creating nodes
head = Node(10)
second = Node(20)
third = Node(30)

# Linking nodes
[Link] = second
[Link] = third

# Traversing the linked list


current = head
while current:
print([Link])
current = [Link]

OUTPUT: 10
20
30

EXPERIMENT-5.
AIM: Excercise programs on Threads
Defination : A thread in Python is a smallest unit of execution that runs
independently inside [Link] allow a program to perform
multiple tasks at the same time, which is called multithreading.
In Python, threads are created using the threading module.
Key Points
 Thread is a lightweight process
 Thread() is used to create a thread
 start() begins execution
 join() waits for completion

PROGRAM: #Creating a Simple Thread

import threading

def show():
print("Thread is running")

t = [Link](target=show)
[Link]()
[Link]()

print("Main program ended")

OUTPUT:

Thread is running
Main program ended

PROGRAM : # Creating Multiple Threads


Aim:”
To execute multiple threads simultaneously.
Key Points
 Multiple threads can run in parallel
 Each thread performs a separate task

PROGRAM: #Thread with arguments

import threading

def display(num):
for i in range(1, num+1):
print(i)

t = [Link](target=display, args=(5,))
[Link]()
[Link]()
OUTPUT:
1
2
3
4
5
EXPERIMENT- 6
AIM:. Excercise programs on Exceptions

Defination : An exception in Python is an error that occurs during program execution,


which interrupts the normal flow of the program.
Python handles exceptions using try, except, else, and finally blocks.

Types of Exceptions in Python


1. Built-in Exceptions
Errors provided by Python.
Examples:
 ZeroDivisionError
 ValueError
 TypeError
 IndexError
 FileNotFoundError

2. User-Defined Exception:

Exceptions created by the programmer using the raise keyword.


Aim
To handle ZeroDivisionError.
Program
try:
a = 10
b=0
print(a / b)
except ZeroDivisionError:
print("Cannot divide by zero")

Output
Cannot divide by zero

Exercise 2: Handling Invalid Input


Aim
To handle ValueError.
Program
try:
num = int("abc")
except ValueError:
print("Invalid input")
Output
Invalid input
1. TypeError
Definition
A TypeError occurs when an operation is performed on incompatible data types.
Example Program
a = 10
b = "5"
print(a + b)
Output
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Explanation
An integer cannot be added to a string.

2. IndexError
Definition
An IndexError occurs when we try to access an index that does not exist in a list or
tuple.
Example Program
numbers = [10, 20, 30]
print(numbers[5])
Output
IndexError: list index out of range
Explanation
Index 5 does not exist in the list.

3. FileNotFoundError
Definition
A FileNotFoundError occurs when Python cannot find the specified file.
Example Program
file = open("[Link]", "r")
print([Link]())
Output
FileNotFoundError: [Errno 2] No such file or directory: '[Link]'

2. User-Defined Exception in Python

Definition
A user-defined exception is an exception created by the programmer to handle
custom error conditions that are not covered by built-in exceptions.
User-defined exceptions are created by inheriting from the Exception class and
raised using the raise keyword.

Simple Definition (Exam Ready)


A user-defined exception is a custom exception created by the programmer to handle
specific errors in a program.

Steps to Create User-Defined Exception


1. Create a class that inherits from Exception
2. Use raise to throw the exception
3. Handle it using try and except

Example Program: Age Validation


Aim
To create and use a user-defined exception.
Program
class AgeError(Exception):
pass

try:
age = int(input("Enter age: "))
if age < 18:
raise AgeError
else:
print("Eligible to vote")
except AgeError:
print("Age must be 18 or above")

OUTPUT:
Enter age: 15
Age must be 18 or above

EXPERIMENT-7
AIM: Write a python program to achieve thread synchronization in
multithreaded environment

Thread synchronization is the process of controlling the execution of multiple


threads so that shared resources are accessed by only one thread at a time,
preventing data inconsistency and race conditions.
In Python, synchronization is achieved using Lock, RLock, Semaphore, and Event
from the threading module.

Program: Thread Synchronization using Lock


Aim
To achieve thread synchronization in a multithreaded environment using Lock.
Program
import threading
import time
lock = [Link]()
def print_numbers(thread_name):
[Link]()
print(thread_name, "has acquired the lock")
for i in range(1, 6):
print(thread_name, ":", i)
[Link](0.5)
print(thread_name, "has released the lock")
[Link]()
t1 = [Link](target=print_numbers, args=("Thread-1",))
t2 = [Link](target=print_numbers, args=("Thread-2",))
[Link]()
[Link]()
[Link]()
[Link]()

OUTPUT:
Thread-1 has acquired the lock
Thread-1 : 1
Thread-1 : 2
Thread-1 : 3
Thread-1 : 4
Thread-1 : 5
Thread-1 has released the lock
Thread-2 has acquired the lock
Thread-2 : 1
Thread-2 : 2
Thread-2 : 3
Thread-2 : 4
Thread-2 : 5
Thread-2 has released the lock

EXPERIMENT-8

AIM: . Design Graphical user interface application using different


widgets.
Definition
A Graphical User Interface (GUI) allows users to interact with a program using visual
components like buttons, text boxes, labels, etc., instead of typing commands.
In Python, GUI applications are commonly designed using the Tkinter module.

Widgets Used
 Label – displays text.
 Entry – accepts user input
 Button – performs an action
 Checkbutton – selects an option
 Radiobutton – selects one option from many

PROGRAM: GUI Application Using Multiple Widgets


import tkinter as tk
from tkinter import messagebox

# create main window


window = [Link]()
[Link]("Simple GUI Application")
[Link]("300x300")
# label
lbl = [Link](window, text="Enter your name:")
[Link]()

# entry
entry = [Link](window)
[Link]()

# checkbox
check_var = [Link]()
chk = [Link](window, text="Accept Terms", variable=check_var)
[Link]()

# radio buttons
gender = [Link]()
[Link](window, text="Male", variable=gender, value="Male").pack()
[Link](window, text="Female", variable=gender, value="Female").pack()

# button function
def show_message():
name = [Link]()
[Link]("Message", "Hello " + name)

# button
btn = [Link](window, text="Submit", command=show_message)
[Link]()

# start GUI
[Link]()

OUTPUT:

Output (Screen Description)


 A window titled “Simple GUI Application”
 Label asking Enter your name
 Text box to enter name
 Checkbox Accept Terms
 Radio buttons Male / Female
 Submit button
 On clicking Submit → message box shows

EXPERIMENT-9

AIM: Design GUI using different Geometry Managers

Definition:
Geometry managers in Python control how widgets are arranged inside a GUI
window.
Tkinter provides three geometry managers:
 pack() -> automatic arrangement (top, bottom, left, right)
 grid() -> table-like layout (rows and columns)
 place()->absolute positioning using x and y coordinates

PROGRAM: GUI Using pack(), grid(), and place()


import tkinter as tk

# create main window


root = [Link]()
[Link]("Geometry Manager Example")
[Link]("400x300")

# Frame for pack()


frame1 = [Link](root, bg="lightgray")
[Link](fill="x")

[Link](frame1, text="Pack Manager", bg="lightgray").pack(pady=5)


[Link](frame1, text="Pack Button 1").pack(side="left", padx=10)
[Link](frame1, text="Pack Button 2").pack(side="right", padx=10)

# Frame for grid()


frame2 = [Link](root)
[Link](pady=20)

[Link](frame2, text="Username").grid(row=0, column=0, padx=5)


[Link](frame2).grid(row=0, column=1, padx=5)
[Link](frame2, text="Password").grid(row=1, column=0, padx=5)
[Link](frame2, show="*").grid(row=1, column=1, padx=5)

# place()
[Link](root, text="Using place()").place(x=150, y=220)
[Link](root, text="Login").place(x=170, y=250)

# start GUI
[Link]()

OUTPUT:

Output (Screen Description)


 Window titled “Geometry Managers”
 Label and button arranged using pack() at the top
 Label and button aligned in a row using grid()
 Label and button placed at fixed positions using place()

EXPERIMENT-10

AIM: Develop a python program to handle events generated by various


widgets
Definition
Event handling in Python GUI programming is the process of responding to user
actions such as button clicks, key presses, mouse movements, and selections
made on widgets.
In Python, event handling is commonly implemented using the Tkinter module

Widgets and Events Used


 Button → click event
 Entry → text input event
 Checkbutton → select/deselect event
 Radiobutton → selection event
PROGRAM:
import tkinter as tk
from tkinter import messagebox

root = [Link]()
[Link]("Event Handling")

def show_msg():
[Link]("Event", "Button Clicked")

def check_event():
print("Checkbox selected")

# Entry
[Link](root, text="Name").pack()
[Link](root).pack()

# Button
[Link](root, text="Submit", command=show_msg).pack()

# Checkbutton
[Link](root, text="Accept Terms", command=check_event).pack()

# Radiobutton
[Link](root,text="Male").pack()
[Link](root,text="Female").pack()
[Link](root,text="others").pack()

[Link]()
OUTPUT:
EXPERIMENT-11

AIM: Develop a python program to open, close, read, write, and append data
into the files
python Program: File Handling

# File Handling Example in Python

# 1. Open a file in write mode and write data

file = open("[Link]", "w")

[Link]("Hello, this is a test file.\n")

[Link]("Python file handling is easy.\n")

[Link]() # Close the file after writing

# 2. Open the file in append mode and add more data

file = open("[Link]", "a")

[Link]("This line is appended.\n")

[Link]()

# 3. Open the file in read mode and read the contents

file = open("[Link]", "r")

content = [Link]()

print("File Content:\n", content)

[Link]() # Close the file after reading


# 4. Open the file in read mode and read line by line

file = open("[Link]", "r")

print("Reading line by line:")

for line in file:

print([Link]()) # strip() removes extra newline characters

[Link]()

OUTPUT:

File Content:

Hello, this is a test file.

Python file handling is easy.

This line is appended.

Reading line by line:

Hello, this is a test file.

Python file handling is easy.

This line is appended.

Explanation

1. Open a file using open(filename, mode)

o "w" → write (creates or overwrites)

o "a" → append (adds data at the end)

o "r" → read

2. Write/append using write()

3. Read using read() or by iterating line by line

4. Close using close() to free resources

EXPERIMENT-13
AIM: Develop a python program for creation of table, insert a row in a table,
and update an entry in a table
PYTHON PROGRAM: Table Creation, Insert, and Update
import [Link]
try:
# Connect to MySQL
conn = [Link](
host="localhost",
user="root",
password="your_password",
database="testdb" # Make sure this database exists
)
cursor = [Link]()
# 1. Create table
[Link]("""
CREATE TABLE IF NOT EXISTS students (
id INT PRIMARY KEY,
name VARCHAR(50),
age INT
)
""")
print("Table created successfully.")

# 2. Insert a row
[Link]("INSERT INTO students (id, name, age) VALUES (1, 'Alice',
20)")
[Link]() # Commit changes
print("Row inserted successfully.")

# 3. Update an entry
[Link]("UPDATE students SET age = 21 WHERE id = 1")
[Link]()
print("Row updated successfully.")

# Optional: Display table contents


[Link]("SELECT * FROM students")
rows = [Link]()
print("Current Table Data:")
for row in rows:
print(row)

except [Link] as err:


print("Error:", err)

finally:
[Link]()
[Link]()
print("Connection closed.")

EXPECTED OUTPUT:
Table created successfully.
Row inserted successfully.
Row updated successfully.
Current Table Data:
(1, 'Alice', 21)
Connection closed.
Explanation
1. Create Table → CREATE TABLE IF NOT EXISTS ensures table is created
only if it doesn’t exist.
2. Insert Row → INSERT INTO adds a record. [Link]() saves changes.
3. Update Row → UPDATE ... SET ... WHERE ... modifies the existing entry.
4. Fetch Data → SELECT * FROM students to view table contents.
5. Close Connection → Always close cursor and connection to free
resources.

You might also like