Indian Institute of Information Technology
Bhopal
CW LAB Assignment
Submitted To: Submitted By:
Dr. Saurabh Jain Shankar Kumar
Scholar no.: 23U02116
Branch: CSE Sec II
1. Write a program to print student name, scholar number and branch.
Code:
def print_student_info(name, scholar_number, branch):
print("Student Information:")
print(f"Name: {name}")
print(f"Scholar Number: {scholar_number}")
print(f"Branch: {branch}")
name = input("Enter your name: ")
scholar_number = input("Enter your scholar number: ")
branch = input("Enter your branch: ")
print_student_info(name, scholar_number, branch)
Output:
2. Write a program to declare and initiate two integers.
Code:
num1 = 10
num2 = 5
addition = num1 + num2
subtraction = num1 - num2
multiplication = num1 * num2
division = num1 / num2 if num2 != 0 else "Undefined (division by zer)"
print("First integer:", num1)
print("Second integer:", num2)
print("Addition:", addition)
print("Subtraction:", subtraction)
print("Multiplication:", multiplication)
print("Division:", division)
Output:
3. Write a program to calculate area and circumference of a circle.
Code:
import math
radius = float(input("Enter the radius of the circle: "))
area = math.pi * (radius ** 2)
circumference = 2 * math.pi * radius
print(f"Area: {area:.2f}, Circumference: {circumference:.2f}")
Output:
4. Write a program to calculate area and perimeter of a rectangle.
Code:
length = float(input("Enter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))
area = length * width
perimeter = 2 * (length + width)
print(f"Area: {area:.2f}, Perimeter: {perimeter:.2f}")
Output:
5. Write a program to convert Rupees into Dollar.
Code:
conversion_rate = 84
rupees = float(input("Enter the amount in Rupees: "))
dollars = rupees / conversion_rate
print(f"{rupees} Rupees is equal to {dollars:.2f} Dollars.")
Output:
6. Write a program to convert temperature Fahrenheit to Celcius.
Code:
def fahrenheit_to_celsius(fahrenheit):
celsius = (fahrenheit - 32) * 5 / 9
return celsius
fahrenheit = float(input("Enter temperature in Fahrenheit: "))
celsius = fahrenheit_to_celsius(fahrenheit)
print(f"{fahrenheit} Fahrenheit is equal to {celsius:.2f} Celsius.")
Output:
7. Write a program to check if number is positive or negative.
Code:
num = float(input("Enter a number: "))
print("Positive" if num > 0 else "Negative" if num < 0 else "Zero")
Output:
8. Write a program to check if number is even or odd.
Code:
num = int(input("Enter a number: "))
if num % 2 == 0:
print(f"{num} is Even.")
else:
print(f"{num} is Odd.")
Output:
9. Write a program to find the largest of two numbers.
Code:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
if num1 > num2:
print(f"The largest number is {num1}.")
elif num2 > num1:
print(f"The largest number is {num2}.")
else:
print("Both numbers are equal.")
Output:
10. Write a program to check if a character is vowel or a consonant
Code:
def check_vowel_or_consonant(char):
vowels = 'AEIOUaeiou'
if len(char) == 1 and char.isalpha():
if char in vowels:
print(f"{char} is a vowel.")
else:
print(f"{char} is a consonant.")
else:
print("Invalid input! Please enter a single alphabetic character.")
char = input("Enter a character: ")
check_vowel_or_consonant(char)
Output:
11. Write a program to find the largest of three numbers
Code:
a = float(input("Enter the first number: "))
b = float(input("Enter the second number: "))
c = float(input("Enter the third number: "))
largest = max(a, b, c)
print(f"The largest number is {largest}."
Output:
12. Write a program to determine whether a person is eligible for voting or not.
Code:
def check_voting_eligibility(age):
if age >= 18:
return "Eligible for voting."
else:
return "Not eligible for voting."
age = int(input("Enter your age: "))
print(check_voting_eligibility(age))
Output:
13. Write a program to determine the character entered by a user.
Code:
def check_character(character):
return f"The entered character is: {character}"
character = input("Enter a character: ")
print(check_character(character))
Output:
14. Write a program to check the entered year is leap year or not.
Code:
def is_leap_year(year):
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
return "Leap year."
else:
return "Not a leap year."
year = int(input("Enter a year: "))
print(is_leap_year(year))
Output:
15. Write a program to check the given character is uppercase, lowercase or a digit.
Code:
def check_case(character):
if character.isupper():
return "Uppercase letter."
elif character.islower():
return "Lowercase letter."
elif character.isdigit():
return "Digit."
else:
return "Not an uppercase letter, lowercase letter, or digit."
character = input("Enter a character: ")
print(check_case(character))
Output:
16. Write a program to accept the cost price of a bike and display the road tax
according to the following strategy:
Cost Price (in Rupees) Tax (in percent)
Cost>1 lakh 20
50k <= Cost < 1 lakh 15
25k <= Cost <50k 10
Cost< 25k 5
Code:
def calculate_road_tax(cost_price):
if cost_price >= 100000:
tax = 20
elif 50000 < cost_price < 100000:
tax = 15
elif 25000 < cost_price <= 50000:
tax = 10
else:
tax = 5
return f"Road tax is {tax}%."
cost_price = float(input("Enter the cost price of the bike (in Rupees): "))
print(calculate_road_tax(cost_price))
Output:
17. Write a program to accept the percentage from user and display grades
according to IIIT Criteria.
Code:
def display_grade(percentage):
if percentage >= 75:
return "Grade: A"
elif percentage >= 60:
return "Grade: B"
elif percentage >= 50:
return "Grade: C"
elif percentage >= 40:
return "Grade: D"
else:
return "Grade: F"
percentage = float(input("Enter the percentage: "))
print(display_grade(percentage))
Output:
18. Write a program to check whether the number entered is Palindrome or not.
Code:
def is_palindrome(number):
return "Palindrome." if str(number) == str(number)[::-1] else "Not a palindrome."
number = input("Enter a number: ")
print(is_palindrome(number))
Output:
19. Write a program to check whether the number entered is an Armstrong number
or not.
Code:
def is_armstrong_number(number):
num_str = str(number)
power = len(num_str)
total = sum(int(digit) ** power for digit in num_str)
return "Armstrong number." if total == number else "Not an Armstrong number."
number = int(input("Enter a number: "))
print(is_armstrong_number(number))
Output:
20. Write a program to find roots of a Quadratic Equation.
Code:
import cmath
def find_roots(a, b, c):
discriminant = b ** 2 - 4 * a * c
root1 = (-b + cmath.sqrt(discriminant)) / (2 * a)
root2 = (-b - cmath.sqrt(discriminant)) / (2 * a)
return f"Roots are: {root1} and {root2}"
a = float(input("Enter coefficient a: "))
b = float(input("Enter coefficient b: "))
c = float(input("Enter coefficient c: "))
print(find_roots(a, b, c))
Output:
21. Write a program to make comparison between three numbers. Write in Python
language
Code:
def compare_three_numbers(num1, num2, num3):
largest = max(num1, num2, num3)
return f"The largest number is: {largest}"
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
print(compare_three_numbers(num1, num2, num3))
Output:
22. Write a Python class called 'Bank Account' that has attributes: account number,
balance and methods: Deposit and Withdraw
Code:
class BankAccount:
def __init__(self, account_number, balance=0):
self.account_number = account_number
self.balance = balance
def deposit(self, amount):
if amount > 0:
self.balance += amount
print(f"Deposited: {amount}. New balance: {self.balance}.")
else:
print("Deposit amount must be positive.")
def withdraw(self, amount):
if amount > 0:
if amount <= self.balance:
self.balance -= amount
print(f"Withdrew: {amount}. New balance: {self.balance}.")
else:
print("Insufficient funds.")
else:
print("Withdrawal amount must be positive.")
# Example usage
account = BankAccount("123456789", 1000)
account.deposit(500) # Deposits 500
account.withdraw(300) # Withdraws 300
account.withdraw(1500) # Attempts to withdraw more than the balance
Output:
23. Write a Python program that takes a list of numbers and divides each number
by another number provided by the user. Handle possible Exceptions
Code:
def divide_numbers(numbers, divisor):
results = []
for number in numbers:
try:
result = number / divisor
results.append(result)
except ZeroDivisionError:
print(f"Cannot divide {number} by zero.")
results.append(None) # Append None or a custom message if division fails
except Exception as e:
print(f"An error occurred: {e}")
results.append(None)
return results
numbers_input = input("Enter a list of numbers separated by spaces: ")
numbers = list(map(float, numbers_input.split()))
while True:
try:
divisor = float(input("Enter a divisor: "))
break
except ValueError:
print("Please enter a valid number.")
results = divide_numbers(numbers, divisor)
for number, result in zip(numbers, results):
if result is not None:
print(f"{number} / {divisor} = {result}")
else:
print(f"Division for {number} could not be completed.")
Output:
24. Write a Python program to read a file and count the occurrence of each word in
the file.
Code:
def count_words_in_file(filename):
word_count = {}
try:
with open(filename, 'r') as file:
for line in file:
words = line.split()
for word in words:
word = word.lower() # Normalize to lowercase
word_count[word] = word_count.get(word, 0) + 1
except FileNotFoundError:
print(f"The file '{filename}' does not exist.")
return word_count
# Input: filename
filename = input("Enter the filename: ")
word_counts = count_words_in_file(filename)
# Display the word counts
for word, count in word_counts.items():
print(f"{word}: {count}")
25. Write a Python program to implement a stack using List and perform push, pop
and display operations.
Code:
c # Stack implementation using a list
stack = []
def push(item):
stack.append(item)
print(f"Pushed {item} onto the stack.")
def pop():
if stack:
item = stack.pop()
print(f"Popped {item} from the stack.")
else:
print("Stack is empty. Cannot pop.")
def display():
if stack:
print("Stack contents:", stack)
else:
print("Stack is empty.")
# Example usage
while True:
choice = input("\nEnter 'push', 'pop', 'display', or 'exit': ").strip().lower()
if choice == 'push':
item = input("Enter item to push: ")
push(item)
elif choice == 'pop':
pop()
elif choice == 'display':
display()
elif choice == 'exit':
print("Exiting...")
break
else:
print("Invalid choice. Please try again.")
Output:
26. Write a Python program to calculate factorial of a number using recursion
Code:
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
num = int(input("Enter a number to calculate its factorial: "))
result = factorial(num)
print(f"The factorial of {num} is {result}.")
Output: