INDEX
Python
1. Write a program to demonstrate different numbers data types in python.
2. Write a python program to design simple calculator using functions.
3. Write a python program to check whether a given number is Armstrong
number or no
4. Write a python program to generate prime numbers between different
intervals.
5. Write a python program to find factorial of a number using recursion.
6. Write a python program to check whether a string is palindrome or not.
7. Write a python program to count the number of characters present in a
word.
8. Write a python program to create, append and remove lists.
9. Write a program to demonstrate working with tuples in python.
10. Write a program to demonstrate dictionaries in python.
Numpy
11. Python program to demonstrate basic array
characteristics
12. Python program to demonstrate array creation
techniques
13. Python program to demonstrate indexing in numpy
14. Python program to demonstrate basic operations on
single array
15. Python program to demonstrate unary operators in
numpy
Pandas
16. Python code demonstrate to make a Pandas DataFrame
with two-dimensional list
17. Python code demonstrate creating DataFrame from
dictionary of narray and lists
18. Python code demonstrate creating a Pandas dataframe
using list of tuples .
19 Python code demonstrate how to iterate over rows in
Pandas Dataframe
20. Python code demonstrate how to get column names in
Pandas dataframe
PYTHON
1.Write a program to demonstrate different numbers data types in python.
a=5
print(a, "is of type", type(a))
a = 2.0
print(a, "is of type", type(a))
a = 1+2j
print(a, "is complex number?", isinstance(1+2j,complex))
Output:-
5 is of type <class 'int'>
2.0 is of type <class 'float'>
(1+2j) is complex number? True
2. Write a python program to design simple calculator using functions
# Function to add two numbers
def add(x, y):
return x + y
# Function to subtract two numbers
def subtract(x, y):
return x - y
# Function to multiply two numbers
def multiply(x, y):
return x * y
# Function to divide two numbers
def divide(x, y):
if y == 0:
return "Cannot divide by zero"
else:
return x / y
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
# Take input from the user
choice = input("Enter choice (1/2/3/4): ")
# Check if choice is one of the four options
if choice in ('1', '2', '3', '4'):
# Take input from the user for two numbers
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print("Result:", add(num1, num2))
elif choice == '2':
print("Result:", subtract(num1, num2))
elif choice == '3':
print("Result:", multiply(num1, num2))
elif choice == '4':
print("Result:", divide(num1, num2))
else:
print("Invalid input")
Output:-
Select operation:
1. Add
2. Subtract
3. Multiply
4. Divide
Enter choice (1/2/3/4): 3
Enter first number: 5
Enter second number: 3
Result: 15.0
3.Write a python program to check whether a given number is Armstrong
number or not.
def is_armstrong(number):
# Count the number of digits
num_digits = len(str(number))
# Initialize sum
armstrong_sum = 0
# Temporary variable to store original number
temp = number
while temp > 0:
digit = temp % 10
armstrong_sum += digit ** num_digits
temp //= 10
# Check if the given number is Armstrong
if number == armstrong_sum:
return True
else:
return False
# Take input from the user
number = int(input("Enter a number: "))
# Check if the number is Armstrong or not
if is_armstrong(number):
print(number, "is an Armstrong number")
else:
print(number, "is not an Armstrong number")
Output:-
Enter a number: 153
153 is an Armstrong number.
4.Write a python program to generate prime numbers between different
intervals
def generate_primes(start, end):
primes = []
for num in range(start, end + 1):
if num > 1:
for i in range(2, int(num ** 0.5) + 1):
if (num % i) == 0:
break
else:
primes.append(num)
return primes
# Take input from the user for the interval
start = int(input("Enter the start of the interval: "))
end = int(input("Enter the end of the interval: "))
# Generate prime numbers within the interval
prime_numbers = generate_primes(start, end)
# Print the prime numbers
if prime_numbers:
print("Prime numbers between", start, "and", end, "are:", prime_numbers)
else:
print("There are no prime numbers between", start, "and", end)
Output:-
Enter the start of the interval: 10
Enter the end of the interval: 50
Prime numbers between 10 and 50 are: [11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
5. Write a python program to find factorial of a number using recursion.
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
# Take input from the user
number = int(input("Enter a number: "))
# Check if the number is negative
if number < 0:
print("Factorial is not defined for negative numbers")
else:
# Calculate the factorial using recursion
result = factorial(number)
print("Factorial of", number, "is:", result)
Output:-
Enter a number: 5
Factorial of 5 is: 120
6.Write a python program to check whether a string is palindrome or not .
def is_palindrome(s):
# Remove spaces and convert to lowercase
s = s.replace(" ", "").lower()
# Compare the string with its reverse
return s == s[::-1]
# Take input from the user
string = input("Enter a string: ")
# Check if the string is a palindrome
if is_palindrome(string):
print("The string is a palindrome")
else:
print("The string is not a palindrome")
Output:-
Enter a string: katak
The string is a palindrome
7. Write a python program to count the number of characters present in a word.
# Take input from the user
word = input("Enter a word: ")
# Count the number of characters in the word
count = 0
for char in word:
count += 1
# Print the result
print("The word", word, "contains", count, "characters.")
Output:-
Enter a word: Katak
The word Katak contains 5 characters.
8.Write a python program to create, append and remove lists.
# Create a list with initial elements
my_list = [10, 20, 30, 40, 50]
print("Initial list:", my_list)
# Append an element to the list
my_list.append(60)
print("List after appending element 60:", my_list)
# Remove an element from the list
my_list.remove(30)
print("List after removing element 30:", my_list)
# Remove the last element from the list
removed_element = my_list.pop()
print("Removed element from the list:", removed_element)
print("List after removing the last element:", my_list)
Output:-
Initial list: [10, 20, 30, 40, 50]
List after appending element 60: [10, 20, 30, 40, 50, 60]
List after removing element 30: [10, 20, 40, 50, 60]
Removed element from the list: 60
List after removing the last element: [10, 20, 40, 50]
9.Write a program to demonstrate working with tuples in python.
# Create a tuple
my_tuple = (1, 2, 3, 4, 5)
print("Original Tuple:", my_tuple)
# Accessing elements of a tuple
print("First element:", my_tuple[0])
print("Last element:", my_tuple[-1])
# Slicing a tuple
print("Slice of tuple:", my_tuple[1:4])
# Length of a tuple
print("Length of tuple:", len(my_tuple))
# Concatenating tuples
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
concatenated_tuple = tuple1 + tuple2
print("Concatenated tuple:", concatenated_tuple)
# Repeating elements of a tuple
repeated_tuple = tuple1 * 3
print("Repeated tuple:", repeated_tuple)
# Check if an element exists in a tuple
print("Is 3 in the tuple?", 3 in my_tuple)
# Iterate through a tuple
print("Elements of the tuple:")
for item in my_tuple:
print(item)
# Convert a tuple to a list
tuple_to_list = list(my_tuple)
print("Tuple converted to list:", tuple_to_list)
# Convert a list to a tuple
list_to_tuple = tuple(tuple_to_list)
print("List converted to tuple:", list_to_tuple)
Output:-
Original Tuple: (1, 2, 3, 4, 5)
First element: 1
Last element: 5
Slice of tuple: (2, 3, 4)
Length of tuple: 5
Concatenated tuple: (1, 2, 3, 4, 5, 6)
Repeated tuple: (1, 2, 3, 1, 2, 3, 1, 2, 3)
Is 3 in the tuple? True
Elements of the tuple:
1
2
Tuple converted to list: [1, 2, 3, 4, 5]
List converted to tuple: (1, 2, 3, 4, 5)
10.Write a program to demonstrate dictionaries in python .
# Create a dictionary
my_dict = {"apple": 2, "banana": 3, "orange": 4}
print("Original Dictionary:", my_dict)
# Accessing elements of a dictionary
print("Value of 'apple':", my_dict["apple"])
# Adding a new key-value pair
my_dict["grape"] = 5
print("Dictionary after adding 'grape':", my_dict)
# Modifying the value of an existing key
my_dict["banana"] = 6
print("Dictionary after modifying 'banana':", my_dict)
# Removing a key-value pair
del my_dict["orange"]
print("Dictionary after removing 'orange':", my_dict)
# Check if a key exists in the dictionary
print("Is 'apple' in the dictionary?", "apple" in my_dict)
# Iterate through a dictionary
print("Key-value pairs in the dictionary:")
for key, value in my_dict.items():
print(key, ":", value)
# Get the keys of the dictionary
print("Keys of the dictionary:", my_dict.keys())
# Get the values of the dictionary
print("Values of the dictionary:", my_dict.values())
# Get the length of the dictionary
print("Length of the dictionary:", len(my_dict))
# Clear the dictionary
my_dict.clear()
print("Dictionary after clearing:", my_dict)
Output:-
Original Dictionary: {'apple': 2, 'banana': 3, 'orange': 4}
Value of 'apple': 2
Dictionary after adding 'grape': {'apple': 2, 'banana': 3, 'orange': 4, 'grape': 5}
Dictionary after modifying 'banana': {'apple': 2, 'banana': 6, 'orange': 4, 'grape': 5}
Dictionary after removing 'orange': {'apple': 2, 'banana': 6, 'grape': 5}
Is 'apple' in the dictionary? True
Key-value pairs in the dictionary:
apple : 2
banana : 6
grape : 5
Keys of the dictionary: dict_keys(['apple', 'banana', 'grape'])
Values of the dictionary: dict_values([2, 6, 5])
Length of the dictionary: 3
Dictionary after clearing: {}
Numpy
11. Python program to demonstrate basic array characteristics.
import numpy as np
# Create a 1D array
arr1d = np.array([1, 2, 3, 4, 5])
print("1D Array:", arr1d)
# Create a 2D array
arr2d = np.array([[1, 2, 3], [4, 5, 6]])
print("\n2D Array:")
print(arr2d)
# Print shape of arrays
print("\nShape of 1D Array:", arr1d.shape)
print("Shape of 2D Array:", arr2d.shape)
# Print dimensions of arrays
print("\nDimensions of 1D Array:", arr1d.ndim)
print("Dimensions of 2D Array:", arr2d.ndim)
# Print size of arrays
print("\nSize of 1D Array:", arr1d.size)
print("Size of 2D Array:", arr2d.size)
# Print data type of arrays
print("\nData type of 1D Array:", arr1d.dtype)
print("Data type of 2D Array:", arr2d.dtype)
This program creates a NumPy array and prints out its characteristics such as type, shape, dimension,
size, and data type of its elements.
Output:-
1D Array: [1 2 3 4 5]
2D Array:
[[1 2 3]
[4 5 6]]
Shape of 1D Array: (5,)
Shape of 2D Array: (2, 3)
Dimensions of 1D Array: 1
Dimensions of 2D Array: 2
Size of 1D Array: 5
Size of 2D Array: 6
Data type of 1D Array: int64
Data type of 2D Array: int64
12. Python program to demonstrate array creation techniques
import numpy as np
# Technique 1: Creating an array from a list
arr1 = np.array([1, 2, 3, 4, 5])
# Technique 2: Creating an array of zeros
arr2 = np.zeros((2, 3)) # 2 rows, 3 columns
# Technique 3: Creating an array of ones
arr3 = np.ones((3, 2)) # 3 rows, 2 columns
# Technique 4: Creating an empty array
arr4 = np.empty((2, 2)) # 2 rows, 2 columns
# Technique 5: Creating an array with a range of values
arr5 = np.arange(0, 10, 2) # Start at 0, stop at 10 (exclusive), step by 2
# Technique 6: Creating an array with evenly spaced values
arr6 = np.linspace(0, 5, 10) # Start at 0, stop at 5 (inclusive), with 10 equally spaced values
# Printing arrays created using different techniques
print("Array 1 (from a list):", arr1)
print("Array 2 (Zeros):", arr2)
print("Array 3 (Ones):", arr3)
print("Array 4 (Empty):", arr4)
print("Array 5 (Arange):", arr5)
print("Array 6 (Linspace):", arr6)
This program showcases various techniques for creating arrays in NumPy, such as creating arrays from
lists, creating arrays filled with zeros or ones, creating empty arrays, creating arrays with a range of
values, and creating arrays with evenly spaced values.
Output:-
Array 1 (from a list): [1 2 3 4 5]
Array 2 (Zeros):
[[0. 0. 0.]
[0. 0. 0.]]
Array 3 (Ones):
[[1. 1.]
[1. 1.]
[1. 1.]]
Array 4 (Empty):
[[4.9e-324 9.9e-324]
[1.5e-323 2.0e-323]]
Array 5 (Arange): [0 2 4 6 8]
Array 6 (Linspace): [0. 0.55555556 1.11111111 1.66666667 2.22222222
2.77777778
3.33333333 3.88888889 4.44444444 5. ]
13. Python program to demonstrate indexing in numpy.
import numpy as np
# Create a NumPy array
arr = np.array([[10, 20, 30, 40],
[50, 60, 70, 80],
[90, 100, 110, 120]])
# Accessing individual elements
print("Element at (0,0):", arr[0, 0]) # Output: 10
print("Element at (2,3):", arr[2, 3]) # Output: 120
# Accessing entire rows or columns
print("Second row:", arr[1]) # Output: [50 60 70 80]
print("Third column:", arr[:, 2]) # Output: [ 30 70 110]
# Slicing
print("Slice of the array:")
print(arr[1:, 1:3]) # Output: [[ 60 70] [100 110]]
Output:-
Element at (0,0): 10
Element at (2,3): 120
Second row: [50 60 70 80]
Third column: [ 30 70 110]
Slice of the array:
[[ 60 70]
[100 110]]
14. Python program to demonstrate basic operations on single array.
import numpy as np
# Create a NumPy array
arr = np.array([1, 2, 3, 4, 5])
# Print the original array
print("Original array:", arr)
# Basic operations
print("Sum of elements:", np.sum(arr)) # Output: 15
print("Minimum element:", np.min(arr)) # Output: 1
print("Maximum element:", np.max(arr)) # Output: 5
print("Mean of elements:", np.mean(arr)) # Output: 3.0
# Scalar operations
scalar = 2
print("Original array multiplied by", scalar, ":", arr * scalar) # Output: [ 2 4 6 8 10]
print("Original array added by", scalar, ":", arr + scalar) # Output: [3 4 5 6 7]
Note:- This program achieves basic operations such as sum, minimum, maximum, and mean using
NumPy functions and also demonstrates scalar operations like multiplication and addition.
Output:-
Original array: [1 2 3 4 5]
Sum of elements: 15
Minimum element: 1
Maximum element: 5
Mean of elements: 3.0
Original array multiplied by 2 : [ 2 4 6 8 10]
Original array added by 2 : [3 4 5 6 7]
15. Python program to demonstrate unary operators in numpy.
import numpy as np
# Create a NumPy array
arr = np.array([1, 2, 3, 4, 5])
# Print the original array
print("Original array:", arr)
# Unary operators
print("Negative values:", np.negative(arr)) # Output: [-1 -2 -3 -4 -5]
print("Reciprocal values:", np.reciprocal(arr.astype(float))) # Output: [1. 0.5 0.33333333 0.25
0.2 ]
print("Square values:", np.square(arr)) # Output: [ 1 4 9 16 25]
print("Sign values:", np.sign(arr - 3)) # Output: [-1 -1 0 1 1]
Note:- This program demonstrates unary operators like negation, reciprocal,
squaring, and sign using NumPy functions on a NumPy array.
Output:-
Original array: [1 2 3 4 5]
Negative values: [-1 -2 -3 -4 -5]
Reciprocal values: [1. 0.5 0.33333333 0.25 0.2 ]
Square values: [ 1 4 9 16 25]
Sign values: [-1 -1 0 1 1]
Pandas
16. Python code demonstrate to make a Pandas DataFrame with two-
dimensional list .
import pandas as pd
# Two-dimensional list
data = [[1, 'Alice', 25],
[2, 'Bob', 30],
[3, 'Charlie', 35],
[4, 'David', 40]]
# Define column names
columns = ['ID', 'Name', 'Age']
# Create DataFrame
df = pd.DataFrame(data, columns=columns)
# Print the DataFrame
print(df)
Note:- This code creates a Pandas DataFrame from the two-dimensional list data and specifies the
column names using the columns parameter. Finally, it prints the DataFrame.
Output:-
ID Name Age
0 1 Alice 25
1 2 Bob 30
2 3 Charlie 35
3 4 David 40
17. Python code demonstrate creating DataFrame from dictionary of narray and
lists.
import pandas as pd
import numpy as np
# Dictionary with NumPy arrays and lists
data = {'A': np.array([1, 2, 3, 4]),
'B': [5, 6, 7, 8],
'C': np.array(['a', 'b', 'c', 'd'])}
# Create DataFrame
df = pd.DataFrame(data)
# Print the DataFrame
print(df)
Note:-This code creates a Pandas DataFrame from the dictionary data, where the keys represent column
names and the values are NumPy arrays or lists. It then prints the resulting DataFrame.
Output:-
A B C
0 1 5 a
1 2 6 b
2 3 7 c
3 4 8 d
18. Python code demonstrate creating a Pandas dataframe using list of tuples .
import pandas as pd
# List of tuples
data = [(1, 'Alice', 25),
(2, 'Bob', 30),
(3, 'Charlie', 35),
(4, 'David', 40)]
# Define column names
columns = ['ID', 'Name', 'Age']
# Create DataFrame
df = pd.DataFrame(data, columns=columns)
# Print the DataFrame
print(df)
Note:- This code creates a Pandas DataFrame from the list of tuples data and specifies the column
names using the columns parameter. Finally, it prints the DataFrame.
It displays a Pandas DataFrame with columns 'ID', 'Name', and 'Age', populated with the corresponding
data from the list of tuples.
Output:-
ID Name Age
0 1 Alice 25
1 2 Bob 30
2 3 Charlie 35
3 4 David 40
19.Python code demonstrate how to iterate over rows in Pandas Dataframe.
import pandas as pd
# Create a Pandas DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie', 'David'],
'Age': [25, 30, 35, 40]}
df = pd.DataFrame(data)
# Iterate over rows
for index, row in df.iterrows():
print("Index:", index)
print("Name:", row['Name'])
print("Age:", row['Age'])
print()
Note:- This code creates a simple Pandas DataFrame and then iterates over its rows using the iterrows()
function. Inside the loop, it prints the index of the row and the values of each column for that row.
It displays the index, name, and age of each row in the Pandas DataFrame.
Output:-
Index: 0
Name: Alice
Age: 25
Index: 1
Name: Bob
Age: 30
Index: 2
Name: Charlie
Age: 35
Index: 3
Name: David
Age: 40
20. Python code demonstrate how to get column names in Pandas dataframe.
import pandas as pd
# Create a Pandas DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie', 'David'],
'Age': [25, 30, 35, 40]}
df = pd.DataFrame(data)
# Get column names
column_names = df.columns
# Print column names
print("Column names:")
for column in column_names:
print(column)
Note:- This code creates a simple Pandas DataFrame and then retrieves the column names using the
columns attribute. It then iterates over the column names and prints each one.
It displays the column names of the Pandas DataFrame: "Name" and "Age".
Output:-
Column names:
Name
Age