0% found this document useful (0 votes)
3 views

Python Program 1 to 13 (1)

The document contains a series of Python programming exercises covering various topics such as temperature conversion, variable swapping, number conversions, simple calculators, and string manipulations. It also includes file handling, data processing with CSV and JSON, and web applications using Flask for tasks like address book management and event registration. Each exercise is presented with code snippets and expected outputs.

Uploaded by

dsss919138
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)
3 views

Python Program 1 to 13 (1)

The document contains a series of Python programming exercises covering various topics such as temperature conversion, variable swapping, number conversions, simple calculators, and string manipulations. It also includes file handling, data processing with CSV and JSON, and web applications using Flask for tasks like address book management and event registration. Each exercise is presented with code snippets and expected outputs.

Uploaded by

dsss919138
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
You are on page 1/ 13

1) Write a Python Program to Convert Celsius to Fahrenheit and vice –a-versa.

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.

a = int(input("Enter first variable (a): "))


b = int(input("Enter second variable (b): "))

print(f"\nBefore swapping: a = {a}, b = {b}")


a, b = b, a

print(f"After swapping: a = {a}, b = {b}")

Output : -

pg. 1
3) Write a Python Program to Convert Decimal to Binary, Octal and Hexadecimal

decimal = int(input("Enter a decimal number: "))

binary = bin(decimal)[2:]
octal = oct(decimal)[2:]
hexadecimal = hex(decimal)[2:].upper()

print(f"Binary: {binary}, Octal: {octal}, Hexadecimal: {hexadecimal}")

Output : -

4) Write a program to make a simple calculator (using functions).

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.

num1 = float(input("Enter first number: "))


num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))

maximum = max(num1, num2, num3)


minimum = min(num1, num2, num3)

print(f"\nMaximum number: {maximum}")


print(f"Minimum number: {minimum}")

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.

num = int(input("Enter a number: "))


order = len(str(num))
sum_of_powers = 0
temp = num

while temp > 0:


digit = temp % 10
sum_of_powers += digit ** order
temp //= 10

if sum_of_powers == num:
print(f"{num} is an Armstrong number.")
else:
print(f"{num} is not an Armstrong number.")

Output : -

8) Write a Python program to check if the number provided by the user is a


palindrome or not.

num = input("Enter a number: ")

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.

s = input("Enter a string: ")

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]

find_str = input("Enter string to find: ")


replace_str = input("Enter string to replace with: ")
replaced_string = s.replace(find_str, replace_str)

is_palindrome = s == s[::-1]

print(f"\nNumber of vowels: {vowel_count}")


print(f"Length of string: {length}")
print(f"Reversed string: {reversed_string}")
print(f"Replaced string: {replaced_string}")
print(f"Is palindrome: {is_palindrome}")

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 : -

11) Write a program in python to implement Fibonacci series up to user entered


number. (Use recursive Function)

def fibonacci(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)

num = int(input("Enter a number: "))

pg. 6
print("\nFibonacci series:")
for i in range(num):
print(fibonacci(i), end=' ')

Output : -

12) Write a program in python to implement Factorial series up to user entered


number. (Use recursive Function)

def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)

num = int(input("Enter a number: "))

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.

with open('example.txt', 'w') as f:


f.write("Hello, World!\n")
f.writelines(["This is line 1.\n", "This is line 2.\n"])

with open('example.txt', 'r') as f:

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

# Sample file content:


# 101,Alice,1,1000,500,300,100
# 102,Bob,1,1200,600,350,120

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 : -

16) Write a Python program to implement module.

# 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

# Sample CSV content:


# 1,Alice
# 2,Bob

with open("sample.csv", mode="r") as f:


reader = csv.reader(f)
rows = list(reader)

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 : -

19) Write a program to process CSV file using CSV module.

import csv

# Sample CSV content:


#name,age
# Alice,21
# Bob,25

with open("sample.csv", mode="r") as f:


reader = csv.DictReader(f)
for row in reader:
print(row)

Output : -

pg. 10
20) Desirable: Write a program to process JSON and XML data.

import json, xml.etree.ElementTree as ET

json_data = '{"name": "Alice", "age": 25}'


parsed = json.loads(json_data)
print(parsed['name'])

xml_data = "<person><name>Alice</name><age>25</age></person>"
root = ET.fromstring(xml_data)
print(root.find('name').text)

Output : -

21) Create Web Database Application “Address Book” with options to


a) add/ insert a record
b) modify a record
c) display a record
d) delete a record

from flask import Flask, request, render_template, redirect, url_for

app = Flask(__name__)
address_book = {}

@app.route('/add', methods=['GET', 'POST'])


def add_record():
if request.method == 'POST':
name = request.form['name']
phone = request.form['phone']
address_book[name] = phone
return redirect(url_for('display'))
return render_template('add.html')

@app.route('/display')
def display():
return render_template('display.html', address_book=address_book)

if __name__ == '__main__':
app.run()

Output : -

Note : How to run :

 First Run program file and shows its running


 Go to: http://127.0.0.1:5000/add
 Fill Name and Phone → Click Add.
 It will automatically redirect to /display to show all records!

pg. 11
22) Create Web Database Application “Event Registration” with options to
a) Event Registration
b) Cancel Registration
c) display a record

from flask import Flask, request, render_template

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 : -

Note : How to run :

 First Run program file and shows its running


 Go to: http://127.0.0.1:5000/
 Fill Form

pg. 12
Registration successful for Divyesh for Python

pg. 13

You might also like