0% found this document useful (0 votes)
6 views38 pages

Python

Some of the python lab questions

Uploaded by

salmashaik1319
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)
6 views38 pages

Python

Some of the python lab questions

Uploaded by

salmashaik1319
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

PYTHON LAB

1) Write a program to find the largest element among three


numbers.

num1 = 10
num2 = 14
num3 = 12

# uncomment following lines to take three numbers from user


#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:
The largest number is 14

2) Write a program to display all prime numbers within an


internal.

lower = 900
upper = 1000

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

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


# all 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 to 1000 are:
907
911
919
929
937
941
947
953
967
971
977
983
991
997
3) Write a program to swap two numbers without using a
temporary variable.

x = 10
y=5

# code to swap
# 'x' and 'y'

if y == 0:
y=x
x=0
elif x == 0:
x=y
y=0
else:
x=x*y
y = x // y
x = x // y
print("After Swapping: x =", x, " y =", y)

Output :
After swapping: x=5,u=10

4) Demonstrate the following Operations in python with


suitable example
A) Artimetic operation:
X=5
Y=3
print(X+Y)

Output:
8

B) Relational operators:
a=5
b= 10
print(a == b)
output : False
print(a != b)
output: True
print(a < b)
Output: True
print(a <= b)
Output: True
print(a > b)
Output: False
print(a >= b)
Output: False

C) Assignment operation:

# assign 10 to a
a= 10

# assign 5 to b
b=5

# assign the sum of a and b to a


a+= b #a=a+b
print(a)

Output: 15

D) logical operator:

# logical AND
x=5
print (x>3 and x<10)
Output: True

# logical OR
x=5
print(x>3 and x<4)

Output : false

# logical NOT
x=5
print(not(x>3 and x<10))
Output : False

e) Bitwise operators:

a = 10
b=4

# Print bitwise AND operation


print(“a & b =”, a & b)
Output: A&b=0

F) Ternary operator:
# Program to demonstrate ternary operator
a = 10
b = 20

# python ternary operator


min = “a is minimum” if a < b else “b is minimum”
print(min)
Output: A is minimum
G) membership operator and identify operation:
# initialized some sequences
list1 = [1, 2, 3, 4, 5]
str1 = “Hello World”
set1 = {1, 2, 3, 4, 5}
dict1 = {1: “Geeks”, 2:”for”, 3:”geeks”}
tup1 = (1, 2, 3, 4, 5)

# using membership ‘in’ operator


# checking an integer in a list
print(2 in list1)

# checking a character in a string


print(‘O’ in str1)

# checking an integer in a set


print(6 in set1)

# checking for a key in a dictionary


print(3 in dict1)
# checking for an integer in a tuple
print(9 in tup1)
Output:
True
False
True
False

5) Write a program to add and multiply complex numbers:

# Python program to add two complex number

# Enter first complex number i.e. 3+4j not 3+4i


first = complex(input(‘Enter first complex number: ‘))
second = complex(input(‘Enter first complex number: ‘))

# Addition of complex number


Addition = first + second

# Displaying Sum
print(‘SUM = ‘, addition)
Output:
Enter first complex number: 2+3j
Enter first complex number: 4+6j
SUM = (6+9j)

6) Write a program to print multiplication table of a given


number
# Multiplication table (from 1 to 10) in Python

num = 12
# To take input from the user
# num = int(input(“Display multiplication table of? “))

# Iterate 10 times from I = 1 to 10


for i in range(1, 11):
print(num, ‘x’, i, ‘=’, num*i)
Output:
12×1=12
….
12×10=120
7) Write a program to define a function with multiple return
values.
# A Python program to return multiple
# values from a method using class
class test:
def init (self):
self.str = “geeksforgeeks”
self.x = 20

# This function returns an object of Test


def fun():
return test()

# Driver code to test above method


t = fun()
print(t.str)
print(t.x)
Output:
Geeksforgeeks
20
8) Write a program to define a function using default
arguments.
def student(firstname, lastname =’Mark’, standard =’Fifth’):
print(firstname, lastname, ‘studies in’, standard, ‘Standard’)

# 1 positional argument
student(‘John’)

# 3 positional arguments
student(‘John’, ‘Gates’, ‘Seventh’)

# 2 positional arguments
student(‘John’, ‘Gates’)
student(‘John’, ‘Seventh’)
Output:
John Mark studies in Fifth Standard
John Mark studies in Seventh Standard
John Gates studies in Fifth Standard
9) Write a program to fine the length of the string without using
any library function.
string =’hello’
count=0
for i in string:
count+=1
print(count)

Output
1,2,3,4,5

10) Write a program to check if the substring is present in a


given string or not:

text = “Geeks welcome to the Geek Kingdom!”

if “Geek” in text:
print(“Substring found!”)
else:
print(“Substring not found!”)
if “For” in text:
print(“Substring found!”)
else:
print(“Substring not found!”)
Output:
Substring found!
Substring not found!

10) Write a program to perform the given operations on a list:

A) Addition: Program:
X=5
Y=3
print(X+Y)
Output: 8

B) Insertion:Program:
fruits = [‘apple’, ‘banana’, ‘cherry’]
fruits.insert(1, “orange”)
print(fruits)
Output: [‘apple’, ‘orange’, ‘banana’, ‘cherry’]
C) Slicing :Program:
a= (“a”, “b”, “c”, “d”, “e”, “f”, “g”, “h”)
x = slice(2)
print(a[x])
Output: (‘a’, ‘b’)

12) Write a program to perform any 5 buil in function by talking


any list
A) Float: Program

x= float(3.7)

print(x)

Output: 3.0

B) Set: Program

x = set((“apple”, “banana”, “cherry”))

print(x)

# Note: the set list is unordered, so the result will display the
items in a random order.
Output: {‘banana’, ‘apple’, ‘cherry’}
C) string: Program:
x= str(‘hello’)

print(x)
Output: 3.5

D) Tuple: Program:

x= tuple((“apple”, “banana”, “cherry”))

print(x)

Output: (‘banana’, ‘cherry’, ‘apple’)

E) Boolean: Program:

X= bool(1)
print(X)

Output: True

13. Write a program to create tuples (name, age, college,


address) for at least two members and concatenate the tuples
and print the concatenated tuples?

st=((“Aman”,98,SV collage, Kadapa), (“Geet”,95,KSRM collage, Kurnool),


(“Sahil”,87,KLM collage, Hyderabad),(”pawan”,79,CBIT collage, Bangalore))
print(“Name”,”Age”,”collage”,”address”)
for i in range(0,lent(st)):

print((i+1),’\t’,st[i][0],’\’t’,st[i][1],’\t’,st[i][2])

Output:

>> Name Age collage address


>> Aman 98 SV collage kadapa
>> Geet 95 KSRM collage kurnool
>> Sahil 87 KLM collage hyderabad
>> Pawan 79 CBIT collage Bangalore

14) Write a program to count the number of vowels in a string

string = “GeekforGeeks!”
vowels = “aeiouAEIOU”

count = sum(string.count(vowel) for vowel in vowels)


print(count)
Output: 5

15) Write a program to check if a given key Exists in a dictionary or not.


def checkKey(dic, key):
if key in dic.keys():
print(“Present, “, end =” “)
print(“value =”, dic[key])
else:
print(“Not present”)

# Driver Code
dic = {‘a’: 100, ‘b’:200, ‘c’:300}
key = ‘b’
checkKey(dic, key)

key = ‘w’
checkKey(dic, key)

Output:
Present, value = 200
Not present

16) Write a program to add a new key value pair to an existing dictionary

dict = {‘key1’:’geeks’, ‘key2’:’for’}


dict[‘key3’] = ‘Geeks’
dict[‘key4’] = ‘is’
dict[‘key5’] = ‘portal’
dict[‘key6’] = ‘Computer’
print(dict)
Output:
Current Dict is: {‘key2’: ‘for’, ‘key1’: ‘geeks’} Updated Dict is: {‘key3’: ‘Geeks’,
‘key5’: ‘portal’, ‘key6’: ‘Computer’, ‘key4’: ‘is’, ‘key1’: ‘geeks’, ‘key2’: ‘for’}

17) Write a program to sum all the items in a given dictionary

# Function to print sum


def returnSum(myDict):

list = []
for i in myDict:
list.append(myDict[i])
final = sum(list)

return final

# Driver Function
dict = {‘a’: 100, ‘b’: 200, ‘c’: 300}
print(“Sum :”, returnSum(dict))
Output:
Sum:600
18) Write a program to sort words in a file and put them in another file.
The output file should have only lower-case words, so any upper-case
words from source must be lowed.

# To open the first file in write mode

f1 = open(“sample file 1.txt”, “r”)

# To open the second file in write mode

f2 = open(“sample file 2.txt”, “w”)

# For loop to traverse through the file

for line in f1:

# Writing the content of the first

# file to the second file

# Using upper() function to

# capitalize the letters

f2.write(line.upper())

Output:
19) Python program to print each line of a file in reverse order

# Open the file in write mode

f1 = open("output1.txt", "w")

# Open the input file and get

# the content into a variable data

with open("file.txt", "r") as myfile:

data = myfile.read()

# For Full Reversing we will store the

# value of data into new variable data_1

# in a reverse order using [start: end: step],

# where step when passed -1 will reverse

# the string

data_1 = data[::-1]
# Now we will write the fully reverse

# data in the output1 file using

# following command

f1.write(data_1)

f1.close()
Output
Output1.txt
!skeeg rof
SkeeG olleH

20) Python program to create, display, append, insert and reverse the
order of the items in the array

# Python program to reverse an array

fruits=[‘apple’,’banana’,’cherry’]

fruits.reverse()

print(fruits)

Output: [‘cherry’, ‘banana’,’apple’]

Insert:

list = [‘Sun’, ‘rises’, ‘in’, ‘the’, ‘east’]

list.insert(0, “The”)

print(list)
Output: [‘The’, ‘Sun’, ‘rises’, ‘in’, ‘the’, ‘east’]

Append:

cars = [“Ford”, “Volvo”, “BMW”]

cars.append(“Honda”)

print(cars)

Output: [‘Ford’, ‘Volvo’, ‘BMW’, ‘Honda’]

21) Python program to compute the number of characters, words and


lines in a file.

Import os

# Function to count number

# of characters, words, spaces

# and lines in a file

def counter(fname):

# variable to store total word count

num_words = 0

# variable to store total line count

num_lines = 0

# variable to store total character count

num_charc = 0

# variable to store total space count


num_spaces = 0

# opening file using with() method

# so that file gets closed

# after completion of work

with open(fname, ‘r’) as f:

# loop to iterate file

# line by line

for line in f:

# separating a line from \n character

# and storing again in line

line = line.strip(os.linesep)

# splitting the line

wordslist = line.split()

# incrementing value of num_lines

num_lines = num_lines + 1

# incrementing value of num_word

num_words = num_words + len(wordslist)


# incrementing value of num_char

num_charc = num_charc + sum(1 for c in line


if c not in (os.linesep, ‘ ‘))

# incrementing value of num_space

num_spaces = num_spaces + sum(1 for s in line

If s in (os.linesep, ‘ ‘))

# printing total word count

print(“Number of words in text file: “,

num_words)

# printing total line count

print(“Number of lines in text file: “,

Num_lines)

# printing total character count

print(“Number of characters in text file: “,

Num_charc)

# printing total space count

print(“Number of spaces in text file: “,

Num_spaces)
# Driver Code:

if name == ‘ main ’:

fname = ‘File1.txt’

Try:

counter(fname)

except:

print(‘File not found’)

Output:

Number of words in text file: 25

Number of lines in text file: 4

Number of characters in text file: 91

Number of spaces in text file: 21

22) Write a program to add, transport and multiply two matrices.

# Python program to multiply two matrices

def mulMat(mat1, mat2, R1, R2, C1, C2):

# List to store matrix multiplication result

rslt = [[0, 0, 0, 0],

[0, 0, 0, 0],
[0, 0, 0, 0],

[0, 0, 0, 0]]

for i in range(0, R1):

for j in range(0, C2):

for k in range(0, R2):

rslt[i][j] += mat1[i][k] * mat2[k][j]

print("Multiplication of given two matrices is:")

for i in range(0, R1):

for j in range(0, C2):

print(rslt[i][j], end=" ")

print("\n", end="")

# Driver code

if name == ' main ':

R1 = 2

R2 = 2

C1 = 2

C2 = 2

# First matrix. M is a list

mat1 = [[1, 1],


[2, 2]]

# Second matrix. N is a list

mat2 = [[1, 1],

[2, 2]]

if C1 != R2:

print("The number of columns in Matrix-1 must be equal to the number


of rows in " + "Matrix-2", end='')

print("\n", end='')

print("Please update MACROs according to your array dimension in


#define section", end='')

print("\n", end='')

else:

# Call matrix_multiplication function

mulMat(mat1, mat2, R1, R2, C1, C2)

Output:

Multiplication of given two matrices is:

3 3

6 6
23) Write a Python program to create a class that represents a shape.
Include methods to calculate its area and perimeter. Implement
subclasses for different shapes like circle, triangle, and square.

# define a function for calculating

# the area of a shapes

def calculate_area(name):\

# converting all characters

# into lower cases

Name = name.lower()

# check for the conditions

If name == “rectangle”:

L = int(input(“Enter rectangle’s length: “))

B = int(input(“Enter rectangle’s breadth: “))

# calculate area of rectangle

rect_area = l * b

print(f”The area of rectangle is

{rect_area}.”)

elif name == “square”:


s = int(input(“Enter square’s side length: “))

# calculate area of square

sqt_area = s * s

print(f”The area of square is

{sqt_area}.”)

elif name == “triangle”:

H = int(input(“Enter triangle’s height length: “))

B = int(input(“Enter triangle’s breadth length: “))

# calculate area of triangle

tri_area = 0.5 * b * h

print(f”The area of triangle is

{tri_area}.”)

elif name == “circle”:

R = int(input(“Enter circle’s radius length: “))

Pi = 3.14

# calculate area of circle

circ_area = pi * r * r

print(f”The area of circle is


{circ_area}.”)

elif name == ‘parallelogram’:

B = int(input(“Enter parallelogram’s base length: “))

H = int(input(“Enter parallelogram’s height length: “))

# calculate area of parallelogram

para_area = b * h

print(f”The area of parallelogram is

{para_area}.”)

else:

print(“Sorry! This shape is not available”)

# driver code

if name == “ main ”:

print(“Calculate Shape Area”)

shape_name = input(“Enter the name of shape whose area you want to find:
“)

# function calling

calculate_area(shape_name)
Output:

Calculate Shape Area

Enter the name of shape whose area you want to find: rectangle

Enter rectangle’s length: 10

Enter rectangle’s breadth: 15

The area of rectangle is 150.

24) Python program to check whether a JSON string contains complex


object or not.

Import json

def is_complex_num(objct):

if ‘ complex ’ in objct:

return complex(objct[‘real’], objct[‘img’])

return objct

complex_object =json.loads(‘{“ complex ”: true, “real”: 4, “img”: 5}’,


object_hook = is_complex_num)

simple_object =json.loads(‘{“real”: 4, “img”: 3}’, object_hook =


is_complex_num)

print(“Complex_object: “,complex_object)

print(“Without complex object: “,simple_object)

Output:

Complex_object: (4+5j)

Without complex object: {‘real’: 4, ‘img’: 3}


25) Python program to demonstrate numpy arrays creation using array
() function.

import numpy as np

arr = np.array([1, 2, 3, 4, 5])

print(arr)

print(type(arr))

Output:
[1 2 3 4 5]

<class ‘numpy.ndarray’>

26) python program to demonstrate use of ndim, shape, size dtype.

# Python program explaining

# numpy.ndarray.ndim() function

# importing numpy as geek

import numpy as geek

arr = geek.array([1, 2, 3, 4])

gfg = arr.ndim

print (gfg)

Output: 1
27) Python program to demonstrate basic slicing, integer and Boolean
indexing.

import numpy as np

# Create a sequence of integers from 10 to 1 with a step of -2

a = np.arange(10, 1, -2)

print(“\n A sequential array with a negative step: \n”,a)

# Indexes are specified inside the np.array method.

newarr = a[np.array([3, 1, 2 ])]

print(“\n Elements at these indices are:\n”,newarr)

Out put:

A sequential array with a negative step:

[10 8 6 4 2]

Elements at these indices are:

[4 8 6]

28) Python program to find min, max, sum, cumulative sum of array.

# Python code to get the Cumulative sum of a list

def Cumulative(lists):

cu_list = []

length = len(lists)

cu_list = [sum(lists[0:x:1]) for x in range(0, length+1)]

return cu_list[1:]
# Driver Code

lists = [10, 20, 30, 40, 50]

print (Cumulative(lists))

Output: [10, 30, 60, 100, 150]

29) Select any two columns from the above data frame, and observe
the change in one Attribute with respect to other attribute with scatter
and plot operations in matplotlib

# program to draw scatter plot using dataframe.plot

# import libraries

import pandas as pd

# prepare data

data={‘name’:[‘dhanashri’, ‘smita’, ‘rutuja’,

‘sunita’, ‘poonam’, ‘srushti’],

‘age’:[20, 18, 27, 50, 12, 15]}

# load data into dataframe

df = pd.dataframe(data = data);

# draw a scatter plot

df.plot.scatter(x = ‘name’, y = ‘age’, s = 100);


Output:

30) Create a dictionary with at least five keys and each key represent
value as a list where this list contains at least ten values and convert
this dictionary as a pandas data frame and explore the data through the
data frame as follows:

a) Apply head () function to the pandas data frame


b) Perform various data selection operations on Data Frame

# import pandas library


import pandas as pd

# dictionary with list object in values


details = {
‘Name’ : [‘Ankit’, ‘Aishwarya’, ‘Shaurya’, ‘Shivangi’],
‘Age’ : [23, 21, 22, 21],
‘University’ : [‘BHU’, ‘JNU’, ‘DU’, ‘BHU’],
}

# creating a Dataframe object


df= pd.DataFrame(details)

df

Output:

You might also like