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

Python File

This document is a practical file for the Programming in Python course at the Institute of Technology & Management, Gwalior, detailing various programming experiments. It includes a list of 20 experiments covering topics such as data types, arithmetic operations, string manipulation, lists, tuples, dictionaries, and the use of libraries like Numpy and Pandas. Each experiment contains a brief description, the corresponding Python program, and expected output.

Uploaded by

surbhitiwarihfn
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 views30 pages

Python File

This document is a practical file for the Programming in Python course at the Institute of Technology & Management, Gwalior, detailing various programming experiments. It includes a list of 20 experiments covering topics such as data types, arithmetic operations, string manipulation, lists, tuples, dictionaries, and the use of libraries like Numpy and Pandas. Each experiment contains a brief description, the corresponding Python program, and expected output.

Uploaded by

surbhitiwarihfn
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

Institute of Technology & Management, Gwalior

Department of Information Technology

Practical File

Subject Name: Programming in Python

Subject Code: IT-605

Year/Semester: 3rd Year, VI Sem

Submitted to: Submitted by:


Dr. Jitendra Singh Kushwah Surbhi Tiwari
Associate Professor 0905IT221144
Department of IT, ITM Gwalior
Institute of Technology & Management, Gwalior
Department of Information Technology

INDEX

S.No Name of Experiment Date Signature

1. Write a program to demonstrate different number


data types in Python.
2. Write a program to perform different Arithmetic
Operations on numbers in Python.
3. Write a program to create, concatenate, and print a
string and access a substring from a given string.
4. Write a program to create, append, and remove lists
in Python.
5. Write a program to demonstrate working with tuples
in Python.
6. Write a program to demonstrate working with
dictionaries in Python.
7. Write a Python program to find the largest of three
numbers.
8. Write a Python program to convert temperatures to
and from Celsius and Fahrenheit. [Formula: c/5 = f-
32/9]
9. Write a Python program to construct the stars (*)
pattern, using a nested for loop on
10. Write a Python script that prints prime numbers less
than 20.

11. Write a Python program to find the factorial of a


number using Recursion.
12. Using a Numpy module, create an array and check the
following: 1. Type of array 2. Axes of array 3. Shape of
array 4. Type of elements in the array
13. Write a Python program using a Numpy module to
create an array and check the following: 1. A List with
type float 2. A 3*4 array with all zeros 3. From tuple 4.
Random values
14. Write a Python program to concatenate the
dataframes with two different objects.
15. Write a Python program to read a CSV file using the
Pandas module and print the first and last five lines of
the file.
16. Write a Python program to take user input for a list of
numbers, sort the list in ascending order, and print
the sorted list.
17. Write a Python program to define a student class with
attributes like name, age, and grade, and create
objects to display their details.
18. Write a Python function that checks whether a given
number is a palindrome.
19. Write a Python script to find the sum and average of
elements in a list.
20. Write a Python program to remove all duplicates from
a list using a set.
Experiment 1

Write a program to demonstrate different number data types in


Python.
Program: -

int_num = 10

float_num = 10.5

complex_num = 3 + 4j

print("Integer:", int_num)

print("Float:", float_num)

print("Complex:", complex_num)

Output: -
Experiment 2

Write a program to perform different Arithmetic Operations on


numbers in Python.

Program: -

a = 15

b=4

print("Addition:", a + b)

print("Subtraction:", a - b)

print("Multiplication:", a * b)

print("Division:", a / b)

print("Floor Division:", a // b)

print("Modulus:", a % b)

print("Exponent:", a ** b)

Output: -
Experiment 3

Write a program to create, concatenate, and print a string and


access a substring from a given string.

Program: -

str1 = "Hello"

str2 = "World"

concat = str1 + " " + str2

print("Concatenated String:", concat)

print("Substring:", concat[0:5])

Output: -
Experiment 4

Write a program to create, append, and remove lists in Python.

Program: -

my_list = [1, 2, 3]

my_list.append(4)

print("After append:", my_list)

my_list.remove(2)

print("After remove:", my_list)

Output: -
Experiment 5

Write a program to demonstrate working with tuples in Python.

Program: -

# Demonstration of Tuples in Python

# Creating a tuple

my_tuple = ("apple", "banana", "cherry", "date")

# Accessing elements

print("First element:", my_tuple[0])

print("Last element:", my_tuple[-1])

# Slicing a tuple

print("Sliced tuple (2nd to 3rd element):", my_tuple[1:3])

# Iterating through a tuple

print("Iterating through the tuple:")

for fruit in my_tuple:

print(fruit)
# Tuple length

print("Length of the tuple:", len(my_tuple))

# Tuple with mixed data types

mixed_tuple = (1, "hello", 3.14, True)

print("Mixed data types tuple:", mixed_tuple)

# Nesting tuples

nested_tuple = ("Python", (1, 2, 3))

print("Nested tuple:", nested_tuple)

# Tuple concatenation

tuple1 = (1, 2)

tuple2 = (3, 4)

combined = tuple1 + tuple2

print("Concatenated tuple:", combined)

# Tuple repetition

repeated = tuple1 * 3

print("Repeated tuple:", repeated)


# Checking existence of an item

if "banana" in my_tuple:

print("'banana' is in the tuple")

# Tuple immutability demonstration (this will raise an error if


uncommented)

# my_tuple[0] = "orange" # Tuples are immutable!

Output: -
Experiment 6

Write a program to demonstrate working with dictionaries in


Python.

Program: -

# Demonstration of Dictionaries in Python

# Creating a dictionary

student = {

"name": "Alice",

"age": 21,

"major": "Computer Science"

# Accessing values

print("Student's name:", student["name"])

print("Student's age:", student.get("age")) # safer way to access keys


# Adding a new key-value pair

student["year"] = "Final"

print("Updated dictionary with year:", student)

# Updating an existing value

student["age"] = 22

print("Updated age:", student)

# Deleting a key-value pair

del student["major"]

print("Dictionary after deleting 'major':", student)

# Iterating through keys and values

print("\nIterating through dictionary:")

for key, value in student.items():

print(f"{key}: {value}")
# Dictionary length

print("\nTotal items in dictionary:", len(student))

# Checking if a key exists

if "name" in student:

print("Key 'name' exists in the dictionary")

# Using a dictionary with different data types as values

person = {

"name": "Bob",

"age": 30,

"skills": ["Python", "Java", "C++"], # list as a value

"address": {

"city": "New York",

"zip": "10001"

} # nested dictionary

}
print("\nPerson's skills:", person["skills"])

print("Person's city:", person["address"]["city"])

# Clearing the dictionary

student.clear()

print("\nCleared student dictionary:", student)

Output: -
Experiment 7

Write a Python program to find the largest of three numbers.

Program: -

num1 = 45

num2 = 78

num3 = 66

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: -
Experiment 8

Write a Python program to convert temperatures to and from


Celsius and Fahrenheit. [Formula: c/5 = f-32/9]

Program: -

def c_to_f(c):

return (c * 9/5) + 32

def f_to_c(f):

return (f - 32) * 5/9

print("25C to F:", c_to_f(25))

print("77F to C:", f_to_c(77))

Output: -
Experiment 9

Write a Python program to construct the stars (*) pattern, using a


nested for loop on

Program: -

for i in range(1, 6):

for j in range(i):

print("*", end="")

print()

Output: -
Experiment 10

Write a Python script that prints prime numbers less than 20.

Program: -

for num in range(2, 20):

for i in range(2, num):

if num % i == 0:

break

else:

print(num, end=" ")

print()

Output: -
Experiment 11

Write a Python program to find the factorial of a number using


Recursion.

Program: -

def factorial(n):

if n == 0 or n == 1:

return 1

else:

return n * factorial(n - 1)

num = 6

result = factorial(num)

print(f"Factorial of {num} is {result}")

Output: -
Experiment 12

Using the Numpy module, create an array and check the following:
1. Type of array 2. Axes of array 3. Shape of array 4. Type of
elements in the array

Program: -

import numpy as np

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

print("Array type:", type(arr))

print("Array axes:", arr.ndim)

print("Array shape:", arr.shape)

print("Element type:", arr.dtype)

Output: -
Experiment 13

Write a Python program using the Numpy module to create an


array and check the following:
1. A List with type float 2. A 3*4 array with all zeros 3. From tuple 4.
Random values

Program: -

import numpy as np

# 1. Create an array from a list with type float

float_list = [1, 2, 3, 4]

float_array = np.array(float_list, dtype=float)

print("1. Array from list with float type:")

print(float_array)

print("Data type:", float_array.dtype, "\n")

# 2. Create a 3x4 array with all zeros

zeros_array = np.zeros((3, 4))

print("2. 3x4 array with all zeros:")

print(zeros_array, "\n")

# 3. Create an array from a tuple

tuple_data = (5, 6, 7)
tuple_array = np.array(tuple_data)

print("3. Array from tuple:")

print(tuple_array)

print("Data type:", tuple_array.dtype, "\n")

# 4. Create an array with random values

random_array = np.random.rand(2, 3)

print("4. Array with random values (2x3):")

print(random_array)

Output: -
Experiment 14

Write a Python program to concatenate the dataframes with two


different objects

Program: -

import pandas as pd

df1 = pd.DataFrame({"A": [1, 2], "B": [3, 4]})

df2 = pd.DataFrame({"A": [5, 6], "B": [7, 8]})

result = pd.concat([df1, df2])

print("Concatenated DataFrame:\n", result)

Output: -
Experiment 15

Write a Python program to read a CSV file using the Pandas module
and print the first and last five lines of the file.

Program: -

import pandas as pd

# Replace 'your_file.csv' with the actual path to your CSV file

file_path = 'your_file.csv'

# Read the CSV file

data = pd.read_csv(file_path)

# Print the first five rows

print("First five lines of the CSV file:")

print(data.head())

print("\nLast five lines of the CSV file:")

print(data.tail())
Output: -
Experiment 16

Write a Python program to take user input for a list of numbers,


sort the list in ascending order, and print the sorted list.

Program: -

input_str = input("Enter numbers separated by spaces: ")

num_list = list(map(int, input_str.split()))

num_list.sort()

print("Sorted list in ascending order:")

print(num_list)

Output: -
Experiment 17

Write a Python program to define a student class with attributes


like name, age, and grade, and create objects to display their
details.

Program: -

class Student:

def __init__(self, name, age, grade):

self.name = name

self.age = age

self.grade = grade

def display(self):

print(f"Name: {self.name}, Age: {self.age}, Grade: {self.grade}")

s1 = Student("Alice", 20, "A")

s1.display()

Output: -
Experiment 18

Write a Python function that checks whether a given number is a


palindrome.

Program: -

def is_palindrome(number):

str_num = str(number)

return str_num == str_num[::-1]

num = 121

if is_palindrome(num):

print(f"{num} is a palindrome.")

else:

print(f"{num} is not a palindrome.")

Output: -
Experiment 19

Write a Python script to find the sum and average of elements in a


list.

Program: -

lst = [10, 20, 30, 40]

sum_lst = sum(lst)

avg_lst = sum_lst / len(lst)

print("Sum:", sum_lst, "Average:", avg_lst)

Output: -
Experiment 20

Write a Python program to remove all duplicates from a list using a


set.

Program: -

dup_list = [1, 2, 2, 3, 4, 4, 5]

unique_list = list(set(dup_list))

print("List without duplicates:", unique_list)

Output: -

You might also like