Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
18 views

Python programs

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

Python programs

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

1.

Python program to calculate the area and perimeter (circumference) of


a circle:

import math

# Function to calculate area and perimeter of a circle


def circle_properties(radius):
area = math.pi * radius ** 2 # Formula for area: A = π * r^2
perimeter = 2 * math.pi * radius # Formula for perimeter (circumference): P = 2 * π * r
return area, perimeter

# Input the radius of the circle


radius = float(input("Enter the radius of the circle: "))

# Call the function and display the results


area, perimeter = circle_properties(radius)
print(f"Area of the circle: {area:.2f}")
print(f"Perimeter (Circumference) of the circle: {perimeter:.2f}")

Explanation:

1. The program uses the math.pi constant to get the value of π (pi).
2. It defines a function circle_properties() that calculates:
o Area using the formula A=πr2A = \pi r^2A=πr2
o Perimeter (Circumference) using the formula P=2πrP = 2 \pi rP=2πr
3. The user is prompted to input the radius, and the program prints the area and perimeter,
rounded to two decimal places.
2. Python program to generate the Fibonacci series:

# Function to generate Fibonacci series up to 'n' terms


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

# Input number of terms in the Fibonacci series


n = int(input("Enter the number of terms in the Fibonacci series: "))

# Generate and display the Fibonacci series


fib_sequence = fibonacci_series(n)
print(f"Fibonacci series up to {n} terms: {fib_sequence}")

Explanation:

1. The function fibonacci_series(n) generates the Fibonacci sequence up to n terms.


o It starts with the first two terms a = 0 and b = 1.
o In each iteration of the loop, it appends the current value of a to the list, then
updates a and b for the next iteration.
2. The program prompts the user to input the number of terms (n) they want in the series.
3. It then prints the Fibonacci series up to the entered number of terms.

For example, if the user enters 7, the program will output:

Fibonacci series up to 7 terms: [0, 1, 1, 2, 3, 5, 8]


3. Python program to calculate the Greatest Common Divisor (GCD) of two
numbers

# Function to calculate GCD using the Euclidean algorithm


def gcd(a, b):
while b:
a, b = b, a % b
return a

# Input two numbers


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

# Calculate and display the GCD


result = gcd(num1, num2)
print(f"The GCD of {num1} and {num2} is: {result}")
4. Python program that generates the first N prime numbers:

# Function to check if a number is prime


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

# Function to generate first N prime numbers


def generate_primes(n):
primes = []
num = 2 # Start checking from 2
while len(primes) < n:
if is_prime(num):
primes.append(num)
num += 1
return primes

# Input number of prime numbers to generate


n = int(input("Enter the number of prime numbers to generate: "))

# Generate and display the prime numbers


prime_numbers = generate_primes(n)
print(f"The first {n} prime numbers are: {prime_numbers}")

Explanation:

1. is_prime(num): This function checks if a number is prime by testing divisibility from 2


up to the square root of the number.
2. generate_primes(n): This function generates the first n prime numbers by checking each
number starting from 2. If the number is prime, it adds it to the list of primes.
3. The program asks the user to input the number of prime numbers they want to generate,
then displays the first n prime numbers.

Example:

If the user enters:

Enter the number of prime numbers to generate: 5

The output will be:

The first 5 prime numbers are: [2, 3, 5, 7,


5. Python program that calculates the sum of the squares of the first N
natural numbers:

# Function to calculate the sum of squares of first N natural numbers


def sum_of_squares(n):
return sum(i ** 2 for i in range(1, n + 1))

# Input: Number of natural numbers


n = int(input("Enter a number N to calculate the sum of squares of first N natural
numbers: "))

# Calculate and display the sum of squares


result = sum_of_squares(n)
print(f"The sum of squares of the first {n} natural numbers is: {result}")

Explanation:

1. The function sum_of_squares(n) computes the sum of the squares of numbers from 1 to
n. It uses a generator expression inside the sum() function to compute the squares.
2. The user is prompted to input a number n which determines how many natural numbers
(starting from 1) to consider.
3. The program then calculates and prints the sum of their squares.

Example:

If the user inputs 5, the program will calculate:

1^2 + 2^2 + 3^2 + 4^2 + 5^2 = 1 + 4 + 9 + 16 + 25 = 55

Output:

The sum of squares of the first 5 natural numbers is: 55


6. Python program to find the sum of the elements of an array (or list):

# Input array from the user


arr = list(map(int, input("Enter the elements of the array (space-separated): ").split()))

# Find the sum of the elements of the array


sum_of_elements = sum(arr)

# Display the sum


print(f"The sum of the elements in the array is: {sum_of_elements}")

Explanation:

1. Input: The program asks the user to input the elements of the array, separated by spaces.
These elements are converted into a list of integers using map() and split().
2. Sum of elements: The sum() function is used to calculate the sum of the elements in the
list.
3. Output: The program prints the sum of the elements in the array.

Example:

If the user inputs:

Enter the elements of the array (space-separated): 1 2 3 4 5

The output will be:

The sum of the elements in the array is: 15

This program calculates the sum of the elements in an array and displays it.
7. Python program to find the largest element in an array:

# Function to find the largest element in the array


def find_largest(arr):
if len(arr) == 0:
return None # Return None if the array is empty
largest = arr[0] # Assume the first element is the largest
for num in arr:
if num > largest:
largest = num # Update largest if a larger element is found
return largest

# Input: Array of numbers


arr = list(map(int, input("Enter the elements of the array (space-separated): ").split()))

# Find and display the largest element


largest_element = find_largest(arr)
if largest_element is not None:
print(f"The largest element in the array is: {largest_element}")
else:
print("The array is empty.")

Explanation:

1. find_largest(arr): This function iterates through each element in the array and keeps
track of the largest number found. Initially, it assumes the first element to be the largest
and then compares it with each subsequent element.
2. User input: The program asks for the input of an array, where the user enters the
elements separated by spaces. The map and split functions are used to convert the input
into a list of integers.
3. It checks if the array is empty and handles that case by returning None.

Example:

If the user inputs:

Enter the elements of the array (space-separated): 3 9 1 7 4


8. Python program to check if a string is a palindrome or not:

# Function to check if a string is palindrome


def is_palindrome(s):
# Remove spaces and convert to lowercase for case-insensitive comparison
s = s.replace(" ", "").lower()
return s == s[::-1]

# Input string
string = input("Enter a string to check if it's a palindrome: ")

# Check and display result


if is_palindrome(string):
print(f"'{string}' is a palindrome.")
else:
print(f"'{string}' is not a palindrome.")

Explanation:

1. is_palindrome(s):
o The function first removes spaces (s.replace(" ", "")) and converts the string to
lowercase (.lower()) to ensure case-insensitive and space-insensitive comparison.
o It then checks if the string is equal to its reverse (s[::-1]), which is a common
technique to reverse a string in Python.

2. User input: The program prompts the user to input a string.


3. Output: It prints whether the string is a palindrome or not based on the check.

Example:

If the user inputs:

Enter a string to check if it's a palindrome: madam

The output will be:

'madam' is a palindrome.

If the user inputs:

Enter a string to check if it's a palindrome: hello

The output will be:


'hello' is not a palindrome.

9. Python program that stores a string in a list and prints the elements of
the list:

# Input a string
string = input("Enter a string: ")

# Store the string in a list (each character will be an element)


string_list = list(string)

# Print the list


print("The string stored in the list is:")
print(string_list)

Explanation:

1. Input a string: The program asks the user to input a string.


2. Convert string to list: The list() function is used to convert the string into a list, where
each character becomes an individual element in the list.
3. Print the list: The program then prints the list.

Example:

If the user inputs:

Enter a string: hello

The output will be:

The string stored in the list is:


['h', 'e', 'l', 'l', 'o']

This program stores each character of the string as a separate element in the list and prints the
list.
10.Python program that demonstrates how to find the length of a list,
reverse it, copy it, and clear it:

# Input list from the user


lst = list(map(int, input("Enter the elements of the list (space-separated): ").split()))

# 1. Find the length of the list


length = len(lst)
print(f"Length of the list: {length}")

# 2. Reverse the list


reversed_lst = lst[::-1]
print(f"Reversed list: {reversed_lst}")

# 3. Copy the list


copied_lst = lst.copy()
print(f"Copied list: {copied_lst}")

# 4. Clear the list


lst.clear()
print(f"List after clearing: {lst}")

Explanation:

1. Find the length: We use the len() function to find the number of elements in the list.
2. Reverse the list: We reverse the list using slicing (lst[::-1]), which returns a new list that
is the reverse of the original.
3. Copy the list: We use the copy() method to create a shallow copy of the list.
4. Clear the list: We use the clear() method to remove all elements from the list, leaving it
empty.

Example:

If the user inputs:

Enter the elements of the list (space-separated): 1 2 3 4 5

The output will be:

Length of the list: 5


Reversed list: [5, 4, 3, 2, 1]
Copied list: [1, 2, 3, 4, 5]
List after clearing: []

You might also like