0% found this document useful (0 votes)
2 views7 pages

Python Lab Program

Uploaded by

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

Python Lab Program

Uploaded by

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

1. Python Program to Find the Square Root.

import math

# Function to calculate square root


def square_root(num):
return math.sqrt(num)

# Example usage
number = float(input("Enter a number: "))
result = square_root(number)
print(f"The square root of {number} is {result}")
2. Using the exponentiation operator:
You can use the ** operator to raise a number to the power of 0.5 to get the square
root.

python
Copy code
# Function to calculate square root
def square_root(num):
return num ** 0.5

# Example usage
number = float(input("Enter a number: "))
result = square_root(number)
print(f"The square root of {number} is {result}")

2. Python Program to Swap Two Variables.


# Swapping using multiple assignment
def swap(a, b):
a, b = b, a
return a, b

# Example usage
x = int(input("Enter the value of x: "))
y = int(input("Enter the value of y: "))
x, y = swap(x, y)
print(f"After swapping: x = {x}, y = {y}")

3. Python Program to Generate a Random Number


import random

# Function to generate a random integer between a and b (inclusive)


def generate_random_integer(a, b):
return random.randint(a, b)

# Example usage
lower = int(input("Enter the lower bound: "))
upper = int(input("Enter the upper bound: "))
random_number = generate_random_integer(lower, upper)
print(f"Random integer between {lower} and {upper} is: {random_number}")

4. Python Program to Check if a Number is Odd or Even.


# Function to check if the number is odd or even
def check_odd_even(number):
if number % 2 == 0:
return "Even"
else:
return "Odd"
# Example usage
num = int(input("Enter a number: "))
result = check_odd_even(num)
print(f"The number {num} is {result}.")

5. Python Program to Find the Largest Among Three Numbers


# Function to find the largest among three numbers
def find_largest(a, b, c):
if a >= b and a >= c:
return a
elif b >= a and b >= c:
return b
else:
return c

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

largest = find_largest(num1, num2, num3)


print(f"The largest number among {num1}, {num2}, and {num3} is {largest}.")

6. Python Program to Check Prime Number.


# Function to check if a number is prime
def is_prime(num):
# Numbers less than 2 are not prime
if num < 2:
return False
# Check for factors from 2 to the square root of the number
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True

# Example usage
number = int(input("Enter a number: "))

if is_prime(number):
print(f"{number} is a prime number.")
else:
print(f"{number} is not a prime number.")

Enter a number: 29
29 is a prime number.

Enter a number: 12
12 is not a prime number.

7. Python Program to Display the multiplication Table.


# Function to display the multiplication table for a given number
def multiplication_table(num, upto=10):
for i in range(1, upto + 1):
print(f"{num} x {i} = {num * i}")

# Example usage
number = int(input("Enter a number to display its multiplication table: "))
multiplication_table(number)
Enter a number to display its multiplication table: 5
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

8. Python Program to Print the Fibonacci sequence


# Function to print Fibonacci sequence up to n terms
def fibonacci_sequence(n):
a, b = 0, 1 # Starting values of the sequence
count = 0
while count < n:
print(a, end=" ")
a, b = b, a + b # Update to the next term
count += 1

# Example usage
terms = int(input("Enter the number of terms: "))
if terms <= 0:
print("Please enter a positive integer.")
else:
print(f"Fibonacci sequence up to {terms} terms:")
fibonacci_sequence(terms)
Enter the number of terms: 10
Fibonacci sequence up to 10 terms:
0 1 1 2 3 5 8 13 21 34

9. Python Program to Find the Sum of Natural Numbers.


# Function to calculate sum of natural numbers using the formula
def sum_of_natural_numbers(n):
return n * (n + 1) // 2

# Example usage
n = int(input("Enter a positive integer: "))
if n <= 0:
print("Please enter a positive integer.")
else:
result = sum_of_natural_numbers(n)
print(f"The sum of the first {n} natural numbers is {result}.")
Enter a positive integer: 5

The sum of the first 5 natural numbers is 15.


10. Python Program to Find Factorial of Number Using Recursion
# Function to calculate factorial using recursion
def factorial(n):
# Base case: factorial of 0 or 1 is 1
if n == 0 or n == 1:
return 1
# Recursive case: n * factorial of (n-1)
else:
return n * factorial(n - 1)

# Example usage
number = int(input("Enter a number: "))
if number < 0:
print("Factorial is not defined for negative numbers.")
else:
result = factorial(number)
print(f"The factorial of {number} is {result}.")
Enter a number: 5
The factorial of 5 is 120.

I l. Python Program to work with string methods.


# Function to demonstrate various string methods
def string_methods_demo(s):
print(f"Original String: '{s}'")

# 1. Convert to uppercase
print(f"Uppercase: '{s.upper()}'")

# 2. Convert to lowercase
print(f"Lowercase: '{s.lower()}'")

# 3. Capitalize the first letter


print(f"Capitalize: '{s.capitalize()}'")

# 4. Title case (capitalize the first letter of each word)


print(f"Title Case: '{s.title()}'")

# 5. Strip leading and trailing whitespace


print(f"Stripped: '{s.strip()}'")

# 6. Replace a substring
old_substring = "old"
new_substring = "new"
print(f"Replace '{old_substring}' with '{new_substring}':
'{s.replace(old_substring, new_substring)}'")

# 7. Find the position of a substring


substring = "find"
print(f"Find '{substring}': {s.find(substring)}")

# 8. Split the string into a list of substrings


delimiter = " "
print(f"Split by '{delimiter}': {s.split(delimiter)}")

# 9. Join a list of substrings into a single string


words = ["join", "these", "words"]
print(f"Join with '-': '{'-'.join(words)}'")

# 10. Check if the string is alphanumeric


print(f"Is Alphanumeric: {s.isalnum()}")

# 11. Check if the string is alphabetic


print(f"Is Alphabetic: {s.isalpha()}")

# 12. Check if the string is numeric


print(f"Is Numeric: {s.isdigit()}")

# Example usage
example_string = " Example string for string methods demo. "
string_methods_demo(example_string)
Explanation of Methods:
upper(): Converts all characters in the string to uppercase.
lower(): Converts all characters in the string to lowercase.
capitalize(): Capitalizes the first character of the string.
title(): Capitalizes the first character of each word in the string.
strip(): Removes leading and trailing whitespace from the string.
replace(old, new): Replaces occurrences of the substring old with new.
find(substring): Finds the first occurrence of substring and returns its index.
Returns -1 if not found.
split(delimiter): Splits the string into a list of substrings based on the
delimiter.
join(iterable): Joins the elements of an iterable (e.g., list) into a single
string, separated by the string on which join is called.
isalnum(): Returns True if all characters in the string are alphanumeric (letters
and numbers) and there is at least one character.
isalpha(): Returns True if all characters in the string are alphabetic and there is
at least one character.
isdigit(): Returns True if all characters in the string are digits and there is at
least one character.
Example Output:
vbnet
Copy code
Original String: ' Example string for string methods demo. '
Uppercase: ' EXAMPLE STRING FOR STRING METHODS DEMO. '
Lowercase: ' example string for string methods demo. '
Capitalize: ' example string for string methods demo. '
Title Case: ' Example String For String Methods Demo. '
Stripped: 'Example string for string methods demo.'
Replace 'old' with 'new': ' Example string for string methods demo. '
Find 'find': 26
Split by ' ': ['Example', 'string', 'for', 'string', 'methods', 'demo.']
Join with '-': 'join-these-words'
Is Alphanumeric: False
Is Alphabetic: False
Is Numeric: False

12. Python Program to create a dictionary and print its content.


# Function to create and print a dictionary
def create_and_print_dictionary():
# Create a dictionary with some key-value pairs
my_dict = {
"name": "Alice",
"age": 30,
"city": "New York",
"occupation": "Engineer"
}

# Print the entire dictionary


print("Dictionary contents:")
for key, value in my_dict.items():
print(f"{key}: {value}")

# Example usage
create_and_print_dictionary()

Example Output:
vbnet
Copy code
Dictionary contents:
name: Alice
age: 30
city: New York
occupation: Engineer

13. Python Program to create class and objects.


# Define a class named Person
class Person:
# Constructor to initialize the attributes
def __init__(self, name, age, city):
self.name = name
self.age = age
self.city = city

# Method to display person details


def display_info(self):
print(f"Name: {self.name}")
print(f"Age: {self.age}")
print(f"City: {self.city}")

# Method to celebrate birthday


def celebrate_birthday(self):
self.age += 1
print(f"Happy Birthday, {self.name}! You are now {self.age} years old.")

# Create objects (instances) of the Person class


person1 = Person("Alice", 30, "New York")
person2 = Person("Bob", 25, "Los Angeles")

# Display information for person1


print("Person 1 details:")
person1.display_info()
print()

# Celebrate birthday for person1 and display updated info


person1.celebrate_birthday()
person1.display_info()
print()

# Display information for person2


print("Person 2 details:")
person2.display_info()

Example Output:
vbnet
Copy code
Person 1 details:
Name: Alice
Age: 30
City: New York

Happy Birthday, Alice! You are now 31 years old.


Name: Alice
Age: 31
City: New York

Person 2 details:
Name: Bob
Age: 25
City: Los Angeles

You might also like