Python Program 1 to 13 (1)
Python Program 1 to 13 (1)
choice = input("Enter 'C' for Celsius to Fahrenheit or 'F' for Fahrenheit to Celsius: ").upper()
if choice == 'C':
celsius = float(input("\nEnter temperature in Celsius: "))
fahrenheit = (celsius * 9/5) + 32
print(f"{celsius} Celsius is {fahrenheit} Fahrenheit.")
elif choice == 'F':
fahrenheit = float(input("\nEnter temperature in Fahrenheit: "))
celsius = (fahrenheit - 32) * 5/9
print(f"{fahrenheit} Fahrenheit is {celsius} Celsius.")
else:
print("Invalid choice.")
Output : -
2) Write a program in python to swap two variables without using temporary variable.
Output : -
pg. 1
3) Write a Python Program to Convert Decimal to Binary, Octal and Hexadecimal
binary = bin(decimal)[2:]
octal = oct(decimal)[2:]
hexadecimal = hex(decimal)[2:].upper()
Output : -
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
choice = input("Enter choice (1/2/3/4): ")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print(f"{num1} + {num2} = {num1 + num2}")
elif choice == '2':
print(f"{num1} - {num2} = {num1 - num2}")
elif choice == '3':
print(f"{num1} * {num2} = {num1 * num2}")
elif choice == '4':
print(f"{num1} / {num2} = {num1 / num2}")
else:
print("Invalid input")
Output : -
pg. 2
5) Write a program in python to find out maximum and minimum number out of three
user entered number.
Output : -
6) Write a program which will allow user to enter 10 numbers and display largest odd
number from them. It will display appropriate message in case if no odd number is
found.
numbers = []
for i in range(10):
num = int(input(f"Enter number {i+1}: "))
numbers.append(num)
odd_numbers = []
for num in numbers:
if num % 2 != 0:
odd_numbers.append(num)
if odd_numbers:
print(f"Largest odd number: {max(odd_numbers)}")
else:
print("No odd number found.")
Output : -
pg. 3
7) Write a Python program to check if the number provided by the user is an
Armstrong number.
if sum_of_powers == num:
print(f"{num} is an Armstrong number.")
else:
print(f"{num} is not an Armstrong number.")
Output : -
if num == num[::-1]:
print(f"{num} is a palindrome.")
else:
print(f"{num} is not a palindrome.")
Output : -
pg. 4
9) Write a Python program to perform following operation on given string input:
a) Count Number of Vowel in given string
b) Count Length of string (do not use Len ())
c) Reverse string
d) Find and replace operation
e) check whether string entered is a palindrome or not.
vowel_count = 0
for char in s:
if char in 'aeiouAEIOU':
vowel_count += 1
length = 0
for _ in s:
length += 1
reversed_string = s[::-1]
is_palindrome = s == s[::-1]
Output : -
pg. 5
10) Define a procedure histogram () that takes a list of integers and prints a histogram
to the screen. For example, histogram ([4, 9, 7]) should print the following:
****
*********
*******
def histogram(numbers):
for num in numbers:
print('*' * num)
histogram([4, 9, 7])
Output : -
def fibonacci(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
pg. 6
print("\nFibonacci series:")
for i in range(num):
print(fibonacci(i), end=' ')
Output : -
def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)
print("\nFactorial series:")
for i in range(num + 1):
print(f"{i}! = {factorial(i)}")
Output : -
13) Write a program in Python to implement readline, readlines, write line and
writelines file handling mechanisms.
pg. 7
print("Read line:", f.readline())
print("Read lines:", f.readlines())
Output : -
14) Write a program in python to implement Salary printing file read operation.
(Fileformat: Employee No, name, deptno, basic, DA, HRA, Conveyance) should
perform below operations.
a) Print Salary Slip for given Employee Number
b) Print Employee List for Given Department Number
def print_salary_slip(employee_no):
with open("employee_data.txt", "r") as f:
for line in f:
details = line.strip().split(',')
if details[0] == str(employee_no):
print(f"Salary Slip for {details[1]}:")
total_salary = float(details[3]) + float(details[4]) + float(details[5]) + float(details[6])
print(f"Total Salary = {total_salary}")
return
print("Employee not found")
print_salary_slip(102)
Output : -
15) Write a program in python to implement Railway Reservation System using file
handling technique. System should perform below operations.
a)Reserve a ticket for a passenger.
b) List information all reservations done for today’s trains.
pg. 8
# Simple mock of a Railway Reservation System
reservations = []
def reserve_ticket(name, train_no, seat_no):
reservations.append((name, train_no, seat_no))
print("Ticket Reserved.")
def show_reservations():
print("Reservations for today:")
for res in reservations:
print(f"Name: {res[0]}, Train No: {res[1]}, Seat No: {res[2]}")
reserve_ticket("Alice", 12, 15)
show_reservations()
Output : -
# module.py :
def greet(name):
return f"Hello, {name}!"
# main.py :
import Program_16_module
print(Program_16_module.greet("Divyesh"))
Output : -
17) Write a program which will implement decorators for functions and methods in
python.
def decorator(func):
def wrapper():
print("Before function")
func()
print("After function")
return wrapper
@decorator
def say_hello():
print("Hello!")
say_hello()
Output : -
pg. 9
18) Write a program to read CSV file and generate output using HTML table.
import csv
html_output = "<table>"
for row in rows:
html_output += f"<tr><td>{row[0]}</td><td>{row[1]}</td></tr>"
html_output += "</table>"
print(html_output)
Output : -
import csv
Output : -
pg. 10
20) Desirable: Write a program to process JSON and XML data.
xml_data = "<person><name>Alice</name><age>25</age></person>"
root = ET.fromstring(xml_data)
print(root.find('name').text)
Output : -
app = Flask(__name__)
address_book = {}
@app.route('/display')
def display():
return render_template('display.html', address_book=address_book)
if __name__ == '__main__':
app.run()
Output : -
pg. 11
22) Create Web Database Application “Event Registration” with options to
a) Event Registration
b) Cancel Registration
c) display a record
app = Flask(__name__)
registrations = {}
@app.route('/')
def home():
return render_template('register.html')
@app.route('/register', methods=['POST'])
def register():
event = request.form['event']
participant = request.form['participant']
registrations[participant] = event
print(f"Registration successful for {participant} for {event}")
return f"Registration successful for {participant} for {event}"
if __name__ == '__main__':
app.run(debug=True)
Output : -
pg. 12
Registration successful for Divyesh for Python
pg. 13