INDIAN INSTITUTE OF INFORMATION
TECHNOLOGY, BHOPAL (IIIT-BHOPAL)
Department of Information Technology
IT WORKSHOP (ITW LAB)
(IT - 216)
SUBMITTED BY: UNDER SUPERVISION OF:
YASH SHUKLA SUBJECT COORDINATOR: DR. AMIT GUPTA
23U03114 ASSISTANT PROFESSOR, IT Department
IT 3rd SEMESTER (Section 2) IIIT BHOPAL
INDEX
S. Experiment Page Remark
No. No.’s
1. Assignment 1 1-5
(Control Statements and Loops)
(1) Write a python program to check if the given
character is a vowel or consonant.
(2) Write a python program to check whether a
given character is a digit or not. If the given
character is a digit, check whether or not it is
less than 5.
(3) Write a python program to print all the natural
numbers from 1 to n in the reverse order.
(4) Write a python program to check whether a
given year is a leap year or not.
(5) Write a python program to print the Fibonacci
Series up to the number entered by the user.
2. Assignment 2 6-9
(Sting, List, Tuple and Dictionary)
(1) Write a python program to check whether or not a
given string is a palindrome.
(2) Create a list and perform the following methods in
python.
insert() (2) remove() (3) append() (4) len() (5) pop()
(6)clear()
(3) Create a tuple and perform the following methods in
python.
Add items (2) len() (3) check for item in tuple
(4)Access items
(4) Create a dictionary and apply the following methods
in python.
Print the dictionary items (2) access items (3) change
values use len()
3. Assignment 3 9-13
(Function and Module)
(1) Write a program in python by taking a function
called gcd that takes parameters a and b and
returns their greatest common divisor.
(2) Write a python program to develop (i) Call by
Value (ii) Call by Reference
(3) Write a python program to swap two numbers by
using user-defined functions.
(4) Write a python program to perform the binary
search.
(5) Write a python program to print the factorial of a
number by using a module.
4. Assignment 4 13-17
5. Assignment 5
6. Assignment 6
7. Assignment 7
Indian Institute of Information Technology Bhopal
Information Technology Workshop
Branch: IT (Section-2)
Assignments of Python Programming
Submitted by Submitted to
Yash Shukla Dr. Amit Gupta
23U03114 Assistant Professor
Assignment 1 (Control Statements and Loops)
1. Write a python program to check if the given character is a vowel or consonant.
Code:
def check_character(char):
vowels = 'aeiouAEIOU'
if char in vowels:
return f"{char} is a vowel."
else:
return f"{char} is a consonant."
char = input("Enter a character: ")
print(check_character(char))
Output:
2. Write a python program to check whether a given character is a digit or not. If the given
character is a digit, check whether or not it is less than 5.
Code:
def check_digit(char):
if char.isdigit(): # Check if the character is a digit
if int(char) < 5:
return f"{char} is a digit and it is less than 5."
else:
return f"{char} is a digit but it is not less than 5."
else:
return f"{char} is not a digit."
char = input("Enter a character: ")
print(check_digit(char))
Output:
3. Write a python program to print all the natural numbers from 1 to n in the reverse order.
Code:
def print_natural_numbers_reverse(n):
for i in range(n, 0, -1):
print(i, end=" ")
n = int(input("Enter the upper limit: "))
print_natural_numbers_reverse(n)
Output:
4. Write a python program to check whether a given year is a leap year or not.
Code:
def is_leap_year(year):
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
return True
else:
return False
year = int(input("Enter a year: "))
if is_leap_year(year):
print(year, "is a leap year.")
else:
print(year, "is not a leap year.")
Output:
5. Write a python program to print the Fibonacci Series up to the number entered by the user.
Code:
def fibonacci_series(n):
a, b = 0, 1
while a <= n:
print(a, end=" ")
a, b = b, a + b
num = int(input("Enter a number: "))
print(f"Fibonacci series up to {num}:")
fibonacci_series(num)
Output:
Assignment 2 (Strings, List, Tupple and Dictionary)
1. Write a python program to check whether or not a given string is a palindrome.
Code:
def is_palindrome(s):
s = s.lower().replace(' ', '')
return s == s[::-1]
s = input("Enter a string: ")
if is_palindrome(s):
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")
Output:
2. Create a list and perform the following methods in python.
1- insert() 2- remove() 3-append() 4-len() 5-pop() 6-clear()
Code:
my_list = [1, 2, 3, 4, 5]
my_list.insert(2, 10)
print(my_list)
my_list.remove(3)
print(my_list)
my_list.append(6)
print(my_list)
length = len(my_list)
print(length)
last_element = my_list.pop()
print(my_list)
print(last_element)
my_list.clear()
print(my_list)
Output:
3. Create a tuple and perform the following methods in python.
(1) Add items (2) len() (3) check for item in tuple (4)Access items
Code:
my_tuple = (1, 2, 3, 4, 5)
print("Original Tuple:", my_tuple)
temp_list = list(my_tuple)
temp_list.append(6)
my_tuple = tuple(temp_list)
print("Tuple after adding item:", my_tuple)
length = len(my_tuple)
print("Length of the tuple:", length)
item_to_check = 3
if item_to_check in my_tuple:
print(f"{item_to_check} is in the tuple.")
else:
print(f"{item_to_check} is not in the tuple.")
print("First item:", my_tuple[0])
print("Last item:", my_tuple[-1])
print("Items from index 1 to 3:", my_tuple[1:4])
Output:
4. Create a dictionary and apply the following methods in python.
(1) Print the dictionary items (2) access items (3) change values use len()
Code:
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
print(my_dict)
name = my_dict["name"]
age = my_dict["age"]
city = my_dict["city"]
print(name, age, city)
my_dict["age"] = 31
my_dict["city"] = "Los Angeles"
print(my_dict)
length = len(my_dict)
print(length)
Output:
Assignment 3 (Functions and Modules)
1. Write a program in python by taking a function called gcd that takes parameters a and b and
returns their greatest common divisor.
Code:
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
result = gcd(num1, num2)
print("The greatest common divisor of", num1, "and", num2, "is:",
result)
Output:
2. Write a python program to develop (i) Call by Value (ii) Call by Reference
Code:
# Call by Value
def add(x, y):
sum = x + y
return sum
a = 10
b = 20
c = add(a, b)
print("Sum:", c)
print("a:", a, "b:", b)
# Call by Reference
def swap(x, y):
temp = x
x = y
y = temp
a = 10
b = 20
swap(a, b)
print("a:", a, "b:", b)
Output:
3. Write a python program to swap two numbers by using user-defined functions.
Code:
def swap(x, y):
temp = x
x = y
y = temp
return x, y
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
num1, num2 = swap(num1, num2)
print("After swapping:")
print("Number 1:", num1)
print("Number 2:", num2)
Output:
4. Write a python program to perform the binary search.
Code:
def binary_search(arr, x):
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == x:
return mid
elif arr[mid] < x:
low = mid + 1
else:
high = mid - 1
return -1
arr = [2, 3, 4, 10, 40]
x = 10
result = binary_search(arr, x)
if result != -1:
print("Element is present at index", str(result))
else:
print("Element is not present in array")
Output:
5. Write a python program to print the factorial of a number by using a module.
Code:
import math
def factorial(n):
if n < 0:
return None
elif n == 0:
return 1
else:
return math.factorial(n)
num = int(input("Enter a number: "))
result = factorial(num)
if result is not None:
print("The factorial of", num, "is:", result)
else:
print("Factorial is not defined for negative numbers.")
Output:
Assignment 4 (OOPs Concepts - Inheritance and Polymorphism)
1. Write a program in Python to demonstrate following operations in Inheritance.
(a) Simple inheritance (b) Multiple inheritance
Code:
# Simple Inheritance Example
class Parent:
def __init__(self, name):
self.name = name
def display_name(self):
print(f"Parent Name: {self.name}")
class Child(Parent): # Child inherits from Parent
def __init__(self, name, age):
super().__init__(name) # Call Parent's constructor
self.age = age
def display_info(self):
self.display_name()
print(f"Child's Age: {self.age}")
# Multiple Inheritance Example
class Father:
def __init__(self, father_name):
self.father_name = father_name
def show_father(self):
print(f"Father's Name: {self.father_name}")
class Mother:
def __init__(self, mother_name):
self.mother_name = mother_name
def show_mother(self):
print(f"Mother's Name: {self.mother_name}")
class ChildMultiple(Father, Mother): # Child inherits from both Father
and Mother
def __init__(self, father_name, mother_name, child_name):
Father.__init__(self, father_name) # Initialize Father
Mother.__init__(self, mother_name) # Initialize Mother
self.child_name = child_name
def display_family(self):
print(f"Child's Name: {self.child_name}")
self.show_father()
self.show_mother()
# Demonstration of Simple Inheritance
print("Simple Inheritance:")
child_obj = Child("Alice", 10)
child_obj.display_info()
print("\nMultiple Inheritance:")
# Demonstration of Multiple Inheritance
multi_child = ChildMultiple("John", "Emma", "Sophia")
multi_child.display_family()
Output:
2. Write a program in Python to demonstrate following operations in Polymorphism.
(a) Method overriding (b) Operator overriding
Code:
# (a) Method overriding
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print("Generic animal sound")
class Dog(Animal):
def speak(self):
print("Woof!")
class Cat(Animal):
def speak(self):
print("Meow!")
animals = [Dog("Buddy"), Cat("Whiskers")]
for animal in animals:
animal.speak()
# (b) Operator overriding
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __str__(self):
return f"({self.x}, {self.y})"
v1 = Vector(2, 3)
v2 = Vector(4, 5)
v3 = v1 + v2
print(v3)
Output:
Assignment 5 (Multi-threading and Sending an email)
1. Write a program in Python for creating a thread.
Code:
import threading
import time
# Function to print numbers
def print_numbers():
for i in range(1, 6):
print(f"Number: {i}")
time.sleep(0.5)
# Function to print letters
def print_letters():
for letter in ['A', 'B', 'C', 'D', 'E']:
print(f"Letter: {letter}")
time.sleep(1)
# Creating threads
thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=print_letters)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print("Both threads have finished execution.")
Output:
2. Write a program to send an email using Python code.
Code:
import smtplib
from email.message import EmailMessage
# Get sender's email and password as input
sender_email = input("Enter your email address: ")
sender_password = input("Enter your password: ")
# Recipient email address
receiver_email = input("Enter the recipient's email address: ")
# Create an email message
msg = EmailMessage()
msg['Subject'] = 'Test Email'
msg['From'] = sender_email
msg['To'] = receiver_email
# Set the body of the email
msg.set_content('This is a test email sent using Python.')
# Connect to the SMTP server
with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
smtp.starttls()
smtp.login(sender_email, sender_password)
smtp.send_message(msg)
print('Email sent successfully!')
Output:
Indian Institute of Information Technology Bhopal
Information Technology Workshop
Branch: IT (Section-2)
Assignments of Java Programming
Submitted by Submitted to
Yash Shukla Dr. Amit Gupta
23U03114 Assistant Professor
Assignment 6 (Classes, Constructor and Inheritance)
1. Write a Java Program to calculate Area of Rectangle using Classes.
Code
import java.util.Scanner;
class Rectangle {
double length;
double width;
double calculateArea() {
return length * width;
}
}
public class AreaCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Rectangle rectangle = new Rectangle();
System.out.print("Enter the length of the rectangle: ");
rectangle.length = scanner.nextDouble();
System.out.print("Enter the width of the rectangle: ");
rectangle.width = scanner.nextDouble();
double area = rectangle.calculateArea();
System.out.println("The area of the rectangle is: " +
area);
scanner.close();
}
}
Output
2. Write a Java Program to implement Constructors.
Code
class Book {
String title;
String author;
double price;
Book(String title, String author, double price) {
this.title = title;
this.author = author;
this.price = price;
}
void displayInfo() {
System.out.println("Book Title: " + title);
System.out.println("Author: " + author);
System.out.println("Price: ₹" + price);
}
}
public class ConstructorDemo {
public static void main(String[] args) {
Book book = new Book("The Alchemist", "Paulo Coelho",
500);
book.displayInfo();
}
}
Output
3. Write Java program(s) on use of Inheritance.
Code
class Vehicle {
String brand;
int wheels;
void displayInfo() {
System.out.println("Brand: " + brand);
System.out.println("Number of Wheels: " + wheels);
}
}
class Car extends Vehicle {
int seats;
void displayCarInfo() {
displayInfo();
System.out.println("Number of Seats: " + seats);
}
}
public class SingleInheritanceDemo {
public static void main(String[] args) {
Car myCar = new Car();
myCar.brand = "Toyota";
myCar.wheels = 4;
myCar.seats = 5;
myCar.displayCarInfo();
}
}
Output
Assignment 7 ((Exception Handling, Interface and Applet)
1.Write Java program(s) which uses the Exception Handling features of the language,
creates exceptions and handles them properly, and uses the predefined exceptions.
Code
import java.util.Scanner;
public class PredefinedExceptionDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter a number: ");
int number = scanner.nextInt();
System.out.print("Enter a divisor: ");
int divisor = scanner.nextInt();
int result = number / divisor;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not
allowed.");
} catch (Exception e) {
System.out.println("An unexpected error occurred: "
+ e.getMessage());
} finally {
scanner.close();
System.out.println("Program ended.");
}
}
}
Output
2. Write a Java Program on implementing Interface.
Code
interface Animal {
void sound();
void habitat();
}
class Dog implements Animal {
public void sound() {
System.out.println("Dog barks");
}
public void habitat() {
System.out.println("Dog lives in a house or kennel");
}
}
class Cat implements Animal {
public void sound() {
System.out.println("Cat meows");
}
public void habitat() {
System.out.println("Cat prefers indoor or outdoor spaces");
}
}
public class InterfaceDemo {
public static void main(String[] args) {
Animal dog = new Dog();
Animal cat = new Cat();
dog.sound();
dog.habitat();
cat.sound();
cat.habitat();
}
}
Output
3. Develop an Applet that receives an integer in one text field & computes its factorial
value & returns it in another text field when the button “Compute” is clicked.
Code
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class FactorialCalculator extends JFrame
implements ActionListener {
JTextField inputField, resultField;
JButton computeButton;
public FactorialCalculator() {
inputField = new JTextField(10);
resultField = new JTextField(10);
resultField.setEditable(false);
computeButton = new JButton("Compute");
setLayout(new FlowLayout());
add(new JLabel("Enter a number:"));
add(inputField);
add(computeButton);
add(new JLabel("Factorial:"));
add(resultField);
computeButton.addActionListener(this);
setTitle("Factorial Calculator");
setSize(300, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
try {
int num =
Integer.parseInt(inputField.getText());
if (num < 0) {
resultField.setText("Invalid Input");
} else {
resultField.setText(String.valueOf(factorial(num)));
}
} catch (NumberFormatException ex) {
resultField.setText("Invalid Input");
}
}
int factorial(int n) {
if (n == 0 || n == 1) return 1;
return n * factorial(n - 1);
}
public static void main(String[] args) {
new FactorialCalculator();
}
}
Output