[go: up one dir, main page]

0% found this document useful (0 votes)
246 views42 pages

PYTHON PRACTIAL FILE - Aman

This document contains 9 Python programs with different aims: 1. Demonstrates different number data types and arithmetic operations. 2. Performs arithmetic operations on user-input numbers. 3. Creates, concatenates, and accesses substrings of strings. 4. Prints the current date and time in a specific format. 5. Creates, appends to, and removes from lists. 6. Demonstrates operations on tuples like accessing elements, slicing, and unpacking. 7. Demonstrates operations on dictionaries like accessing, modifying, adding, and removing key-value pairs. 8. Finds the largest of three user-input numbers. 9

Uploaded by

Naim Mirza
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
246 views42 pages

PYTHON PRACTIAL FILE - Aman

This document contains 9 Python programs with different aims: 1. Demonstrates different number data types and arithmetic operations. 2. Performs arithmetic operations on user-input numbers. 3. Creates, concatenates, and accesses substrings of strings. 4. Prints the current date and time in a specific format. 5. Creates, appends to, and removes from lists. 6. Demonstrates operations on tuples like accessing elements, slicing, and unpacking. 7. Demonstrates operations on dictionaries like accessing, modifying, adding, and removing key-value pairs. 8. Finds the largest of three user-input numbers. 9

Uploaded by

Naim Mirza
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 42

PROGRAM – 1

AIM : WRITE A PROGRAM TO DEMONSTRATE DIFFERENT


NUMBER DATA TYPES IN PYTHON.

# Integer data type


integer_num = 42
print("Integer:", integer_num)

# Floating-point data type


float_num = 3.14
print("Floating-point:", float_num)

# Complex data type


complex_num = 2 + 3j
print("Complex:", complex_num)

# Arithmetic operations
a = 10
b=3

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

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

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

# Division
division_result = a / b

1
print("Division:", division_result)

# Modulo
modulo_result = a % b
print("Modulo:", modulo_result)

CONCLUSION

This program defines variables for each of the different number data types
(integer, floating-point, and complex), and then demonstrates various
arithmetic operations like addition, subtraction, multiplication, division,
and modulo using integer values a and b.

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:", addition_result)

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

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

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

4
CONCLUSION

This program takes two numbers as input from the user, then performs
addition, subtraction, multiplication, division (if the second number is not
zero), and modulo (if the second number is not zero) operations on those
numbers, and displays 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
str1 = "Hello, "

# Concatenate two strings


str2 = "World!"
result_string = str1 + str2

# Print the concatenated string


print("Concatenated String:", result_string)

# Accessing a substring
substring = result_string[0:5] # Access the first 5 characters
print("Substring:", substring)

# Accessing a substring from the end


end_substring = result_string[-6:] # Access the last 6 characters
print("End Substring:", end_substring)

CONCLUSION

This program first creates a string str1, then concatenates it with another
string str2 to form result_string. It prints the concatenated string and
demonstrates how to access a substring from the beginning and the end of
the result_string.

7
OUTPUT

8
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()

# Format the date and time in the desired format


formatted_datetime = current_datetime.strftime("%a %b %d %H:%M:%S
%Z%Y")

# Print the formatted date and time


print("Formatted Date and Time:", formatted_datetime)

CONCLUSION

When you run this script, it will retrieve the current date and time and
format it in the "FRI OCT 11 02:26:23 IST2019" format. The output will
look something like this:

Formatted Date and Time: Fri Oct 11 02:26:23 IST2019

9
OUTPUT

10
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 original list


print("Original List:", my_list)

# Remove an element by value


my_list.remove(3)

# Print the list after removing an element


print("List after removing 3:", my_list)

# Append more elements


my_list.append(5)
my_list.append(6)

# Print the updated list


print("List after appending 5 and 6:", my_list)

# Remove an element by index


removed_element = my_list.pop(1)

11
# Print the list after removing an element by index
print(f"Removed element at index 1: {removed_element}")
print("List after removing element at index 1:", my_list)

CONCLUSION

In this program –

This program begins by creating an empty list called my_list and then
appends elements to it using the append() method. It demonstrates
removing an element by value using the remove() method, appending more
elements, and removing an element by index using the pop() method.
Finally, it prints the list after each operation to show the changes.

12
OUTPUT

13
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 in a tuple


print("Tuple:", my_tuple)
print("Element at index 0:", my_tuple[0])
print("Element at index 3:", my_tuple[3])
# Slicing a tuple
slice_tuple = my_tuple[1:4]
print("Slice of the tuple:", slice_tuple)

# Tuple unpacking
a, b, c, d, e = my_tuple
print("Tuple Unpacking:")
print("a =", a)
print("b =", b)
print("c =", c)
print("d =", d)
print("e =", e)

# Checking if an element exists in a tuple


element_to_check = 6
if element_to_check in my_tuple:
print(f"{element_to_check} exists in the tuple.")
else:
print(f"{element_to_check} does not exist in the tuple.")

14
# Finding the length of a tuple
tuple_length = len(my_tuple)
print("Length of the tuple:", tuple_length)

CONCLUSION

This program covers various tuple operations, including creating a tuple,


accessing elements, slicing, tuple unpacking, checking for the existence of
an element, and finding the length of a tuple. When you run the program, it
will demonstrate these tuple-related operations.

15
OUTPUT

16
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"] = 35
print("Updated Age:", my_dict["age"])

# Adding a new key-value pair to the dictionary


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

# Removing a key-value pair from the dictionary


removed_value = my_dict.pop("city")
17
print("Removed City:", removed_value)
print("Updated Dictionary after removing 'city':", my_dict)

# Checking if a key exists in the dictionary


key_to_check = "name"
if key_to_check in my_dict:
print(f"'{key_to_check}' exists in the dictionary.")
else:
print(f"'{key_to_check}' does not exist in the dictionary.")

# Finding the number of key-value pairs in the dictionary


dict_length = len(my_dict)
print("Number of key-value pairs in the dictionary:", dict_length)

CONCLUSION

This program covers various dictionary operations, including creating a


dictionary, accessing values, modifying values, adding key-value pairs,
removing key-value pairs, checking for the existence of a key, and finding
the number of key-value pairs in the dictionary. When you run the program,
it will demonstrate these dictionary-related operations.

18
OUTPUT

19
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: "))

# Compare the numbers to find the largest


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 is:", largest)

20
CONCLUSION

In this program –

This program takes three numbers as input, compares them using


conditional statements, and then prints the largest number among them.

OUTPUT

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

# Define the number of rows for the pattern


num_rows = 5

# Create the upper part of the pattern


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

22
# Create the lower part of the pattern
for i in range(num_rows - 1, 0, -1):
for j in range(1, i + 1):
print("*", end=" ")
print()

CONCLUSION

This program first creates the upper part of the pattern with increasing
numbers of asterisks in each row, and then it creates the lower part of the
pattern with decreasing numbers of asterisks in each row. When you run the
program, it will generate the requested pattern.

23
OUTPUT

24
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
elif num == 2:
return True
elif num % 2 == 0:
return False
else:
for i in range(3, int(num ** 0.5) + 1, 2):
if num % i == 0:
return False
return True

# Print prime numbers less than 20


print("Prime numbers less than 20:")
for number in range(2, 20):

25
if is_prime(number):
print(number, end=" ")

CONCLUSION

These are the prime numbers less than 20. The script uses a is_prime()
function to check for primality and then iterates through numbers to find
and print prime numbers within the specified range.

OUTPUT

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

# Function to calculate Fibonacci numbers


def calculate_fibonacci(n):
fib_sequence = []
a, b = 0, 1
while len(fib_sequence) < n:
fib_sequence.append(a)
a, b = b, a + b
return fib_sequence

main_program.py (Main program that imports the module):

# Import the Fibonacci module


import fibonacci_module

# Get user input for the number of Fibonacci numbers to calculate

27
n = int(input("Enter the number of Fibonacci numbers to calculate: "))

# Calculate and print the Fibonacci sequence


fib_sequence = fibonacci_module.calculate_fibonacci(n)
print("Fibonacci Sequence:")
for num in fib_sequence:
print(num, end=" ")

CONCLUSION

28
OUTPUT

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

# Function 1
def add(a, b):
return a + b

# Function 2
def subtract(a, b):
return a - b
# Function 3
def multiply(a, b):
return a * b

# Function 4
def divide(a, b):

30
if b != 0:
return a / b
else:
return "Cannot divide by zero"

main_program.py (Main program that imports a specific function from


the module):

# Import a specific function from the module


from my_module import multiply

# Use the imported function


result = multiply(5, 7)
print("Result of multiplication:", result)

CONCLUSION

31
OUTPUT

32
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 read a text file and return unique words in alphabetical order
def get_unique_words(filename):
unique_words = set()

try:
with open(filename, 'r') as file:
for line in file:
words = line.split()
for word in words:
# Remove punctuation and convert to lowercase
cleaned_word = word.strip('.,?!;()[]{}"\'').lower()

33
if cleaned_word:
unique_words.add(cleaned_word)
except FileNotFoundError:
print("File not found.")

return sorted(unique_words)

# Input the filename from the user


file_name = input("Enter the filename: ")

# Get unique words and print them


unique_words = get_unique_words(file_name)
if unique_words:
print("Unique words in alphabetical order:")
for word in unique_words:
print(word)
else:
print("No unique words found in the file.")

CONCLUSION

In this program –

34
OUTPUT

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

36
class IntegerToRoman:
def __init__(self):
# Define the Roman numeral symbols and their corresponding values
self.roman_symbols = {
'M': 1000, 'CM': 900, 'D': 500, 'CD': 400,
'C': 100, 'XC': 90, 'L': 50, 'XL': 40,
'X': 10, 'IX': 9, 'V': 5, 'IV': 4, 'I': 1
}

def int_to_roman(self, num):


if not (0 < num < 4000):
return "Invalid input, enter a number between 1 and 3999."

roman_numeral = ""
for symbol, value in self.roman_symbols.items():
while num >= value:
roman_numeral += symbol
num -= value

return roman_numeral

# Create an instance of the IntegerToRoman class


converter = IntegerToRoman()

# Prompt the user for an integer


try:
number = int(input("Enter an integer (1-3999): "))
result = converter.int_to_roman(number)
print(f"The Roman numeral for {number} is {result}")
except ValueError:
print("Invalid input. Please enter a valid integer.")

CONCLUSION

37
In this code –

OUTPUT

38
PROGRAM – 15
AIM : WRITE A PYTHON CLASS TO REVERSE A STRING
WORD BY WORD.

39
class ReverseWords:
def reverse_words(self, input_str):
# Split the input string into words
words = input_str.split()

# Reverse the order of words


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

return reversed_str

# Create an instance of the ReverseWords class


reverser = ReverseWords()

# Input a string from the user


input_string = input("Enter a string: ")

# Call the reverse_words method to reverse the string word by word


result = reverser.reverse_words(input_string)
print("Reversed String:", result)

CONCLUSION

In this code –

40
OUTPUT

41
42

You might also like