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

Python Practical

The document outlines a practical list for a Python Programming course at Gondwana University, detailing various programming tasks for students. It includes exercises such as adding two numbers, finding square roots, generating random numbers, and implementing object-oriented concepts. Additionally, it provides code examples and expected outputs for each task.
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 views17 pages

Python Practical

The document outlines a practical list for a Python Programming course at Gondwana University, detailing various programming tasks for students. It includes exercises such as adding two numbers, finding square roots, generating random numbers, and implementing object-oriented concepts. Additionally, it provides code examples and expected outputs for each task.
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
You are on page 1/ 17

Gondwana University, Gadchiroli

Post Graduate Teaching Department of Computer Science


M.Sc. Sem-I
Subject: Python Programming
Practical List
Practical: Python Programming (01MSCCS02)
1) Write a Python Program to add two Numbers.
2) Write a Python Program to find the Square root.
3) Write a Python Program to generate Random Numbers.
4) Write a Python Program to check if a number is positive, negative, or zero.
5) Write a Python Program to check number is odd or even
6) Write a Python Program to find the sum of natural numbers
7) Programs on Python List, Dictionary, and Object-Oriented Concepts
8) Write a Python program that can compute the factorial of a given number.
9) Write a Python program to find Armstrong numbers between 100 to 999.
10) Write a Python program to find the sum of prime numbers between 1 to 100.
11) Write a Python program to find the reverse of the given number.
12) Write a Python program to check if a given positive integer is a power of three.
13) Write a Python program to check if a number is a perfect square.
14)
a) Write a function nearly equal to test whether two strings are nearly equal. Two strings a
and b are nearly equal when a can be generated by a single mutation.
b) Write a function to compute the gcd and lcm of two numbers. Each function shouldn’t
exceed one
Execution List

1) Write a Python Program to add two Numbers.

# This program adds two numbers

num1 = 1.5
num2 = 6.3

# Add two numbers


sum = num1 + num2

# Display the sum


print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))

OUTPUT
The sum of 1.5 and 6.3 is 7.8
2) Write a Python Program to find the Square root.

# Input a number
num = float(input("Enter a number: "))

# Calculate the square root


if num >= 0:
sqrt = num ** 0.5
print(f"The square root of {num} is {sqrt}")
else:
print("Sorry, cannot calculate the square root of a negative number.")

OUTPUT

Enter a number: 4
The square root of 4.0 is 2.0
3) Write a Python Program to generate Random Numbers.

import random

# Generate a random integer between a specified range


random_integer = random.randint(1, 100)
print("Random Integer:", random_integer)

# Generate a random floating-point number between 0 and 1


random_float = random.random()
print("Random Float:", random_float)

# Generate a random floating-point number within a specified range


min_value = 5.0
max_value = 10.0
random_float_range = random.uniform(min_value, max_value)
print("Random Float within Range:", random_float_range)

OUTPUT
Random Integer: 21
Random Float: 0.4642207639425908
Random Float within Range: 8.966226056902022
4) Write a Python Program to check if a number is positive, negative, or zero.

# Input a number from the user


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

# Check if the number is positive, negative, or zero


if number > 0:
print("The number is positive.")
elif number < 0:
print("The number is negative.")
else:
print("The number is zero.")

Output

Enter a number: 6
The number is positive.
5) Write a Python Program to check number is odd or even.

# Input a number from the user


num = int(input("Enter a number: "))

# Check if the number is even or odd


if num % 2 == 0:
print(f"{num} is even.")
else:
print(f"{num} is odd.")

OUTPUT
enter a number: 10
10 is even.
6) Write a Python Program to find the sum of natural numbers

# Get the input from the user


n = int(input("Enter a positive integer: "))

# Initialize a variable to store the sum


sum_of_natural_numbers = 0

# Check if the input is a positive integer


if n <= 0:
print("Please enter a positive integer.")
else:
# Calculate the sum of natural numbers from 1 to n
for i in range(1, n + 1):
sum_of_natural_numbers += i

# Display the result


print(f"The sum of natural numbers from 1 to {n} is:
{sum_of_natural_numbers}")

OUTPUT
Enter a positive integer: 6
The sum of natural numbers from 1 to 6 is: 21
7) Programs on Python List, Dictionary, and Object-Oriented Concepts.

a) Programs on Python List


# Program to find the sum and average of a list of numbers
numbers = [10, 20, 30, 40, 50]

# Calculate the sum of the numbers


total = sum(numbers)

# Calculate the average of the numbers


average = total / len(numbers)

print(f"Sum: {total}")
print(f"Average: {average}")

output
Sum: 150
Average: 30.0

b) Programs on Dictionary.
# Program to create and manipulate a dictionary
student = {
'name': 'John',
'age': 20,
'grade': 'A',
'courses': ['Math', 'Science', 'History']
}
# Accessing dictionary values
print(f"Student Name: {student['name']}")
print(f"Student Age: {student['age']}")
# Adding a new key-value pair
student['city'] = 'New York'
# Iterating through dictionary items
for key, value in student.items():
print(f"{key}: {value}")
Output
Student Name: John
Student Age: 20
name: John
age: 20
grade: A
courses: ['Math', 'Science', 'History']
city: New York
c) Programs on Object-Oriented Concepts.
# Define a simple class
class Car:
def __init__(self, make, model):
self.make = make
self.model = model
self.speed = 0

def accelerate(self, amount):


self.speed += amount

def brake(self, amount):


self.speed -= amount
if self.speed < 0:
self.speed = 0

def get_speed(self):
return self.speed

# Create an instance of the Car class


my_car = Car("Toyota", "Camry")

# Accelerate and brake the car


my_car.accelerate(20)
my_car.brake(10)

# Get the current speed of the car


current_speed = my_car.get_speed()

print(f"My car is a {my_car.make} {my_car.model}")


print(f"Current Speed: {current_speed} km/h")

Output
My car is a Toyota Camry
Current Speed: 10 km/h
8) Write a Python program that can compute the factorial of a given number.

def factorial_recursive(n):
if n == 0:
return 1
else:
return n * factorial_recursive(n - 1)

# Input
num = int(input("Enter a number: "))

if num < 0:
print("Factorial is not defined for negative numbers.")
elif num == 0:
print("The factorial of 0 is 1")
else:
result = factorial_recursive(num)
print(f"The factorial of {num} is {result}")

Output
Enter a number: 8
The factorial of 8 is 40320
9) Write a Python program to find Armstrong numbers between 100 to 999.

# Function to check if a number is an Armstrong number


def is_armstrong_number(num):
num_str = str(num)
num_digits = len(num_str)
sum_of_digits = sum(int(digit) ** num_digits for digit in num_str)
return num == sum_of_digits

# Find Armstrong numbers between 100 and 999


armstrong_numbers = []
for number in range(100, 1000):
if is_armstrong_number(number):
armstrong_numbers.append(number)

# Print Armstrong numbers


print("Armstrong numbers between 100 and 999 are:")
for armstrong in armstrong_numbers:
print(armstrong)

OUTPUT
Armstrong numbers between 100 and 999 are:
153
370
371
407
10) Write a Python program to find the sum of prime numbers between 1 to 100.

def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True

def sum_primes(start, end):


prime_sum = 0
for num in range(start, end + 1):
if is_prime(num):
prime_sum += num
return prime_sum

start = 1
end = 100
result = sum_primes(start, end)
print(f"The sum of prime numbers between {start} and {end} is: {result}")

output

The sum of prime numbers between 1 and 100 is: 1060


11) Write a Python program to find the reverse of the given number.

# Function to reverse a number


def reverse_number(number):
# Convert the number to a string
num_str = str(number)

# Reverse the string


reversed_str = num_str[::-1]

# Convert the reversed string back to an integer


reversed_num = int(reversed_str)

return reversed_num

# Input a number from the user


num = int(input("Enter a number: "))

# Call the function to reverse the number


reversed_num = reverse_number(num)

# Display the reversed number


print("Reversed number:", reversed_num)

OUTPUT
Enter a number: 12345
Reversed number: 54321
12) Write a Python program to check if a given positive integer is a power of three.

def is_power_of_three(n):
if n <= 0:
return False
while n % 3 == 0:
n /= 3
return n == 1

# Input a positive integer


num = int(input("Enter a positive integer: "))

if is_power_of_three(num):
print(f"{num} is a power of three.")
else:
print(f"{num} is not a power of three.")

OUTPUT
Enter a positive integer: 9
9 is a power of three.

Enter a positive integer: 7


7 is not a power of three.
13) Write a Python program to check if a number is a perfect square.

import math

def is_perfect_square(number):
# Calculate the square root
sqrt_num = math.sqrt(number)

# Check if the square root is an integer


if sqrt_num.is_integer():
return True
else:
return False

# Input a number to check


num = int(input("Enter a number: "))

if is_perfect_square(num):
print(f"{num} is a perfect square.")
else:
print(f"{num} is not a perfect square.")

OUTPUT

Enter a number: 9
9 is a perfect square.

Enter a number: 8
8 is not a perfect square.
14) a) Write a function nearly equal to test whether two strings are nearly equal.
Two strings a and b are nearly equal when a can be generated by a single
mutation.
def nearly_equal(str1, str2):
# If the lengths of the strings differ by more than 1, they can't be nearly equal
if abs(len(str1) - len(str2)) > 1:
return False

# Initialize variables to keep track of differences


diff_count = 0
i=0
j=0

# Iterate through both strings


while i < len(str1) and j < len(str2):
if str1[i] != str2[j]:
# If we find a difference, increment the difference count
diff_count += 1

# If there have been more than one difference, return False


if diff_count > 1:
return False

# Check if it's a substitution, and move both pointers


if len(str1) == len(str2):
i += 1
j += 1
elif len(str1) > len(str2):
i += 1
else:
j += 1
else:
# If characters are the same, move both pointers
i += 1
j += 1

# If there is one extra character at the end of either string, it can still be nearly
equal
if i < len(str1) or j < len(str2):
diff_count += 1

# Return True if there is at most one difference


return diff_count <= 1

# Example usage:
str1 = "hello"
str2 = "helo"
result = nearly_equal(str1, str2)
print(result) # Output: True
OUTPUT
True

b) Write a function to compute the gcd and lcm of two numbers. Each function
shouldn’t exceed one line.
import math
gcd = lambda a, b: math.gcd(a, b)
lcm = lambda a, b: abs(a * b) // math.gcd(a, b)

You might also like