You are on page 1of 28

z\1.

PROGRAMS USING DATA TYPES, OPERATORS AND EXPRESSION

(a) Convert Celsius to Fahrenheit


# Python Program to convert temperature in celsius to fahrenheit
# change this value for a different result

celsius = 37.5

# calculate fahrenheit

fahrenheit = (celsius * 1.8) + 32

print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %(celsius,fahrenheit))

OUTPUT:

37.5 degree Celsius is equal to 99.5 degree Fahrenheit

(b)Area of a circle:
Radius=int(input("enter the value R"))
circle=3.14*radius*radius print("Area of
circle", circle)

OUTPUT:
C) Simple Interest for the given principal amount
PROGRAM:
P=int(input("enter the value P"))
N=int(input("enter the value N"))
R=int(input("enter the value R"))
SI=P*N*R/100 print("Simple Interest is", SI)

OUTPUT:
2. PROGRAMS USING CONDITIONAL STATEMENTS

(a) Find grade and average marks of a student

print("Enter 'x' for exit.");


print("Enter marks obtained in 5 subjects: ");
mark1 = input();
if mark1 == 'x':
exit();
else:
mark1 = int(mark1);
mark2 = int(input());
mark3 = int(input());
mark4 = int(input());
mark5 = int(input());
sum = mark1 + mark2 + mark3 + mark4 + mark5;
average = sum/5;
if(average>=91 and average<=100):
print("Your Grade is A+");
elif(average>=81 and average<=90):
print("Your Grade is A");
elif(average>=71 and average<=80):
print("Your Grade is B+");
elif(average>=61 and average<=70):
print("Your Grade is B");
elif(average>=51 and average<=60):
print("Your Grade is C+");
elif(average>=41 and average<=50):
print("Your Grade is C");
elif(average>=0 and average<=40):
print("Your Grade is F");
else:
print("Strange Grade..!!");

OUTPUT:
Enter 'x' for exit.
Enter marks obtained in 5 subjects:
67
68
69
54
74
Your Grade is B
b) Greatest of three numbers.
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
 
if (num1 > num2) and (num1 > num3):
largest = num1
elif (num2 > num1) and (num2 > num3):
largest = num2
else:
largest = num3
 
print("The largest number is",largest)

OUTPUT:

Enter first number: 10


Enter second number: 12
Enter third number: 14
The largest number is 14.0

Enter first number: -1


Enter second number: 0
Enter third number: -3
The largest number is 0.0

c) Solve Quadratic Equation


# Solve the quadratic equation ax**2 + bx + c = 0
# import complex math module
import cmath
a=1
b=5
c=6
# To take coefficient input from the users
# a = float(input('Enter a: '))
# b = float(input('Enter b: '))
# c = float(input('Enter c: '))
# calculate the discriminant
d = (b**2) - (4*a*c)
# find two solutions
sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)
print('The solution are {0} and {1}'.format(sol1,sol2))

Output:
The solution are (-3+0j) and (-2+0j)
3. PROGRAMS USING CONTROL STATEMENTS

a) Find sum of N numbers

# Python program to find the sum of natural numbers up to n where n is provided by


user

# change this value for a different result


num = 16

# uncomment to take input from the user


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

if num < 0:
print("Enter a positive number")
else:
sum = 0
# use while loop to iterate un till zero
while(num > 0):
sum += num
num -= 1
print("The sum is",sum)

OUTPUT:

The sum is 136

b) Factorial of given number

n=int(input("Enter number:"))
fact=1
while(n>0):
fact=fact*n
n=n-1
print("Factorial of the number is: ")
print(fact)

OUTPUT:

Case 1:
Enter number:5
Factorial of the number is:
120

Case 2:
Enter number:4
Factorial of the number is:
24

C) Implement a multiplication table

num = 12

# To take input from the user


# num = int(input("Display multiplication table of? "))

# use for loop to iterate 10 times


for i in range(1, 11):
print(num,'x',i,'=',num*i)

OUTPUT:

12 x 1 = 12
12 x 2 = 24
12 x 3 = 36
12 x 4 = 48
12 x 5 = 60
12 x 6 = 72
12 x 7 = 84
12 x 8 = 96
12 x 9 = 108
12 x 10 = 120

D) Find Fibonacci series of a given number


a=int(input("Enter the first number of the series "))
b=int(input("Enter the second number of the series "))
n=int(input("Enter the number of terms needed "))
print(a,b,end=" ")
while(n-2):
c=a+b
a=b
b=c
print(c,end=" ")
n=n-1

OUTPUT:

Case 1:
Enter the first number of the series 0
Enter the second number of the series 1
Enter the number of terms needed 4
0112
Case 2:
Enter the first number of the series 2
Enter the second number of the series 4
Enter the number of terms needed 5
2 4 6 10 16

4. PROGRAMS USING FUNCTIONS

a)Implement a simple calculator


def add(x, y):
return x + y
# This function subtracts two numbers
def subtract(x, y):
return x - y
# This function multiplies two numbers
def multiply(x, y):
return x * y
# This function divides two numbers
def divide(x, y):
return x / y
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
# Take input from the user
choice = input("Enter choice(1/2/3/4):")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")

OUTPUT:
Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice(1/2/3/4): 3
Enter first number: 15
Enter second number: 14
15 * 14 = 210

b) Find odd or even number


num=int(input("Enter a number for check odd or even: "))
def find_Evenodd(num):

if(num%2==0):
print(num," Is an even")
else:
print(num," is an odd")
find_Evenodd(num);//function call

OUTPUT;
Enter a number for check odd or even: 349
349 is an odd

Enter a number for check odd or even: 234


234 is an even

c) Find factorial of given number using recursion

def recur_factorial(n):

"""Function to return the factorial


of a number using recursion"""

if n == 1:
return n
else:
return n*recur_factorial(n-1)

# Change this value for a different result

num = 7

# check is the number is negative


if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of",num,"is",recur_factorial(num))

OUTPUT:
The factorial of 7 is 5040

d) Find Fibonacci series of a given number using recursion


def recur_fibo(n):
"""Recursive function to
print Fibonacci sequence"""
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))

# Change this value for a different result


nterms = 10

# uncomment to take input from the user


#nterms = int(input("How many terms? "))

# check if the number of terms is valid


if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(recur_fibo(i))

OUTPUT:
Fibonacci sequence:
0
1
1
2
3
5
8
13
21
34
5. PROGRAMS USING STRINGS

a) Check whether a given string is Palindrome

string=input("Enter string:")
if(string==string[::-1]):
print("The string is a palindrome")
else:
print("The string isn't a palindrome")

OUTPUT:
Case 1:
Enter string :malayalam
The string is a palindrome

Case 2:
Enter string: hello
The string isn't a palindrome

b) Check whether a given string is Anagram

s1=input("Enter first string:")


s2=input("Enter second string:")

if(sorted(s1)==sorted(s2)):
print("The strings are anagrams.")
else:
print("The strings aren't anagrams.")

OUTPUT:

Case 1:

Enter first string: anagram


Enter second string: nagaram

The strings are anagrams.

Case 2:

Enter first string:hello


Enter second string:world

The strings aren't anagrams.

c) Count number of words and characters in a given string


string=raw_input("Enter string:")
char=0
word=1
for i in string:
char=char+1
if(i==' '):
word=word+1
print("Number of words in the string:")
print(word)
print("Number of characters in the string:")
print(char)

OUTPUT:
Case 1:
Enter string:Hello world
Number of words in the string:
2
Number of characters in the string:
11

Case 2:
Enter string:I love python
Number of words in the string:
3
Number of characters in the string:
13

d) Sort alphabetically the words form a string provided by the user

my_str = "Hello this Is an Example With cased letters"

# uncomment to take input from the user


#my_str = input("Enter a string: ")

# breakdown the string into a list of words


words = my_str.split()

# sort the list


words.sort()

# display the sorted words

print("The sorted words are:")


for word in words:
print(word)

OUTPUT:
The sorted words are:
Example
Hello
Is
With
an
cased
letters
this

e) Count number of vowels in a given string

string=raw_input("Enter string:")
vowels=0

for i in string:
if(i=='a' or i=='e' or i=='i' or i=='o' or i=='u' or i=='A' or i=='E' or i=='I' or i=='O' or
i=='U'):
vowels=vowels+1

print("Number of vowels are:")


print(vowels)

OUTPUT:
Case 1:
Enter string:Hello world
Number of vowels are:
3

Case 2:
Enter string:WELCOME
Number of vowels are:
3
6. PROGRAMS USING LIST

a) To find a maximum element in a list without using built in function

def minimum(a, n):

# inbuilt function to find the position of minimum


minpos = a.index(min(a))

# inbuilt function to find the position of maximum


maxpos = a.index(max(a))

# printing the position


print "The maximum is at position", maxpos + 1
print "The minimum is at position", minpos + 1

# driver code
a = [3, 4, 1, 3, 4, 5]
minimum(a, len(a))

OUTPUT:

The maximum is at position 6


The minimum is at position 3

b) Merge two lists and sort it.


a=[]
c=[]

n1=int(input("Enter number of elements:"))

for i in range(1,n1+1):
b=int(input("Enter element:"))
a.append(b)

n2=int(input("Enter number of elements:"))

for i in range(1,n2+1):
d=int(input("Enter element:"))
c.append(d)

new=a+c

new.sort()

print("Sorted list is:",new)

OUTPUT:
Case 1:
Enter number of elements:4
Enter element:56
Enter element:43
Enter element:78
Enter element:12
('Second largest number is:', 56)

Case 2:
Enter the number of elements in list 1 : 0

Enter the number of elements in list 2 : 3

Enter element 1 : 12

Enter element 2 : 12

Enter element 3 : 12

The union is :

[12]

b)Sort a list according to the length of the elements

a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=input("Enter element:")
a.append(b)
a.sort(key=len)
print(a)

OUTPUT:
Case 1:
Enter number of elements:4
Enter element:"Apple"
Enter element:"Ball"
Enter element:"Cat"
Enter element:"Dog"
['Cat', 'Dog', 'Ball', 'Apple']

Case 2:
Enter number of elements:4
Enter element:"White"
Enter element:"Red"
Enter element:"Purple"
Enter element:"Orange"
['Red', 'White', 'Purple', 'Orange']
c) Perform linear search in a given list

def search(list,n):

for i in range(len(list)):
if list[i] == n:
return True
return False

# list which contains both string and numbers.


list = [1, 2, 'sachin', 4,'Geeks', 6]

# Driver Code
n = 'Geeks'

if search(list, n):
print("Found")
else:
print("Not Found")

OUTPUT:

Found

d) Print Prime numbers in a given list

lower = 900
upper = 1000

# uncomment the following lines to take input from the user


#lower = int(input("Enter lower range: "))
#upper = int(input("Enter upper range: "))

print("Prime numbers between",lower,"and",upper,"are:")

for num in range(lower,upper + 1):


# prime numbers are greater than 1
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)

OUTPUT:

Prime numbers between 900 and 1000 are:


907
911
919
929
937
941
947
953
967
971
977
983
991
997

7. PROGRAMS USING DICTIONARIES

a) Concatenate two dictionaries

d1={'A':1,'B':2}
d2={'C':3}

d1.update(d2)

print("Concatenated dictionary is:")


print(d1)

OUTPUT:

Case 1:

Concatenated dictionary is:


{'A': 1, 'C': 3, 'B': 2}

b) Search a key element from a dictionary

d={'A':1,'B':2,'C':3}

key=raw_input("Enter key to check:")

if key in d.keys():
print("Key is present and value of the key is:")
print(d[key])
else:
print("Key isn't present!")

OUTPUT:
Case 1:

Enter key to check:A

Key is present and value of the key is:


1

Case 2:

Enter key to check:F


Key isn't present!

c) Print product of all elements.

d={'A':10,'B':10,'C':239}

tot=1

for i in d:
tot=tot*d[i]

print(tot)

OUTPUT:

Case 1:
23900

d) Delete a key from dictionary.

d = {'a':1,'b':2,'c':3,'d':4}
print("Initial dictionary")
print(d)

key=input("Enter the key to delete(a-d):")

if key in d:
del d[key]
else:
print("Key not found!")
exit(0)

print("Updated dictionary")
print(d)

OUTPUT:
Case 1:

Initial dictionary
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
Enter the key to delete(a-d):c
Updated dictionary
{'a': 1, 'b': 2, 'd': 4}

Case 2:

Initial dictionary
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
Enter the key to delete(a-d):g
Key not found!

e) Count frequency of words using dictionary

test_string=input("Enter string:")
l=[]

l=test_string.split()

wordfreq=[l.count(p) for p in l]

print(dict(zip(l,wordfreq)))

OUTPUT:

Case 1:

Enter string: hello world program world test


{'test': 1, 'world': 2, 'program': 1, 'hello': 1}

Case 2:

Enter string: orange banana apple apple orange pineapple


{'orange': 2, 'pineapple': 1, 'banana': 1, 'apple': 2}
8. PROGRAMS USING FILES

a) Find occurrences of a given word in a text file

f=open("sample.txt","r")
word=input (" Enter a word: ")
c=0
for x in f:
a=x.split()
print(a)
for i in range (0, len(a)):
if (word == a[i]):
c=c+1
print (“The word ","\"“, word,"\"“, "appears “, c," times ")

OUTPUT:

Contents of file:
hello world hello
hello

Output:

Enter a word : hello

The word “hello” appears 3 times

b) Find occurrences of a given letter in a text file

f=open("sample.txt","r")
l=input (" Enter a letter: ")
c=0
for line in f:
a=line.split()
print(a)
for word in a:
for j in range (0, len(word)):
if(l==word[j]):
c=c+1
print (“The letter ","\"“, l,"\"“, "appears “, c," times ")

OUTPUT:

Contents of file:

hello world hello


hello
Output:

Enter a letter: l

The letter “l” appears 7 times

c) Count number of words in a text file.

f=open("sample.txt","r")
c=0
for x in f:
a=x.split()
print(a)
c=c + len(a)
print (“Total number of words = “, c)

OUTPUT:

Contents of file:
Hello world

Total number of words = 2

d) Count number of letters in a text file

f=open("sample.txt","r")
l=0
for line in f:
a=line.split()
for i in a:
for letter in i:
l=l+1
print (" The total number of letters is = “, l)

OUTPUT:

Contents of file:
hello world hello
hello

The total number of letters is = 20


e) Count number of lines in a text file

f=open("sample.txt","r")
c=0
for x in f:
print(x)
c=c+1
print (" The number of lines: “, c)

OUTPUT:

Contents of file:
Hello world
Hello world

The number of lines: 2


9. Create database connectivity with MYSQL and create a table for
maintaining employee database with employee’s details.

Creating Database Table


Once a database connection is established, we are ready to create tables or records into the
database tables using execute method of the created cursor.
#Importing the module
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost","root","123456","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Drop table if it already exist using execute() method.
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
# Create table as per requirement
sql = """CREATE TABLE EMPLOYEE (
FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT )"""
cursor.execute(sql)
# disconnect from server
db.close()
Output:
10. Write a program to plot the following: -

a) Bar Graph

import matplotlib.pyplot as plt


  
# x-coordinates of left sides of bars 
left = [1, 2, 3, 4, 5]
  
# heights of bars
height = [10, 24, 36, 40, 5]
  
# labels for bars
tick_label = ['one', 'two', 'three', 'four', 'five']
  
# plotting a bar chart
plt.bar(left, height, tick_label = tick_label, width = 0.8, color = ['red', 'green'])
  
# naming the x-axis
plt.xlabel('x - axis')

# naming the y-axis


plt.ylabel('y - axis')

# plot title
plt.title('My bar chart!')
  
# function to show the plot
plt.show()

Output:
b) Scatter Plot

import matplotlib.pyplot as plt


  
# x-axis values
x = [1,2,3,4,5,6,7,8,9,10]

# y-axis values
y = [2,4,5,7,6,8,9,11,12,12]
  
# plotting points as a scatter plot
plt.scatter(x, y, label= "stars", color= "green", marker= "*", s=30)
  
# x-axis label
plt.xlabel('x - axis')

# frequency label
plt.ylabel('y - axis')

# plot title
plt.title('My scatter plot!')

# showing legend
plt.legend()
  
# function to show the plot
plt.show()

Output:
c) Pie Chart

import matplotlib.pyplot as plt


  
# defining labels
activities = ['eat', 'sleep', 'work', 'play']
  
# portion covered by each label
slices = [3, 7, 8, 6]
  
# color for each label
colors = ['r', 'y', 'g', 'b']
  
# plotting the pie chart
plt.pie(slices, labels = activities, colors=colors, startangle=90, shadow = True, explode = (0,
0, 0.1, 0), radius = 1.2, autopct = '%1.1f%%')
  
# plotting legend
plt.legend()
  
# showing the plot
plt.show()

Output:
d) Histogram

import matplotlib.pyplot as plt


  
# frequencies
ages = [2,5,70,40,30,45,50,45,43,40,44,60,7,13,57,18,90,77,32,21,20,40]
  
# setting the ranges and no. of intervals
range = (0, 100)
bins = 10  
  
# plotting a histogram
plt.hist(ages, bins, range, color = 'green',histtype = 'bar', rwidth = 0.8)
  
# x-axis label
plt.xlabel('age')

# frequency label
plt.ylabel('No. of people')

# plot title
plt.title('My histogram')
  
# function to show the plot
plt.show()

Output:

You might also like