[Go to site: main page, start]

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

Python Programs for Common Tasks

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)
7 views7 pages

Python Programs for Common Tasks

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

1. Python Program to Find the Square Root.

import math

# Function to calculate square root


def square_root(num):
return [Link](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 [Link](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: '{[Link]()}'")

# 2. Convert to lowercase
print(f"Lowercase: '{[Link]()}'")

# 3. Capitalize the first letter


print(f"Capitalize: '{[Link]()}'")

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


print(f"Title Case: '{[Link]()}'")

# 5. Strip leading and trailing whitespace


print(f"Stripped: '{[Link]()}'")

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

# 7. Find the position of a substring


substring = "find"
print(f"Find '{substring}': {[Link](substring)}")

# 8. Split the string into a list of substrings


delimiter = " "
print(f"Split by '{delimiter}': {[Link](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: {[Link]()}")

# 11. Check if the string is alphabetic


print(f"Is Alphabetic: {[Link]()}")

# 12. Check if the string is numeric


print(f"Is Numeric: {[Link]()}")

# 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):
[Link] = name
[Link] = age
[Link] = city

# Method to display person details


def display_info(self):
print(f"Name: {[Link]}")
print(f"Age: {[Link]}")
print(f"City: {[Link]}")

# Method to celebrate birthday


def celebrate_birthday(self):
[Link] += 1
print(f"Happy Birthday, {[Link]}! You are now {[Link]} 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

Common questions

Powered by AI

The Python program employs a simple loop to iterate through numbers 1 to 10, multiplying each by the given base number and printing the result with formatted output. This method is straightforward but relies on iteration, making it naturally scalable; it can be extended to higher ranges by adjusting the `upto` parameter. The scalability is mostly limited by how Python handles large integers and the practical aspect of console output readability .

The program's `Person` class demonstrates core object-oriented programming principles by encapsulating data (`name`, `age`, `city`) and behavior (`display_info()`, `celebrate_birthday()`) within a coherent unit. It promotes the use of encapsulation, abstraction, and polymorphism—allowing for complex functionality to be represented in an accessible, modular, and re-usable manner, fostering code reusability and scalability. This setup is fundamental to building more extensive and maintainable systems that are design-driven .

Tuple unpacking in Python offers a concise and readable way to swap variables, eliminating the need for a temporary variable typically required in traditional swapping methods. This makes the code more elegant and reduces the chance of errors associated with managing additional variables. It also allows simultaneous assignment that can be computationally efficient in interpreted languages like Python .

The program for printing the Fibonacci sequence employs a simple iterative approach, maintaining current and next sequence values and incrementing the count. It efficiently generates sequence terms in linear time, `O(n)`. However, its efficiency can be improved by using memoization or matrix exponentiation methods, which can compute Fibonacci numbers in logarithmic time `O(log n)`, allowing for faster computation especially in larger sequences .

The program uses the `random.randint(a, b)` function from Python's random module to generate a random integer between two specified bounds, inclusive. This method is straightforward and uses Python's built-in capabilities. However, its limitations include being impacted by the underlying pseudo-random number generator's predictability and potential biases if the range of numbers is large or if specific numbers are desired with unequal probability .

Python dictionaries provide efficient data storage and access through key-value pairs, allowing for rapid retrieval and dynamic management of associative data structures. They offer advantages like quick lookup times `O(1)` and flexibility with mutable values. However, dictionaries can have limitations, such as hash collisions leading to reduced performance, and the requirement of immutable keys. They also consume more memory compared to basic lists, which may affect performance in memory-constrained environments .

The string manipulation methods demonstrated in the Python program facilitate a range of functionalities such as changing case (`upper`, `lower`, `capitalize`, `title`), trimming whitespace (`strip`), replacing substrings, finding and splitting substrings, joining lists into strings, and checking character types (`isalnum`, `isalpha`, `isdigit`). These operations are crucial in data cleaning, formatting, parsing, and preparing strings for analysis or user interaction across diverse applications like text processing, data validation, and user interface design .

The Python program uses two methods to find the square root of a number. The first method utilizes the `math.sqrt()` function from the math module, which directly calculates the square root. The second method uses the exponentiation operator `**` to raise the number to the power of 0.5, which is mathematically equivalent to finding its square root .

The recursive method for calculating factorials utilizes the base case of `n = 0 or 1`, and a recursive case `n * factorial(n-1)` for other values. This approach is intuitive and elegantly expresses the mathematical definition of factorial. However, recursion can lead to stack overflow errors for large `n` due to Python's recursion limit, and its overhead can be higher than iterative approaches, which might be more memory-efficient for calculating large factorials .

The primality test program in Python benefits from checking divisibility only up to the square root of the number, a mathematical optimization that reduces the number of operations. By iterating only up to `int(num ** 0.5) + 1`, the algorithm efficiently eliminates non-prime numbers. Despite these optimizations, the program can face computational constraints when dealing with very large numbers, as it remains inherently limited by its `O(sqrt(n))` time complexity, making it less efficient than advanced primality tests like Miller-Rabin for large inputs .

You might also like