0% found this document useful (0 votes)
4 views20 pages

Basic Python Practical.....

The document outlines various practical exercises for writing Python programs, covering topics such as data types, control statements, recursion, file handling, and exception handling. Each practical includes aims, input code, and expected output, demonstrating fundamental programming concepts and operations like arithmetic, string manipulation, and array handling. The exercises are structured to enhance understanding of Python programming through hands-on coding examples.

Uploaded by

jazfreelance1920
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)
4 views20 pages

Basic Python Practical.....

The document outlines various practical exercises for writing Python programs, covering topics such as data types, control statements, recursion, file handling, and exception handling. Each practical includes aims, input code, and expected output, demonstrating fundamental programming concepts and operations like arithmetic, string manipulation, and array handling. The exercises are structured to enhance understanding of Python programming through hands-on coding examples.

Uploaded by

jazfreelance1920
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/ 20

Practical – 1

(A) Aim: Write a python program to use various data types.


Input:
Output:

(B) Aim: Write a python program to perform the input and output
operations.
Input:
Output:

Practical – 2
(A) Aim: Write a python program to design various control
statements using suitable examples.
Input:
Output:

(B) Aim: Write a Python program to check whether entered


number is Armstrong or not using while loop.
Input:
number=int(input("Enter your number"))
original_number=number
sum_of_digits=0
num_of_digits=len(str(number))
while number>0:
digit=number%10
sum_of_digits+=digit**num_of_digits
number//=10
if sum_of_digits==original_number:
print(f"{original_number} is an Armstrong number")
else:
print(f"{original_number} is not an Armstrong number")

Output:
Enter your number153
153 is an Armstrong number

(C) Aim: Write a python program to print first n natural number.

Input:
n=int(input("Enter a positive integer:"))
print(f"\nthe first {n} natural numbers are:")
for i in range(1,n+1):
print(i)

Output:
Enter a positive integer:10
the first 10 natural numbers are:
1
2
3
4
5
6
7
8
9
10
Practical - 3
Aim: Write a python program show the use of logical, arithmetic
and comparision operator.

Input:
a=5
b=6
print(f"Arithmetic operator")
print(f"{a} + {b}= {a+b}")
print(f"{a} - {b}= {a-b}")
print(f"{a} * {b}= {a*b}")
print(f"{a} / {b}= {a/b}")
print(f"{a} % {b}= {a%b}")
print(f"{a} // {b}= {a//b}")
print(f"{a} ** {b}= {a**b}")
print("\n")

print(f"Comparision operator")
print(f"{a}>{b} is {a>b}")
print(f"{a}<{b} is {a<b}")
print(f"{a}=={b} is {a==b}")
print(f"{a}!={b} is {a!=b}")
print(f"{a}>={b} is {a>=b}")
print(f"{a}<={b} is {a<=b}")
print("\n")

x=True
y=False
print(f"Logical Operator")
print(f" x AND y is {x and y}")
print(f" x OR y is {x or y}")
print(f" x NOT is {x not}")
Output:
Arithmetic operator
5 + 6= 11
5 - 6= -1
5 * 6= 30
5 / 6= 0.8333333333333334
5 % 6= 5
5 // 6= 0
5 ** 6= 15625

Comparision operator
5>6 is False
5<6 is True
5==6 is False
5!=6 is True
5>=6 is False
5<=6 is True

Logical Operator
x AND y is False
x OR y is True
x NOT is False

Practical – 4

(A) Aim: Wirte a python program to show recursive function in


factorial.

Input:
def recur_factorial(n):
if n==1:
return n
else:
return n*recur_factorial(n-1)
num =7
if num<0:
print(f"sorry ,factorial does not exist for negative number")
elif num==0:
print(f"The factorial of 0 is 1")
else:
print(f"The factorial of",num,"is",recur_factorial(num))

Output:
The factorial of 7 is 5040

(B) Aim: Write a python code to show function.

Input:
def count_down(start):
'''count down from a number'''
print(start)
next=start-1
if next>0:
count_down(next)
count_down(3)

output:
3
2
1

(C) Aim: Write a python program to show lambda function .

Input:
def cube(y):
return y * y* y

lambda_cube = lambda y: y*y*y

print(cube(5))
print(lambda_cube(5))
Output:

Practical – 5

(A) Aim: Write a python program to implement list in python for


suitable problems demonstrate various operations on it
(insert, remove, append, length, pop, clear)

Input:
a=[1,3,5,6,7,[3,4,5],"hello"]
print(a)
a.insert(3,20)
print(a)
a.remove(7)
print(a)
a.append("h1")
print(a)
print("Length of list:",len(a))
a.pop()
print(a)
a.pop(6)
print(a)
a.clear()
print(a)

Output:
[1, 3, 5, 6, 7, [3, 4, 5], 'hello']
[1, 3, 5, 20, 6, 7, [3, 4, 5], 'hello']
[1, 3, 5, 20, 6, [3, 4, 5], 'hello']
[1, 3, 5, 20, 6, [3, 4, 5], 'hello', 'h1']
Length of list: 8
[1, 3, 5, 20, 6, [3, 4, 5], 'hello']
[1, 3, 5, 20, 6, [3, 4, 5]]
[]

(B) Aim: Write a program on string

Input:
string1="Hello"
string2="World"
multiline_string="""This is a multiline string."""
print("String1:",string1)
print("String2:",string2)
print("Multiline String:",multiline_string)

upper_string=string1.upper()
lower_string=string2.lower()
joined_string=string1+""+string2
replaced_string=string1.replace("H","J")
split_string=multiline_string.split()

print("Uppercase String:",upper_string)
print("Lowercase String:",lower_string)
print("Joined String:",joined_string)
print("Replaced String:",replaced_string)
print("Split String:",split_string)

first_char=string1[0]
last_char=string2[-1]
substring=joined_string[6:11]

print("First character of String:",first_char)


print("Last character of String:",last_char)
print("Substring character of String:",substring)

name="Alice"
age=30
formatted_string=f"My name is {name} and I am {age} years old."
print("Formatted String:",formatted_string)

sentence= "This is a simple sentence with the several word."


char_count=len(sentence)
word_count=len(sentence.split())
print("Number of characters in the sentence:",char_count)
print("Number of word in the sentence:",word_count)

original_string="I love programming."


substring_to_insert="Python"
position=7
new_string=original_string[:position]+substring_to_insert +
original_string[position:]
print("String after inserting substring:",new_string)

Output:
String1: Hello
String2: World
Multiline String: This is a multiline string.
Uppercase String: HELLO
Lowercase String: world
Joined String: HelloWorld
Replaced String: Jello
Split String: ['This', 'is', 'a', 'multiline', 'string.']
First character of String: H
Last character of String: d
Substring character of String: orld
Formatted String: My name is Alice and I am 30 years old.
Number of characters in the sentence: 48
Number of word in the sentence: 9
String after inserting substring: I love Pythonprogramming.

Practical - 6

(A) Aim: Write a python program to interchange the tuple values


within two tuples.
tup1=('physics','chemistry',1997,2000)
tup2=(1,2,3,4,5)
print("Value in tuple 1:",tup1)
print("Value in tuple 2:",tup2)
temp=tup1
tup1=tup2
tup2=temp

print("After swapping:")
print("Value in tuple 1:",tup1)
print("Value in tuple 2:",tup2)

Output:
Value in tuple 1: ('physics', 'chemistry', 1997, 2000)
Value in tuple 2: (1, 2, 3, 4, 5)
After swapping:
Value in tuple 1: (1, 2, 3, 4, 5)
Value in tuple 2: ('physics', 'chemistry', 1997, 2000)

(B) Aim: Write a python program to demonstrate dictionary


template create update and delete dictionary

Input:
collegeinfo={"college":"ABC","City":"Mumbai","TPO":"sachin"}
print(collegeinfo)
print(collegeinfo["college"],collegeinfo["TPO"])
print(collegeinfo.keys,".")
print(collegeinfo.values())
collegeinfo["TPO"] = "Bela"
del collegeinfo["City"]
print(collegeinfo)
collegeinfo["website"] = "www.abc.org"
print(collegeinfo)

Output:
{'college': 'ABC', 'City': 'Mumbai', 'TPO': 'sachin'}
ABC sachin
<built-in method keys of dict object at
0x000001EE73013FC0> .
dict_values(['ABC', 'Mumbai', 'sachin'])
{'college': 'ABC', 'TPO': 'Bela'}
{'college': 'ABC', 'TPO': 'Bela', 'website': 'www.abc.org'}

Practical – 7

(A) Aim: Write a python code to read and write a .txt file.

Input:
file=open("j2.txt",'r')
print("Reading from file;")
print(file.read())
file.close()

file=open("j2.txt",'a')
file.write("\nThis text has been newly appended to the j2
file.")
file.close()

file=open("j2.txt",'w')
file.write("All content has been overwritten!")
file.close()
Output:
Reading from file;
<html>
<head>
<title>sample</title>
</head>
<body>
<h1>Hello,I am jatin</h1>
<h2>First year data science student</h2>
</body>
</html>

This text has been newly appended to the j2 file.


Reading from file;
All content has been overwritten!

Practical – 8

Aim: Write a python code to create and manipulate array in


python also demonstrate use of slicing and indexing for
accessing element from the array.

Input:
import numpy
my_array=numpy.array([0,1,2,3,4])
print(my_array)
output:
[0 1 2 3 4]

#Reshaping an array

import numpy as np
a=np.arange(8)
print(a)
print("\n")

b=a.reshape(4,2)
print("\nThe modified array:")
print(b)

Output:
[0 1 2 3 4 5 6 7]

The modified array:


[[0 1]
[2 3]
[4 5]
[6 7]]

Input:
import numpy as np
a=np.arange(12)
b=a.reshape(3,4)
print("\nThe array is")
print(b)

print(a)
print("\n")
print("The transpose array is")
print(np.transpose(a))

Output:
The array is
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[ 0 1 2 3 4 5 6 7 8 9 10 11]

The transpose array is


[ 0 1 2 3 4 5 6 7 8 9 10 11]

Input:
import numpy as np
a=np.array([[1,2,3],[4,5,6]])
print("First Array")
print(a)
print("\n")

print("append element to array")


print(np.append(a,[7,8,9]))
print("\n")

print("Append element along axis 0;")


print(np.append(a,[[7,8,9]],axis=0))
print("\n")

print("Append element along axis 1;")


print(np.append(a,[[5,5,5],[7,8,9]],axis=1))

Output:
First Array
[[1 2 3]
[4 5 6]]

append element to array


[1 2 3 4 5 6 7 8 9]

Append element along axis 0;


[[1 2 3]
[4 5 6]
[7 8 9]]

Append element along axis 1;


[[1 2 3 5 5 5]
[4 5 6 7 8 9]]

#Indexing and slicing of an array


import numpy as np
array1=np.array([2,4,6,8,10])

print(array1[0])

Output:
2

To index from last element of the array


import numpy as np
array1=np.array([2,4,6,8,10])
print(array1[-1])

Output:
10

import numpy as np
array1=np.array([2,4,6,8,10])
print(array1[1:])
Output:
[ 4 6 8 10]

Practical – 9

Aim: Write a python program to perform exception handling.

Input:
def divide_numbers():
try:
num1=float(input("Enter the First number:"))
num2=float(input("Enter the second number:"))
result = num1/num2

except ZeroDivisionError:
print("Error: Cannot divide by zero")

except ValueError:
print("Error: Invalid input! Please enter numeric values")

else:
print(f'The result of dividing {num1} {num2} is:{result}')

finally:
print("Execution completed.")

divide_numbers()

Output:
Enter the First number:2
Enter the second number:4
The result of dividing 2.0 4.0 is:0.5
Execution completed.

Practical - 10

Aim: Write a python program to create multiple function of


math.

Input:
import math
print(f"Square root of 16:{math.sqrt(16)}")

from math import factorial,pi

print(f'Factorial of 5:{factorial(5)}')
print(f"Value of pi:{pi}")

import random as rnd


print(f'Random number between 1 and 10: {rnd.randint(1,10)}')

from math import*

Output:

Square root of 16:4.0


Factorial of 5:120
Value of pi:3.141592653589793
Random number between 1 and 10: 6

You might also like