0% found this document useful (0 votes)
5 views18 pages

Python Programs for Basic Operations

The document contains multiple programming exercises and solutions in Python, covering topics such as arithmetic operations, Armstrong numbers, Fibonacci series, list operations, file handling, MySQL database connectivity, stack operations, and unique vowel identification. Each program includes user input, logic for processing, and output statements. The solutions demonstrate various programming concepts and functionalities in Python.

Uploaded by

ashwinmassey5
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views18 pages

Python Programs for Basic Operations

The document contains multiple programming exercises and solutions in Python, covering topics such as arithmetic operations, Armstrong numbers, Fibonacci series, list operations, file handling, MySQL database connectivity, stack operations, and unique vowel identification. Each program includes user input, logic for processing, and output statements. The solutions demonstrate various programming concepts and functionalities in Python.

Uploaded by

ashwinmassey5
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Program 1: Program to enter two numbers and print the arithmetic operations like +,-,*, /,

// and %.

Solution:
#Program for Arithmetic Calculator result = 0

val1 = float(input("Enter the first value :"))


val2 = float(input("Enter the second value :"))
op = input("Enter any one of the operator (+,-,*,/,//,%"))
if op == "+":
result = val1 + val2
elif op == "-":
result = val1 - val2
elif op == "*":
result = val1 * val2
elif op == "/":
if val2 == 0:
print("Please enter a value other than 0")
else:
result = val1 / val2
elif op == "//":
result = val1 // val2
else:
result = val1 % val2
print("The result is :",result)
Program 2: Write a Program to check if the entered number is Armstrong or not.

Solution:

# Program to check if the entered number is Armstrong or not.


#An Armstrong number has sum of the cubes of its digits is equal to the number itself

no=int(input("Enter any number to check : "))


no1 = no sum = 0 while(no>0):
ans = no % 10;
no = int (no / 10) if sum == no1:
print("Armstrong Number")
else:
print("Not an Armstrong Number")

Program 3: Write a Program to enter the number of terms and to print the Fibonacci Series.
Solution: #fibonacci
I =int(input(“enter the limit:"))
x= 0
y=1
z=1
print("Fibonacci series \n")
print(x,y,end=" ")
while(z<= i):
print(z, end=" ") x = y
x=y
y=z
z=x
Program 4: Write a Program to show the outputs based on entered list.

Solution:

my_list = ['p','r','o','b','e']

# Output: p
print(my_list[0]) #
Output: o
print(my_list[2]) #
Output: e
print(my_list[4])

# Error! Only integer can be used for indexing


# my_list[4.0] # Nested List

n_list = ["Happy", [2,0,1,5]]

# Nested indexing # Output: a


print(n_list[0][1],n_list[0][2],n_list[0][3])

# Output: 5

print(n_list[1][3])
Program 5: Write a Program to enter the numbers in a list using split () and to use all the
functions related to list.

Solution:

#Program to enter the numbers in a list using split () and to use all the functions related to list.

# numbers = [int(n, 10) for n in input().split(",")]


# print (len(numbers))
memo=[]
for i in range (5): x=int(input("enter no. \n"))
[Link](i,x)
i+=1
print(memo) [Link](25)
print("Second List")
print(memo)
msg=input("Enter any string : ")
newlist=[] newlist[:0]=msg
l=len(newlist)
print(l)
Program 6: Write a Program to find factorial of entered number using user-defined module fact().

Solution:

#Using function import factfunc

x=int(input("Enter value for factorial : "))


ans=[Link](x)
print(ans)
Program 7: Write a Program to read data from data file and show Data File
Handling related functions utility in python.

Solution:

f=open("[Link]",'r')
print([Link])
f_contents=[Link]()
print(f_contents)
f_contents=[Link]()
print(f_contents)
f_contents=[Link]()
print(f_contents)
for line in f:
print(line, end='')
f_contents=[Link](50)
print(f_contents)
size_to_read=10
f_contents=[Link](size_to_read)
while len(f_contents)>0:
print(f_contents)
print([Link]())
f_contents=[Link](size_to_read)
Program 8: Write a Program to read data from data file in append mode and use writeLines
function utility in python.

Solution:

#Program to read data from data file in append mode


af=open("[Link]",'a')
lines_of_text = ("One line of text here”,\ “and another
line here”,\ “and yet another here”, “and so on and
so forth")
[Link]('\n' + lines_of_text)
[Link]()
Program 9: Write a Program to read data from data file in read mode and count the
particular word occurrences in given string, number of times in python.

Solution:

#Program to read data from data file in read mode and


#count the particular word occurrences in given string,
#number of times in python.

f=open("[Link]",'r')
read=[Link]()
[Link]() times=0

#the variable has been created to show the number of times the loop runs times2=0
#the variable has been created to show the number of times the loop runs
chk=input("Enter String to search : ")
count=0
for sentence in read:
line=[Link]() times+=1
for each in line:
line2=each times2+=1
if chk==line2
count+=1 print("The search String ", chk, "is present : ", count, "times")
print(times)
print(times2)
Program 10: Write a Program to read data from data file in read mode and append the
words starting with letter ‘T’ in a given file in python.

Solution:
#Program to read data from data file in read mode and
#append the words starting with letter ‘T’
#in a given file in python
f=open("[Link]",'r') read=[Link]()
[Link]()
id=[]
for ln in read:
[Link]("T"):
[Link](ln)
print(id)
Program 11: Write a Program to show MySQL database connectivity in python.

Solution:
import [Link]
con=[Link](host='localhost',user='root',password='',db='school')
stmt=[Link]()
query='select * from student;' [Link](query)
data=[Link]()
print(data)

Program 12: Write a Python program to implement all basic operations of a stack, such as
adding element (PUSH operation), removing element (POP operation) and displaying the stack
elements (Traversal operation) using lists.

Solution:
#Implementation of List as stack s=[]
c="y"
`while (c=="y"):
print ("1. PUSH")
print ("2. POP ")
print ("3. Display")
choice=int(input("Enter your choice: "))
if (choice==1):
a=input("Enter any number :")
[Link](a)
elif (choice==2):
if (s==[]):
print ("Stack Empty")
else:
print ("Deleted element is : ",[Link]())
elif (choice==3):
l=len(s)
for i in range(l-1,-1,-1): #To display elements from last element to first print (s[i])
else:
print("Wrong Input")
c=input("Do you want to continue or not? ")
Program 13: Write a program to display unique vowels present in the given word using Stack.

Solution:
#Program to display unique vowels present in the given word #using Stack
vowels =['a','e','i','o','u']
word = input("Enter the word to search for vowels :")
Stack for letter in word:
if letter in vowels:
if letter not in Stack:
[Link](letter)
print(Stack)
print("The number of different vowels present in",word,"is",len(Stack))

Program 14: Perform all the operations with reference to table ‘Employee’ through
MySQL-Python connectivity.
Solution:
import MySQLdb
# Using connect method to connect database
db1 = [Link]("localhost","root","","TESTDB" )
# using cursor() method for preparing cursor
cursor = [Link]()
# Preparing SQL statement to create EMP table
sql = "CREATE TABLE EMP(empno integer primary key,ename varchar(25) not null,salary
float);"
[Link](sql) n
# disconnect from server [Link]()
Inserting a record in ‘emp’
import MySQLdb
db1 = [Link]("localhost","root","","TESTDB" )
cursor = [Link]()
# Prepareing SQL statement to insert one record with the given values sql = "INSERT INTO
EMP VALUES (1,'ANIL KUMAR',86000);"
try:
[Link](sql)
[Link]()
except:
[Link]()
[Link]()
Fetching all the records from EMP table having salary more than 70000.

import MySQLdb
db1 = [Link]("localhost","root","","TESTDB" )
cursor = [Link]()
sql = "SELECT * FROM EMP WHERE SALARY > 70000;"
try:
[Link](sql)
#using fetchall() function to fetch all records from the table EMP and store in
resultset resultset = [Link]() for row in resultset:
print (row) except:
print ("Error: unable to fetch data")
[Link]()

Updating record(s) of the table using UPDATE

import MySQLdb
db1 = [Link]("localhost","root","","TESTDB" )
cursor = [Link]()
#Preparing SQL statement to increase salary of all employees whose salary is less than
80000 sql = "UPDATE EMP SET salary = salary +1000 WHERE salary<80000;"
try:
[Link](sql)
[Link]() except:
[Link]()
[Link]()
Deleting record(s) from table using DELETE

import MySQLdb
db1 = [Link]("localhost","root","","TESTDB" )
cursor = [Link]()
sal=int(input("Enter salary whose record to be deleted : "))
#Preparing SQL statement to delete records as per given condition sql = "DELETE FROM EMP WHERE
salary =sal”
try:
[Link](sql)
print([Link], end=" record(s) deleted ") [Link]()
except:
[Link]()
[Link]()

Output:

>>> Enter salary whose record to be deleted: 80000

1 record(s) deleted

>>>

You might also like