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

Python 2024

Uploaded by

bhoibazigar007
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Python 2024

Uploaded by

bhoibazigar007
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

1

1. Write a Python program to display 'Hello World" Message


on Screen.

➢ print("Hello")

Output :
2

2. Write a Python program to swap two variables.

a=5
b=7
c=a
a=b
b=c
print("value of a=",a)
print("value of b=",b)

Output :
3

3. Write a Python program to display the Fibonacci series.


# Program to display the Fibonacci sequence up to n-th term
nterms = int(input("How many terms? "))

# first two terms


n1, n2 = 0, 1
count = 0

print("Fibonacci sequence:")
while count < nterms: #0<5,1<5,2<5,3<5,4<5,5<5 so false
print(n1) #answer = 0,1,1,2,3
nth = n1 + n2 #0+1=1,1+1=2,1+2=3,2+3=5,3+5=8
# update values
n1 = n2 #n1=1,1,2,3,5
n2 = nth #n2=1,2,3,5,8
count = count + 1 #count=0+1=1,1+1=2,2+1=3,3+1=4,4+1=5
Output :
4

4. Write a Python program to calculate sum of given number.


#python program to calculate sum of given number

num1 = input('Enter first number: ')


num2 = input('Enter second number: ')
sum = int(num1) + int(num2)
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))

Output :
5

5. Write a Python Program to print first prime number.


lower_value=int(input("Please, Enter the Lowest Range Value: "))
upper_value=int(input("Please, Enter the Upper Range Value: "))

print("The Prime Numbers in the range are: ")


for number in range(lower_value, upper_value + 1):
if number > 1:
for i in range(2, number):
if (number % i) == 0:
break
else:
print(number)
Output :
6

6. Write a Python Program to Check Armstrong Number


num = int(input("Enter a number: "))
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum = sum + digit ** 4
temp = temp // 10
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")

Output :
7

7. Write a Python Program to Create a sequence of numbers using


range datatype to display 1 to 30, with an increment of 2.

#python program to create a sequence of numbers using range


datatype to display 1 to 30, with an increment of 2.
for i in range(1,20,2):
print(i)

Output :
8

8. Write a Python Program to Find area of circle.

#python program to find area of circle

PI = 3.14
r = float(input("enter radius : "))
area = PI*r*r
print("area of circle = ", area)

Output :
9

9. Write a Python program to implement Factorial series up to


user entered number.
num = int(input("Enter a number: "))
factorial = 1
if num < 0:
print(" Factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):#(1,5+1=6)
factorial = factorial*i #1*1=1,1*2=2,2*3=6,6*4=24,24*5=120
print("The factorial of",num,"is",factorial)

Output :
10

10. Write a Python program to check the given number is


palindrome or not.

n=int(input("Enter number:"))
temp=n
rev=0

while(n>0):
dig=n%10
rev=rev*10+dig
#print(rev)
n=n//10

if(temp==rev):
print("The number is a palindrome!")
else:
print("The number isn't a palindrome!")

Output :
11

11. Write a python program to display ascending and


descending order from given 10 numbers.
# List of integers
num = [100, 200, 500, 600, 300]
num.sort()
print("ascending=",num)
num.sort(reverse=True)
print("descending=",num)

# List of float numbers


fnum = [100.43, 50.72, 90.65, 16.00, 04.41]
fnum.sort()
print("\nascending=",fnum)
fnum.sort(reverse=True)
print("descending=",fnum)

# List of strings
str = ["Test", "My", "Word", "Tag", "Has"]
str.sort()
print("\nascending=",str)
str.sort(reverse=True)
print("descending=",str)

Output :
12

12. Write a Python program to print the duplicate elements of


an array

from array import *


arr = array('i', [])
n = int(input("enter number of elements for array : "))
for i in range(n):
arr.append(int(input("enter the array elements : ")))

print("entered array is :")


for i in range(len(arr)):
print(arr[i])

print("Duplicate elements in given array : ")


for i in range(0, len(arr)):
for j in range(i+1, len(arr)):
if(arr[i] == arr[j]):
print(arr[j])
Output :
13

13. Write Python programs to create functions and use


functions in the program.

# function with two arguments


def add_numbers(num1, num2):
sum = num1 + num2
#print("Sum: ",sum)
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))

# function call with two values


add_numbers(5, 4)

Output :
14

14. Write Python programs to using lambda function.


a = lambda x, y: x + y

x = int(input("Enter first number : "))


y = int(input("Enter second number : "))

result = a(x, y)
#print("Sum is:", result)
print('The sum of {0} and {1} is : {2}'.format(x, y, result))

Output :
15

15. Write Python programs Loading the module in Python


code. [15a]
class Car:
brand_name = "Hyundai"
model = "Creta SX(O) 1.5"
manu_year = "2020"

def __init__(self, brand_name, model, manu_year):


self.brand_name = brand_name
self.model = model
self.manu_year = manu_year

def car_details(self):
print("Car brand is ", self.brand_name)
print("Car model is ", self.model)
print("Car manufacture year is ", self.manu_year)

def get_Car_brand(self):
print("Car brand is ", self.brand_name)

def get_Car_model(self):
print("Car model is ", self.model)
[15b]
from p15a import Car
car_det = Car("Hyundai", ' Creta SX(O) 1.5', 2020)
print(car_det.brand_name)
print(car_det.car_details())
print(car_det.get_Car_brand())
print(car_det.get_Car_model())

Output :
16

16. Write a program to print following pattern


1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

n = int(input("Enter number of rows: "))


for i in range(1,n+1):
for j in range(1, i+1):
print(j, end="")
print()

Output :
17

17. Write Python programs to implement a concept of list.


odd = [2, 4, 6, 8]

#change the 1st item


odd[0] = 1
print(odd) #Output : [1, 4, 6, 8]

#change 2nd to 4th items


odd[1:4] = [3, 5, 7]
print(odd) #Output : [1, 3, 5, 7]

#append item
odd.append(10)
print(odd) #Output : [1, 3, 5, 7, 10]

#extend item
odd.extend([9, 11, 13])
print(odd) #Output : [1, 3, 5, 7, 10, 9, 11, 13]

#delete one item


del odd[2]
print(odd) #Output : [1, 3, 7, 10, 9, 11, 13]

#adding of 2 lists
print(odd + [9, 7, 5]) #Output : [1, 3, 7, 10, 9, 11, 13, 9, 7, 5]

#Sum of the element in the list


list1 = [3,40,25,91,10,12,25]
sum = 0
for i in list1:
sum = sum+i #0+3=3, 3+40=43, 43+25=68, 68+91=159, 159+10=169,
169+12=181, 181+25=206
print("The sum is:",sum)

Output :
18

18. Write Python programs to implement a concept of tuples.


#Sum of the element in the list
list1 = (3,40,25,91,10,12,25)
sum = 0
for i in list1:
sum = sum+i #0+3=3, 3+40=43, 43+25=68, 68+91=159, 159+10=169,
169+12=181, 181+25=206
print("The sum is:",sum)

Output :
19

19. Write a Python program to create nested list and display


its elements.
num = [1, 2, [3, 4, [5, 6]], 7, 8]

print(num[2]) # Prints [3, 4, [5, 6]]

print(num[2][2]) # Prints [5, 6]

print(num[2][2][0]) # Prints 5

Output :
20

20. Write a Python program to using multiple inheritance.


# Parent class 1
class Person:
def person_info(self, name, age):
print('--------------------------------')
print('Inside Person class')
print('Name:', name, 'Age:', age)
print('--------------------------------')
# Parent class 2
class Company:
def company_info(self, company_name, location):
print('--------------------------------')
print('Inside Company class')
print('Name:', company_name, 'location:', location)
print('--------------------------------')
# Child class
class Employee(Person, Company):
def Employee_info(self, salary, skill):
print('--------------------------------')
print('Inside Employee class')
print('Salary:', salary, 'Skill:', skill)
print('--------------------------------')
# Create object of Employee
emp = Employee()
# access data
emp.person_info('Daksh', 3)
emp.company_info('Google', 'Atlanta')
emp.Employee_info(12000, 'Machine Learning

Output :
21

21. Write a Python program to read a file bca.txt and print the
contents of file along with number of vowels present in it.
file1 = open("bca21.txt", "r")
str1 = file1.read()

vowel_count = 0

for i in str1:
if (i == 'A' or i == 'a' or i == 'E' or i == 'e' or i == 'I'or i
== 'i' or i == 'O' or i == 'o'or i == 'U' or i == 'u'):
vowel_count =vowel_count + 1
print("\n" + str1 + "\n")
print('The Number of Vowels in text file :', vowel_count)
file1.close()

Output :
22

22. Write a Python program for Error Handling.


try:
num1 = float(input("Enter first number : "))
num2 = float(input("Enter second number : "))
result = num1/num2
print(result)

except:
print("Error: number2 cannot be 0.")

finally:
print("This is finally block.")

Output :
23

23. Write a Python program for connection with my Sql and


display all record from the database.
OR

24. Write a Python program for modified record, display


record and delete record from the database.
OR

25. Write a Python program for search record from the


database.

Create Database
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password=""
)
mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE crudoperation")

Create Table
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="crudoperation"
)
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE students (std_ID INT, FirstName
VARCHAR(255), LastName VARCHAR(255),Contact VARCHAR(255))")
24

Insert Data

import mysql.connector

# Establish a connection to the MySQL server


mydb = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="crudoperation"
)

# Create a cursor object to interact with the database


mycursor = mydb.cursor()

# Display the current data in the table


mycursor.execute("SELECT * FROM students")
result_before_insert = mycursor.fetchall()

print("List of Students before insertion:")


for row in result_before_insert:
print(row)

# Get new values from the user


new_first_name = input("Enter the new first name: ")
new_last_name = input("Enter the new last name: ")
new_age = input("Enter the new age: ")

# Insert new data into the table


sql_insert = "INSERT INTO students (FirstName, LastName, Age) VALUES
(%s, %s, %s)"
values_insert = (new_first_name, new_last_name, int(new_age))

mycursor.execute(sql_insert, values_insert)
mydb.commit()

print("\nData inserted successfully.")

# Display the updated data in the table


mycursor.execute("SELECT * FROM students")
result_after_insert = mycursor.fetchall()

print("\nUpdated List of Students:")


for row in result_after_insert:
print(row)

# Close the cursor and connection


mycursor.close()
mydb.close()
25

Output :
26

Update Data
import mysql.connector

# Establish a connection to the MySQL server


mydb = mysql.connector.connect(
host = "localhost" ,
user = "root" ,
password = "" ,
database = "crudoperation"
)

# Create a cursor object to interact with the database


mycursor = mydb.cursor()

# Display the current data in the table


mycursor.execute("SELECT * FROM students")
result_select = mycursor.fetchall()
print("\nList of Students:")
for row in result_select:
print(row)

# Ask for confirmation to update


confirmation = input("\nDo you want to update a student record?
(yes/no): ").lower()
if confirmation != 'yes':
print("Exiting without updating.")
exit()

# Update data in the table


student_id_to_update = input("Enter the student ID to update: ")
new_first_name = input("Enter the new first name (press Enter to
keep it unchanged): ")
new_last_name = input("Enter the new last name (press Enter to keep
it unchanged): ")
new_age = input("Enter the new age (press Enter to keep it
unchanged): ")

# Build the SQL query dynamically based on user input


sql_update = "UPDATE students SET"
update_values = []

if new_first_name:
sql_update += " FirstName = %s,"
update_values.append(new_first_name)
if new_last_name:
sql_update += " LastName = %s,"
update_values.append(new_last_name)
if new_age:
sql_update += " Age = %s,"
update_values.append(new_age)

# Check if any fields are provided for update


if not update_values:
print("No fields to update. Exiting...")
exit()

# Remove the trailing comma and add the WHERE clause


sql_update = sql_update.rstrip(",") + " WHERE std_ID = %s"
update_values.append(student_id_to_update)
27

# Execute the update query


mycursor.execute(sql_update, tuple(update_values))
mydb.commit()

if mycursor.rowcount > 0:
print(f"{mycursor.rowcount} record(s) updated successfully.")
mycursor.execute ("SELECT * FROM students")
result_select = mycursor.fetchall ()
print ("\nUpdated List of Students:")
for row in result_select :
print (row)
else:
print(f"No records updated. Student ID {student_id_to_update}
not found.")

# Close the cursor and connection


mycursor.close()
mydb.close()

Output :
28

Delete Data
import mysql.connector

# Establish a connection to the MySQL server


mydb = mysql.connector.connect(
host = "localhost" ,
user = "root" ,
password = "" ,
database = "crudoperation"
)

# Create a cursor object to interact with the database


mycursor = mydb.cursor()

# Display the current data in the table


mycursor.execute("SELECT * FROM students")
result_select_before_delete = mycursor.fetchall()
print("\nList of Students before deletion:")
for row in result_select_before_delete:
print(row)

# Ask for confirmation to delete


confirmation = input("\nDo you want to delete a student record?
(yes/no): ").lower()
if confirmation != 'yes':
print("Exiting without deleting.")
exit()

# Delete data from the table


student_id_to_delete = input("Enter the student ID to delete: ")
sql_delete = "DELETE FROM students WHERE std_ID = %s"
values_delete = (student_id_to_delete,)

mycursor.execute(sql_delete, values_delete)
mydb.commit()

if mycursor.rowcount > 0:
print(f"{mycursor.rowcount} record(s) deleted successfully.")
# Display the updated data in the table
mycursor.execute("SELECT * FROM students")
result_select_after_delete = mycursor.fetchall()
print("\nUpdated List of Students:")
for row in result_select_after_delete:
print(row)
else:
print(f"No records deleted. Student ID {student_id_to_delete}
not found.")

# Close the cursor and connection


mycursor.close()
mydb.close()
29

Output :
30

Search Data
import mysql.connector

# Establish a connection to the MySQL server


mydb = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="crudoperation"
)

# Create a cursor object to interact with the database


mycursor = mydb.cursor()

# Specify the value you want to search for


std_id_to_search = input("Enter the student ID to search : ") #
Replace 123 with the actual std_ID you want to search for

# Display the data for a particular row where std_ID matches the
specified value
mycursor.execute("SELECT * FROM students WHERE std_ID = %s",
(std_id_to_search,))
result_select = mycursor.fetchall()

# Print the result


print("\nList of Students:")
for row in result_select:
print(row)

# Close the cursor and connection


mycursor.close()
mydb.close()

Output :

You might also like