Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Python Lab Manual (1)

The document outlines various Python programming exercises, including reversing a string, checking for palindromes, converting a list to a Pandas Series, testing for zero elements in an array using NumPy, copying text between files, handling command line arguments, managing divide by zero errors, validating voter age, and checking student mark ranges. Each exercise includes an aim, algorithm, program code, output, and a result confirming successful execution. The exercises demonstrate fundamental programming concepts and error handling in Python.

Uploaded by

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

Python Lab Manual (1)

The document outlines various Python programming exercises, including reversing a string, checking for palindromes, converting a list to a Pandas Series, testing for zero elements in an array using NumPy, copying text between files, handling command line arguments, managing divide by zero errors, validating voter age, and checking student mark ranges. Each exercise includes an aim, algorithm, program code, output, and a result confirming successful execution. The exercises demonstrate fundamental programming concepts and error handling in Python.

Uploaded by

devi murugan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Ex:7.

1
REVERSE OF A STRING
Date:

Aim:
To write a python program for reversing a string.
Algorithm:
Step 1: Start the program.
Step 2: Read the value of a string value by using function call reversed_string.
Step 3: if len(text)==1 return text.
Step 4: else return reversed_string(text[1:])+text[:1].
Step 5: Print a
Step 6: Stop the program

Program:
def reversed_string(text):
if len(text) == 1:
return text
return reversed_string(text[1:])+text[:1]
a=reversed_string("Hello, World!")
print(a)

Output:
dlroW,olleH

Result:Thus the python program for reversing a.string is executed and the results are verified.
Ex:7.2
PALINDROME OF A STRING
Date:

Aim:
To write a python program for palindrome of a string.
Algorithm:
Step 1: Start the program.
Step 2: Read the value of a string value by using input method.
Step 3: if string==string[::-1],print “the string is palindrome”.
Step 4: else print “ Not a palindrome ”.
Step 5: Stop the program

Program:
string=input(("Enter a string:"))
if(string==string[::-1]):
print("The string is a palindrome")
else:
print("Not a palindrome")

Output:
Enter a string: madam
The string is a palindrome
Enter a string: nice
Not a palindrome

Result: Thus the python program for palindrome of a string is executed and the results are verified.
Ex:8.1
Date: CONVERT LIST IN TO A SERIES USING PANDAS

Aim:
To write a python program for converting list into a Series.

Algorithm:

Step 1: Start the program. Step


2: import pandas library
Step 3: Create an object as pd for pandas.
Step 4: Define a list
Step 5: Convert the list into series by calling the series function
Step 6: print the result
Step 7: Stop the program.

Program:

#To use pandas first we have to import pandas


import pandas as pd
#Here pd just a object of pandas
#Defining a List
A=['a','b','c','d','e']
#Converting into a series
df=pd.Series(A)
print(df)

Output:
1 a
2 b
3 c
4 d
5 e
dtype: object

Result: Thus the python program for converting list into a series is executed and the results are
verified.
Ex:8.2
FINDING THE ELEMENTS OF A GIVEN ARRAY IS ZERO USING
Date: NUMPY

Aim:
To write a python program for testing whether none of the elements of a given array is zero.

Algorithm:

Step 1 : Start the program.


Step 2 : import numpy library
Step 3 : Create a object as np for numpy library
Step 4 : Define and initialize an array
Step 5 : to test if none of the elements of the said array is zero use all function
Step 6 : print the result
Step 7: Stop the program.

Program:

import numpy as np
#Array without zero value
x = np.array([1, 2, 3, 4,])
print("Original array:")
print(x)
print("Test if none of the elements of the said array is zero:")
print(np.all(x))
#Array with zero value
x=np.array([0,1,2,3])
print("Original array:")
print(x)
print("Test if none of the elements of the said array is zero:")
print(np.all(x))

Output:
Original array:
[1 2 3 4]
Test if none of the elements of the said array is zero:
True
Original array:
[0 1 2 3]
Test if none of the elements of the said array is zero:
False

Result:
Thus the python program for testing whether none of the elements of a given array is zero is
executed and the results are verified.
Ex:9.1
Date: COPY TEXT FROM ONE FILE TO ANOTHER

Aim:
To write a Python program for copying text from one file to another.
Algorithm:

Step 1: Start
Step 2: Create file named file.txt and write some data into it.
Step 3: Create a file name sample.txt to copy the contents of the file
Step 4: The file file.txt is opened using the open() function using the f stream.
Step 5: Another file sample.txt is opened using the open() function in the write mode using the
f1 stream.
Step 6: Each line in the file is iterated over using a for loop (in the input stream).
Step 7: Each of the iterated lines is written into the output file.
Step 8: Stop

Program:
with open("file.txt")as f:
with open("sample.txt","w")as f1:
for line in f:
f1.write(line)
Output:

The contents of file named file.txt is copied into sample.txt

Result: Thus the python program for copying text from one file to another is executed and the results
are verified.
Ex:9.2
Date: COMMAND LINE ARGUMENTS (WORDCOUNT)

Aim:
To write a Python program for command line arguments.

Algorithm:

Step 1: Start
Step 2: import the package sys
Step 3: Get the arguments in command line prompt
Step 4: Print the number of arguments in the command line by using len(sys.argv)function
Step 5: Print the arguments using str(sys.argv ) function
Step 6: Stop

Program:
import sys
print('Number of arguments:',len(sys.argv),'arguments.')
print('Argument List:',str(sys.argv))

Steps for execution:

Open Windows command prompt by typing cmd in startup menu


C:\Users\admin>cd..
C:\Users>cd..
C:\>cd Portable Python 3.2.5.1 C:\
PortablePython3.2.5.1>cd App
C:\PortablePython3.2.5.1\App>python.exe cmd.py arg1 arg2 arg3
Or
C:\PortablePython3.2.5.1\App>python cmd.py arg1 arg2 arg3

Output:
Number of arguments: 4 arguments.
Argument List: ['cmd.py','arg1','arg2','arg3']

Result: Thus the Python program for command line arguments is executed successfully and the
output is verified.
Ex:10.1
DIVIDE BY ZERO ERROR–EXCEPTION HANDING
Date:

Aim:
To write a Python program for finding divide by zero error.

Algorithm:

Step 1: Start the program


Step 2: Take inputs from the user, two numbers.
Step 3: If the entered data is not integer, throw an exception.
Step 4: If the remainder is 0, throw divide by zero exception.
Step 5: If no exception is there, return the result.
Step 6: Stop the program.

Program:

try:
num1 = int(input("Enter First Number: "))
num2 = int(input("Enter Second Number:"))
result = num1 / num2
print(result)
except Value Error as e:
print("Invalid Input Please Input Integer...")
except Zero Division Error as e:
print(e)

Output:
Enter First Number: 12.5
Invalid Input Please Input Integer...

Enter First Number: 12


Enter Second Number: 0
division by zero

Enter First Number: 12


Enter Second Number: 2
6.0

Result: Thus the Python program for finding divide by zero error is executed successfully and the
output is verified.
Ex:10.2
VOTER’S AGE VALIDITY
Date:

Aim:
To write a Python program for validating voter’s age.

Algorithm:

Step 1: Start the program


Step 2: Accept the age of the person.
Step 3: If age is greater than or equal to18, then display 'You are eligible to vote'.
Step 4: If age is less than 18, then display 'You are not eligible to vote'.
Step 5: If the entered data is not integer, throw an exception value error.
Step 6: If the entered data is not proper, throw an IOError exception Step
7: If no exception is there, return the result.
Step 8: Stop the program.

Program:

def main():
#single try statement can have multiple except statements.
try:
age=int(input("Enter your age"))
if age>18:
print("'You are eligible to vote'")
else:
print("'You are not eligible to vote'")
except Value Error:
print("age must be a valid number")
except IOError:
print("Enter correct value")
#generic except clause, which handles any exception.
except:
print("An Error occured")
main()
Output:
Enter your age 20.3
age must be a valid number

Enter your age 12


Not eligible to vote

Enter your age 35


Eligible to vote

Result: Thus the Python program for validating voter’s age is executed successfully and the output
is verified.
Ex:10.2
STUDENT MARK RANGE VALIDATION
Date:

Aim:
To write a python program for student mark range validation

Algorithm:

Step 1: Start the program


Step 2: Get the inputs from the users.
Step 3: If the entered data is not integer, throw an exception.
Step 4: If no exception is there, return the result.
Step 5: Stop the program.

Program:

def main():
try:
mark=int(input("Enter your mark:"))
if(mark>=50 and mark<101):
print("You have passed")
else:
print("You have failed")
except ValueError:
print("It must be a valid number")
except IOError:
print("Enter correct valid number")
except:
print("an error occured")
main()
Output:
Enter your mark:50
You have passed
Enter your mark:r
It must be a valid number
Enter your mark:0
You have failed

Result: Thus the python program for student mark range validation is executed and verified.

You might also like