[go: up one dir, main page]

0% found this document useful (0 votes)
8 views12 pages

Python lab Additional Prgms

The document outlines a series of Python programming exercises aimed at teaching various concepts such as data types, arithmetic operations, string manipulation, list and dictionary operations, and more. Each exercise includes an aim, algorithm, program code, and output examples. The exercises cover a wide range of topics, including temperature conversion, prime number printing, recursion, and file handling.

Uploaded by

Amudaria
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)
8 views12 pages

Python lab Additional Prgms

The document outlines a series of Python programming exercises aimed at teaching various concepts such as data types, arithmetic operations, string manipulation, list and dictionary operations, and more. Each exercise includes an aim, algorithm, program code, and output examples. The exercises cover a wide range of topics, including temperature conversion, prime number printing, recursion, and file handling.

Uploaded by

Amudaria
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
You are on page 1/ 12

GE3171 - Problem Solving and Python Programming Lab

ADDITIONAL PROGRAMS
Ex.No : 7
DATA TYPES
Date :

AIM:
To write a Python Program to demonstrate different number data types in python.

Algorithm:

1.Start
2.Read an integer ,a floating point integer and a complex number.
3.Print the type of the integers using “type() function.
4.Do arithmetic operations on these integers.
5.Print the results.
6.Stop.
Program: print("Sum is:",c2)
print(type(c2))
a=int(input("Enter an integer:"))
Output:
b=int(input("Enter an integer:"))
Enter an integer:5
c=a+b
Enter an integer:6
print("Sum is",c)
('Sum is', 11)
print(type(c))
a1=float(input("Enter a floating point integer:")) <type 'int'>
Enter a floating point integer:5.6
b1=float(input("Enter a floating point
integer:")) Enter a floating point integer:5.4
c1=a1+b1 ('Sum is:', 11.0)
print("Sum is:", c1) <type 'float'>
print(type(c1)) Enter a complex integer:3+4j
a2=complex(input("Enter a complex integer:")) Enter a complex integer:2+5j
b2=complex(input("Enter a complex integer:")) ('Sum is:', (5+9j))
c2=a2+b2 <type 'complex'>
RESULT:
Thus the Python program to demonstrate different number data types in python was
executed and verified successfully.
GE3171 - Problem Solving and Python Programming Lab

Ex.No : 8
ARITHMETIC OPERATIONS ON NUMBERS
Date :

AIM:
To write a Python program to perform different arithmetic operations on numbers in
python.
Algorithm:

1. Start.
2. Read two input integers.
3. Addition operation using + operator, x + y adds 2 numbers.
4. Subtraction operation using - operator, x – y finds difference.
5. Multiplication operation using * operator, x * y multiplies 2 numbers.
6. Division use / operator, x / y divides left hand operand by right hand operand.
7. Floor Division operation using // operator, x // y divides left hand operand by right
hand operand, here it removes the values after decimal point.
8. Modulus % operator when applied returns the remainder, x % y.
9. Print the result of each operation.
10. Stop

Program & Output: Refer page no 106 and 107 in Book.

x=5 Output:
y=5 x+y=30
print(“x+y=”,x+y) x-y=20
print(“x-y=”,x-y) x*y=125
print(“x*y=”,x*y) x/y=5.0
print(“x/y=”,x/y) x%y=0
print(“x%y=”,x%y) x//y=5
print(“x//y=”,x//y)

RESULT:
Thus the Python program to perform different arithmetic operations on numbers in
python was executed and verified successfully.
GE3171 - Problem Solving and Python Programming Lab

Ex.No : 9
STRING OPERATIONS
Date :

AIM:
To write a program to create, concatenate and print a string and accessing substring from
a given string.
Program: Output:
a="save" save water
b=" water" ('a[0:4] : ', 'HELL')
print( a + b ) ('a[ :3] : ', 'HEL')
a="HELLO" ('a[1:] : ', 'ELLO')
print("a[0:4] : ", a[0:4])
print("a[ :3] : ", a[ : 3])
print("a[1:] : ", a[1: ])

Ex.No : 10
DISPLAY THE CURRENT DATE
Date :

AIM:
To write a python script to print the current date in the following format “Sun May 29
02:26:23 IST 2017”.

%a : Abbreviated weekday name.


%b : Abbreviated month name.
%d : Day of the month as a decimal number [01,31].
%H : Hour (24-hour clock) as a decimal number [00,23].
%M : Minute as a decimal number [00,59].
%S : Second as a decimal number [00,61].
%Z : Time zone name (no characters if no time zone exists).
%Y : Year with century as a decimal number.
GE3171 - Problem Solving and Python Programming Lab

Program:
import time;
ltime=time.localtime();
print(time.strftime("%a %b %d %H:%M:%S %Z %Y",ltime));
Output:
Sat Mar 12 11:42:33 India Standard Time 2022

Ex.No : 11
LIST OPERATIONS
Date :

AIM:
To write a program to create, append, and remove lists in python.

Program:
pets = ['cat', 'dog', 'rat', 'pig', 'tiger']
snakes=['python','anaconda','fish','cobra','mamba']
print("Pets are :",pets)
print("Snakes are :",snakes)
pets.append(snakes)
print("Appended pets are :",pets)
snakes.remove("fish")
print("Updated Snakes are :",snakes)
Output:
('Pets are :', ['cat', 'dog', 'rat', 'pig', 'tiger'])
('Snakes are :', ['python', 'anaconda', 'fish', 'cobra', 'mamba'])
('Appended pets are :', ['cat', 'dog', 'rat', 'pig', 'tiger', ['python', 'anaconda', 'fish', 'cobra', 'mamba']])
('Updated Snakes are :', ['python', 'anaconda', 'cobra', 'mamba'])

Ex.No : 12
TUPLES
Date :
AIM:
To write a program to demonstrate working with tuples in python.
GE3171 - Problem Solving and Python Programming Lab

Program:
fruits = ("apple", "banana", "cherry", "mango", "grapes", "orange")
print("Fruits are :",fruits)
print("Second fruit is :",fruits[1])
print("From 3-6 fruits are :",fruits[3:6])
print("List of all items in Tuple :")
for i in fruits:
print(i)
if "apple" in fruits:
print("Yes, 'apple' is in the fruits tuple")
print("Length of Tuple is :",len(fruits))
Output: List of all items in Tuple :
('Fruits are :', ('apple', 'banana', 'cherry', apple
'mango', 'grape', 'orange')) banana
('Second fruit is :', 'banana') cherry
('From 3-6 fruits are :', ('mango', 'grape', mango
'orange'))
grape
orange
Yes, 'apple' is in the fruits tuple
('Length of Tuple is :', 6)

Ex.No : 13 CONVERT TEMPERATURES TO AND FROM CELSIUS, FAHRENHEIT


Date :

AIM:
To write a Python program to convert temperatures to and from Celsius, Fahrenheit.

Program: (Refer page no 101 in Book)


celsius=int(input("Enter the Temperature in Celsius:"))
f=(celsius * 9 / 5)+ 32
print("Temperature in Fahrenheit is:",f)
GE3171 - Problem Solving and Python Programming Lab

fahr=int(input("Enter the Temperature in Fahrenheit:"))


c=(fahr - 32) * 5 / 9;
print("Temperature in Celsius is:",c)
Output:
Enter the Temperature in Celsius:32
('Temperature in Fahrenheit is:', 89)
Enter the Temperature in Fahrenheit:80
('Temperature in Celsius is:', 26)

Ex.No : 14
Date : DICTIONARIES

AIM:
To write a program to demonstrate working with dictionaries in python.

Program:
cse={"name" : "ABC","age" : 20} Output:
print("Dictionary is : ", cse) ('Dictionary is : ', {'age': 20, 'name': 'ABC'})
print("cse[name] : ", cse["name"]) ('cse[name] : ', 'ABC')
print("cse[age] : ", cse["age"]) ('cse[age] : ', 20)
print("Length : ", len(cse)) ('Length : ', 2)
cse["address"]="xyz" ('age', 20)
for key, val in cse.items(): ('name', 'ABC')
print( key, val ) ('address', 'xyz')
print("Kays : ", dict.keys(cse)) ('Kays : ', ['age', 'name', 'address'])
print("Values : ", dict.values(cse)) ('Values : ', [20, 'ABC', 'xyz'])
student = dict.copy(cse) ('Student is : ', {'age': 20, 'name': 'ABC',
'address': 'xyz'})
print("Student is : ", student)
dict.clear(cse)
GE3171 - Problem Solving and Python Programming Lab

Ex.No : 15
Date : NESTED FOR LOOP

AIM:
To write a Python program to construct the stars(*) pattern, using a nested for loop.

PYRAMID PATTERN: (Refer page no 9 in Manual)

PROGRAM: OUTPUT:
num = int( input( "Enter a number : " ) ) Enter a number : 5
for i in range( num ): *
for j in range( ( num - i ) - 1 ) : **
print( “ “ ), ***
for j in range( i + 1 ): ****
print( "* " ), *****
print

Ex.No : 16
Date : FIND LARGEST OF THREE NUMBERS

AIM:
To write a python program to find largest of three numbers.

Program:
num1 = int(input("Enter first number: ")) Output:
num2 = int(input("Enter second number: ")) Enter first number: 5
num3 = int(input("Enter third number: ")) Enter second number: 8
if (num1 > num2) and (num1 > num3): Enter third number: 3
largest = num1 ('The largest number is', 8)
elif (num2 > num1) and (num2 > num3):
largest = num2
else:
largest = num3
print("The largest number is",largest)
GE3171 - Problem Solving and Python Programming Lab

Ex.No : 17
Date : PRINT PRIME NUMBERS

AIM:
To write a Python script that prints prime numbers less than 20.

Program: Output:
print("Prime numbers b/w 1 and 20 are:") Prime numbers between 1 and 20 are:
for num in range(20): 2
if num > 1: 3
for i in range(2,num): 5
if (num % i) == 0: 7
break 11
else: 13
print(num) 17
19

Ex.No : 18
Date : RECURSION

AIM:
To write a python program to find factorial of a number using Recursion.

Program: (Refer pg no 129 in Book)


def fact(n): Output:
if(n==1): Enter no. to find fact:5
return 1
('Fact is', 120)
else:
return n*fact(n-1)
n=int(input("Enter no. to find fact:"))
fact=fact(n)
print("Fact is",fact)
GE3171 - Problem Solving and Python Programming Lab

Ex.No : 19
Date : RIGHT TRIANGLE

AIM:
To write a program that accepts the lengths of three sides of a triangle as inputs. The
program output should indicate whether or not the triangle is a right triangle (Use Pythagorean
Theorem).
Formula : hypotenuse 2 = Base 2 * Perpendicular 2
Program:
base=float(input("Enter length of Base : "))
perp=float(input("Enter length of Perpendicular : "))
hypo=float(input("Enter length of Hypotenuse : "))
if hypo**2==((base**2) + (perp**2)):
print("It's a right triangle")
else:
print("It's not a right triangle")
Output:
Enter length of Base : 20
Enter length of Perpendicular : 15
Enter length of Hypotenuse : 25
It's a right triangle

Ex.No : 20
Date : FIBONACCI NUMBERS

AIM:
To write a python program to define a module to find Fibonacci Numbers and import the
module to another program.
GE3171 - Problem Solving and Python Programming Lab

Program:
fib.py Output:
Enter a no for Fibonacci series 15
def fibonacci(n):
1
a, b = 0, 1
1
while b < n:
2
print(b)
3
a, b = b, a+b
5
ex14.py
8
import fib
13
num=int(input("Enter a no for Fibonacci:"))
fib.fibonacci(num)

Ex.No : 21
Date : IMPORT A FUNCTION

AIM:
To write a python program to define a module and import a specific function in that
module to another program.

Program:
fact.py
def factorial(n): Output:
if(n == 1): Enter no. to find fact:5
return 1
('Factorial is ', 120)
else:
return n*fact(n-1)

ex15.py

import factorial
n=int(input("Enter no. to find fact:"))
f=fact.factorial(n)
print("Factorial is ",f)
GE3171 - Problem Solving and Python Programming Lab

Ex.No : 22
Date : FILE

AIM:
To write a script named copyfile.py. This script should prompt the user for the names of
two text files. The contents of the first file should be input and written to the second file.

Program:
file1.py
This is python program
Welcome to python

Program: (Refer program in page no 31 in Manual)


source = open("E:\\nisha\\file1.txt", "r+") dest.close()
dest = open("E:\\nisha\\file2.txt", "w+") Output :
line = source.readline() File copied successfully!
while line: File2.py
dest.write(line) This is python program
line = source.readline() Welcome to python
print("File copied successfully!")
source.close()

Ex.No : 23 PRINT ALL OF THE UNIQUE WORDS IN THE FILE IN ALPHABETICAL


Date : ORDER.

AIM:
To write a program that inputs a text file and print all of the unique words in the file in
alphabetical order.
GE3171 - Problem Solving and Python Programming Lab

Program:
filename=input("Enter file name:")
inf=open(filename,'r') Output:
wordcount={} Enter file name:file1.txt
for line in inf.readlines(): this is python program.
print(line) welcome to python program.
for word in line.split( ): ['is', 'program.', 'python', 'this', 'to', 'welcome']
if word not in wordcount:
wordcount[word]=1
else:
wordcount[word]+=1
print(sorted(wordcount.keys()))

Ex.No : 24
STRINGS (REVERSE AND PALINDROME)
Date :

AIM:
To write a program to implement using strings(reverse and palindrome).

Program: Output:
str = raw_input("Enter a String : ") Enter a String : malayalam
print("The original string is: ",str) ('The original string is: ', 'malayalam')
rev = str[::-1] ('The reverse string is', 'malayalam')
print("The reverse string is",rev) Palindrome
if(str==rev):
print("Palindrome")
else:
print("Not palindrome")

You might also like