0% found this document useful (0 votes)
27 views

Python Practial File

This program contains 8 programs that demonstrate various Python programming concepts: 1. Defines different number data types and performs arithmetic operations. 2. Takes numeric input and performs arithmetic operations. 3. Creates and manipulates strings. 4. Prints the current date and time in a specified format. 5. Demonstrates list creation, appending, and removal of elements. 6. Shows various operations on tuples like accessing elements, slicing, and packing/unpacking. 7. Covers dictionary operations like accessing, modifying, adding, removing keys and values. 8. Finds the largest of three numbers input by the user.

Uploaded by

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

Python Practial File

This program contains 8 programs that demonstrate various Python programming concepts: 1. Defines different number data types and performs arithmetic operations. 2. Takes numeric input and performs arithmetic operations. 3. Creates and manipulates strings. 4. Prints the current date and time in a specified format. 5. Demonstrates list creation, appending, and removal of elements. 6. Shows various operations on tuples like accessing elements, slicing, and packing/unpacking. 7. Covers dictionary operations like accessing, modifying, adding, removing keys and values. 8. Finds the largest of three numbers input by the user.

Uploaded by

Naim Mirza
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 45

PROGRAM – 1

AIM : WRITE A PROGRAM TO DEMONSTRATE DIFFERENT


NUMBER DATA TYPES IN PYTHON.

# Integer
x=5
print("Integer (x):", x, "Type:", type(x))

# Floating-Point Number
y = 3.14
print("Floating-Point (y):", y, "Type:", type(y))

# Complex Number
z = 2 + 3j
print("Complex (z):", z, "Type:", type(z))

# Basic Arithmetic Operations


a = 10
b=3

# Addition
addition_result = a + b
print("Addition (a + b):", addition_result)

# Subtraction
subtraction_result = a - b
print("Subtraction (a - b):", subtraction_result)

# Multiplication
multiplication_result = a * b
print("Multiplication (a * b):", multiplication_result)

# Division (float result)


division_result = a / b

1
print("Division (a / b):", division_result)

# Integer Division (floors the result)


integer_division_result = a // b
print("Integer Division (a // b):", integer_division_result)

# Modulus (remainder)
modulus_result = a % b
print("Modulus (a % b):", modulus_result)

# Exponentiation
exponentiation_result = a ** b
print("Exponentiation (a ** b):", exponentiation_result)

CONCLUSION

This program defines variables of different number data types (integer,


floating-point, and complex), performs basic arithmetic operations, and
demonstrates the results. You can run this program to see the output and
better understand how these number data types work in Python.

2
OUTPUT

3
PROGRAM – 2
AIM : WRITE A PROGRAM TO PERFORM DIFFERENT
ARITHMETIC OPERATIONS ON NUMBERS IN
PYTHON.

# Input two numbers from the user


num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

# Addition
addition_result = num1 + num2
print("Addition:", num1, "+", num2, "=", addition_result)

# Subtraction
subtraction_result = num1 - num2
print("Subtraction:", num1, "-", num2, "=", subtraction_result)

# Multiplication
multiplication_result = num1 * num2
print("Multiplication:", num1, "*", num2, "=", multiplication_result)

# Division (with error handling for division by zero)


if num2 != 0:
division_result = num1 / num2
print("Division:", num1, "/", num2, "=", division_result)
else:
print("Division by zero is not allowed.")

# Integer Division (floors the result)


if num2 != 0:
integer_division_result = num1 // num2
print("Integer Division:", num1, "//", num2, "=", integer_division_result)

4
else:
print("Integer Division by zero is not allowed.")

# Modulus (remainder)
if num2 != 0:
modulus_result = num1 % num2
print("Modulus:", num1, "%", num2, "=", modulus_result)
else:
print("Modulus by zero is not allowed.")

# Exponentiation
exponentiation_result = num1 ** num2
print("Exponentiation:", num1, "**", num2, "=", exponentiation_result)

CONCLUSION

This program takes two numbers as input from the user, performs addition,
subtraction, multiplication, division (with error handling for division by
zero), integer division, modulus, and exponentiation operations, and then
prints the results.

5
OUTPUT

6
PROGRAM – 3
AIM : WRITE A PROGRAM TO CREATE, CONCATENATE
AND PRINT A STRING AND ACCESSING SUB-STRING
FROM A GIVEN STRING.

# Create a string
string1 = "Hello, "
string2 = "World!"

# Concatenate strings
concatenated_string = string1 + string2
print("Concatenated String:", concatenated_string)

# Accessing Substrings
original_string = "This is a sample string."

# Access a substring from index 5 to 10 (exclusive)


substring1 = original_string[5:10]
print("Substring1:", substring1)

# Access a substring from the beginning to index 7 (exclusive)


substring2 = original_string[:7]
print("Substring2:", substring2)

# Access a substring from index 12 to the end


substring3 = original_string[12:]
print("Substring3:", substring3)

# Access the last character


last_char = original_string[-1]

7
print("Last Character:", last_char)

CONCLUSION

This program first creates two strings, string1 and string2, and then
concatenates them into concatenated_string. After that, it accesses
substrings from the original_string using slicing and indexing. Finally, it
prints the results.

8
OUTPUT

9
PROGRAM – 4
AIM : WRITE A PYTHON SCRIPT TO PRINT THE CURRENT
DATE IN THE FOLLOWING FORMAT “FRI OCT 11
02:26:23 IST2019”

import datetime

# Get the current date and time


current_datetime = datetime.datetime.now()

# Define the desired format


date_format = "%a, %b %d %H:%M:%S %Z %Y"

# Format and print the current date and time


formatted_date = current_datetime.strftime(date_format)
print(formatted_date)

CONCLUSION

When you run this script, it will print the current date and time in the
specified format, including the day of the week, month, day, time,
timezone, and year.

10
OUTPUT

11
PROGRAM – 5
AIM : WRITE A PROGRAM TO CREATE, APPEND, AND
REMOVE LISTS IN PYTHON.

# Create an empty list


my_list = []

# Append elements to the list


my_list.append(1)
my_list.append(2)
my_list.append(3)
my_list.append(4)

# Print the list


print("Initial List:", my_list)

# Remove an element by value


value_to_remove = 2
if value_to_remove in my_list:
my_list.remove(value_to_remove)
print("List after removing", value_to_remove, ":", my_list)

# Remove an element by index


index_to_remove = 0
if index_to_remove < len(my_list):
del my_list[index_to_remove]
print("List after removing element at index", index_to_remove, ":",
my_list)

12
CONCLUSION

In this program –

1. An empty list my_list is created.


2. Elements (1, 2, 3, and 4) are appended to the list using the append
method.
3. The initial list is printed.
4. An element (2) is removed from the list by value using the remove
method.
5. An element at a specific index (0) is removed from the list using the
del statement.

This program demonstrates how to create, append, and remove elements


from a list in Python.

13
OUTPUT

14
PROGRAM – 6
AIM : WRITE A PROGRAM TO DEMONSTRATE WORKING
WITH TUPLES IN PYTHON.

# Creating a tuple
my_tuple = (1, 2, 3, 4, 5)

# Accessing elements of a tuple


print("Tuple:", my_tuple)
print("First element:", my_tuple[0])
print("Second element:", my_tuple[1])
print("Last element:", my_tuple[-1])

# Slicing a tuple
print("Slice from index 1 to 3:", my_tuple[1:4]) # Note: The end index is
exclusive

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

# Checking if an element exists in a tuple


element_to_check = 3
if element_to_check in my_tuple:
print(element_to_check, "exists in the tuple.")
else:
print(element_to_check, "does not exist in the tuple.")

15
# Iterating through a tuple
print("Iterating through the tuple:")
for item in my_tuple:
print(item)

# Tuple packing and unpacking


tuple_packing = 10, 20, 30
print("Tuple Packing:", tuple_packing)
x, y, z = tuple_packing # Tuple Unpacking
print("Tuple Unpacking:", "x =", x, "y =", y, "z =", z)

CONCLUSION

This program covers various operations with tuples, including creating a


tuple, accessing elements, slicing, getting the length, checking for the
existence of an element, iterating through a tuple, and tuple packing and
unpacking.

16
OUTPUT

17
PROGRAM – 7
AIM : WRITE A PROGRAM TO DEMONSTRATE WORKING
WITH DICTIONARIES IN PYTHON.

# Creating a dictionary
my_dict = {
"name": "John",
"age": 30,
"city": "New York",
}

# Accessing values in a dictionary


print("Dictionary:", my_dict)
print("Name:", my_dict["name"])
print("Age:", my_dict["age"])
print("City:", my_dict["city"])

# Modifying values in a dictionary


my_dict["age"] = 31
print("Modified Age:", my_dict["age"])

# Adding a new key-value pair


my_dict["country"] = "USA"
print("Updated Dictionary:", my_dict)

18
# Checking if a key exists in a dictionary
key_to_check = "country"
if key_to_check in my_dict:
print(key_to_check, "exists in the dictionary.")
else:
print(key_to_check, "does not exist in the dictionary.")

# Removing a key-value pair


key_to_remove = "city"
if key_to_remove in my_dict:
del my_dict[key_to_remove]
print("Dictionary after removing", key_to_remove + ":", my_dict)

# Iterating through a dictionary


print("Iterating through the dictionary:")
for key, value in my_dict.items():
print(key + ":", value)

CONCLUSION

This program covers various operations with dictionaries, including


creating a dictionary, accessing values, modifying values, adding new key-
value pairs, checking for the existence of a key, removing a key-value pair,
and iterating through a dictionary.

19
OUTPUT

20
PROGRAM – 8
AIM : WRITE A PYTHON PROGRAM TO FIND LARGEST OF
THREE NUMBERS.

# Input three numbers from the user


num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))

# Find the largest number


if num1 >= num2 and num1 >= num3:
largest = num1
elif num2 >= num1 and num2 >= num3:
largest = num2
else:
largest = num3

# Print the largest number


print("The largest number among", num1, ",", num2, ", and", num3, "is",
largest)

21
CONCLUSION

In this program –

1. The user is prompted to enter three numbers.


2. The program uses conditional statements (if-elif-else) to compare
these numbers and determine which one is the largest.
3. The largest number is then printed as the output.

You can run this program and input three numbers to find the largest
among them.

22
OUTPUT

23
PROGRAM – 9
AIM : WRITE A PYTHON PROGRAM TO CONSTRUCT THE
FOLLOWING PATTERN, USING A NESTED FOR LOOP
*
**
***
****
*****
****
***
**
*

# Define the number of rows in the pattern


n=5

# Construct the top half of the pattern


for i in range(1, n + 1):
for j in range(1, i + 1):
print("*", end=" ")

24
print()

# Construct the bottom half of the pattern


for i in range(n - 1, 0, -1):
for j in range(1, i + 1):
print("*", end=" ")
print()

CONCLUSION

This program uses two nested for loops to create the pattern. The first loop
constructs the top half of the pattern, while the second loop constructs the
bottom half in reverse order. When you run this program, it will print the
pattern as specified.

25
OUTPUT

26
PROGRAM – 10
AIM : WRITE A PYTHON SCRIPT THAT PRINTS PRIME
NUMBERS LESS THAN 20.

# Function to check if a number is prime


def is_prime(num):
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
i=5
while i * i <= num:
if num % i == 0 or num % (i + 2) == 0:
return False
i += 6
return True

27
# Find and print prime numbers less than 20
print("Prime numbers less than 20:")
for i in range(2, 20):
if is_prime(i):
print(i, end=" ")

CONCLUSION

This program defines a function is_prime to check whether a number is


prime or not. Then, it iterates through numbers from 2 to 19 and prints the
prime numbers.

When you run this script, it will output the prime numbers less than 20:

28
OUTPUT

29
PROGRAM – 11
AIM : WRITE A PYTHON PROGRAM TO DEFINE A MODULE
TO FIND FIBONACCI NUMBERS AND IMPORT THE
MODULE TO ANOTHER PROGRAM.

# Function to generate Fibonacci numbers up to n terms


def generate_fibonacci(n):
fibonacci_sequence = []
a, b = 0, 1
for _ in range(n):
fibonacci_sequence.append(a)
a, b = b, a + b
return fibonacci_sequence

main_program.py (Import and use the module in another program):

# Import the Fibonacci module

30
import fibonacci_module

# Get the number of Fibonacci terms from the user


n = int(input("Enter the number of Fibonacci terms to generate: "))

# Use the module function to generate Fibonacci numbers


fibonacci_sequence = fibonacci_module.generate_fibonacci(n)

# Print the Fibonacci sequence


print("Fibonacci sequence up to", n, "terms:")
print(fibonacci_sequence)

CONCLUSION

In this setup, the fibonacci_module module contains a function


generate_fibonacci that generates Fibonacci numbers up to a specified
number of terms. The main_program imports this module and uses the
generate_fibonacci function to compute and print the Fibonacci sequence.

When you run main_program.py and input the number of Fibonacci terms,
it will import the fibonacci_module and display the Fibonacci sequence.

31
OUTPUT

32
PROGRAM – 12
AIM : WRITE A PYTHON PROGRAM TO DEFINE A MODULE
AND IMPORT A SPECIFIC FUNCTION IN THAT
MODULE TO ANOTHER PROGRAM.

# Function to calculate the square of a number


def calculate_square(number):
return number ** 2

# Function to calculate the cube of a number


def calculate_cube(number):
return number ** 3

main_program.py (Import a specific function from the module into


another program):

33
# Import a specific function from the module
from my_module import calculate_square

# Get a number from the user


number = float(input("Enter a number: "))

# Use the imported function to calculate the square


result = calculate_square(number)

# Print the result


print("Square of", number, "is", result)

CONCLUSION

In this example, we've created a module called my_module with two


functions: calculate_square and

1. Calculate_cube. In the main_program, we import only the


2. Calculate_square function from the module and use it to calculate the
square of a number entered by the user.

When you run main_program.py, it will import the specific function and
display the square of the entered number.

34
OUTPUT

35
PROGRAM – 13
AIM : WRITE A PROGRAM THAT INPUTS A TEXT FILE.
THE PROGRAM SHOULD PRINT ALL OF THE
UNIQUE WORDS IN THE FILE IN ALPHABETICAL
ORDER.

# Function to extract unique words from a text file and print them in
alphabetical order
def extract_and_print_unique_words(file_path):
unique_words = set() # Using a set to store unique words

try:
with open(file_path, 'r') as file:
# Read each line from the file

36
for line in file:
# Split the line into words
words = line.split()

# Add unique words to the set for word in words:


unique_words.add(word.strip())

# Print unique words in alphabetical order


sorted_words = sorted(unique_words)
for word in sorted_words:
print(word)

except FileNotFoundError:
print(f"The file '{file_path}' was not found.")

# Input the file path from the user


file_path = input("Enter the path of the text file: ")

# Call the function to extract and print unique words


extract_and_print_unique_words(file_path)

CONCLUSION

In this program –

1. The extract_and_print_unique_words function reads the specified text


file line by line, splits each line into words, and adds unique words to
a set.
2. After reading the file, it sorts the unique words alphabetically.
3. The program then takes the file path as input from the user and calls
the extract_and_print_unique_words function to perform the desired
task.

37
Ensure that you have a text file with the content you want to analyze, and
provide its path when prompted.

When you run this program and input the file path, it will print all unique
words from the file in alphabetical order.

OUTPUT

38
PROGRAM – 14
AIM : WRITE A PYTHON CLASS TO CONVERT AN INTEGER
TO A ROMAN NUMERAL.

39
class IntegerToRoman:
def int_to_roman(self, num):
val = [
1000, 900, 500, 400,
100, 90, 50, 40,
10, 9, 5, 4, 1
]
syms = [
"M", "CM", "D", "CD",
"C", "XC", "L", "XL",
"X", "IX", "V", "IV",
"I"
]
roman_numeral = ''
i=0
while num > 0:
for _ in range(num // val[i]):
roman_numeral += syms[i]
num -= val[i]
i += 1
return roman_numeral

# Create an instance of the class


converter = IntegerToRoman()

# Example usage
number = 1994
roman_numeral = converter.int_to_roman(number)
print(f"{number} in Roman numerals is: {roman_numeral}")

CONCLUSION

40
In this code –

1. The IntegerToRoman class defines a method called int_to_roman,


which takes an integer as input and converts it to a Roman numeral.

2. It uses two lists, val and syms, to store the values and symbols of
Roman numerals.

3. The method iterates through the values in val and adds the
corresponding symbols from syms to the roman_numeral string while
subtracting the value from the input number until the number
becomes zero.

4. An instance of the class is created, and the int_to_roman method is


used to convert an example number (1994) to a Roman numeral.

When you run this program, it will print:

OUTPUT

41
PROGRAM – 15

42
AIM : WRITE A PYTHON CLASS TO REVERSE A STRING
WORD BY WORD.

class StringReverser:
def reverse_words(self, s):
# Split the input string into words
words = s.split()

# Reverse the words and join them back into a string


reversed_string = ' '.join(reversed(words))

return reversed_string

# Create an instance of the class


reverser = StringReverser()

# Example usage
input_string = "Hello World"
reversed_string = reverser.reverse_words(input_string)
print(f"Original string: {input_string}")
print(f"Reversed string: {reversed_string}")

CONCLUSION

43
In this code –

1. The StringReverser class defines a method called reverse_words,


which takes a string as input and reverses it word by word.

2. The input string is split into words using the split method.

3. The reversed function is used to reverse the order of the words.

4. The reversed words are joined back into a string with spaces between
them.

5. An instance of the class is created, and the reverse_words method is


used to reverse an example input string ("Hello World").

When you run this program, it will print:

OUTPUT

44
45

You might also like