0% found this document useful (0 votes)
29 views30 pages

Python Programs for Basic Calculations

The document describes several Python programs to solve common problems involving strings, arrays, numbers, and other data types. For each program, it provides the aim, algorithm, code, output and result. The programs cover topics like finding the area and perimeter of a circle, generating Fibonacci series, computing GCD of two numbers, generating prime numbers, finding the sum of squares, finding the largest element in an array, checking for palindromes, and storing/printing strings from a list.

Uploaded by

subabsc1234
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)
29 views30 pages

Python Programs for Basic Calculations

The document describes several Python programs to solve common problems involving strings, arrays, numbers, and other data types. For each program, it provides the aim, algorithm, code, output and result. The programs cover topics like finding the area and perimeter of a circle, generating Fibonacci series, computing GCD of two numbers, generating prime numbers, finding the sum of squares, finding the largest element in an array, checking for palindromes, and storing/printing strings from a list.

Uploaded by

subabsc1234
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

EX.

NO: 01
01. AREA AND PERIMETER OF A CIRCLE
DATE:

AIM

To Write a Python program to find the area and perimeter of a circle

ALGORITHM

Step1: Start the program

Step 2: the user to enter the radius of the circle and reads in the value as a string

using the input() function. The float() function is then used to convert the input

value to a floating-point number.

Step 3: calculates the area of the circle using the formula π*r^2. The value of π

is approximated to 3.142.

Step 4: calculates the perimeter of the circle using the formula 2*π*r.

Step 5: These lines print the area and perimeter of the circle using the print()

function. The values of a and p are inserted into the output strings using string

formatting

Step 6:Stop the program


PROGRAM:

r=float(input("enter the radius of the circle....."))

a=3.142*r*r

p=2*3.142*r

print("the area of the circle=",a)

print("the perimeter of the circle=",p)

OUTPUT:

RESULT:

Thus the program has been created and executed Successfully.


[Link]: 02
FIBONACCI SERIES
DATE :

AIM:

To Write a Python program to generate Fibonacci series

ALGORITHM:

Step1: Start the program

Step 2: The user to enter a value for n and reads it in as an integer using the

input() and int() functions.

Step 3: Initializes the first two terms of the Fibonacci series, which are 0 and 1

Step 4: print the initial two terms of the series, which are 0 and 1

Step 5: The loop runs from the third term (i=2) up to the nth term (i=num1-1).

In each iteration of the loop, the current term (c) is calculated as the sum

of the previous two terms (a and b).

The values of a and b are then updated to the previous two terms,

respectively. Finally, the current term is printed using the print() function

with end="" to prevent the cursor from moving to the next line.

Step 6: Stop the program


PROGRAM:

num1=int(input("enter n value:"))
a=0
b=1
print("fibonacci series.....")
print("0 1",end="")
i=2
while(i<=num1-1):
c=a+b
a=b
b=c
print(c,end="")
i=i+1
OUTPUT:

RESULT

Thus the program has been created and executed Successfully.


[Link]: 03
GCD OF TWO NUMBERS
DATE:

AIM

To Write a Python program to compute the GCD of two numbers

ALGORITHM

Step1: Start the program

Step 2: Initialize the two numbers (num1 and num2) and the GCD (gcd) to 1

Step 3: loops through all possible factors of the smaller of the two numbers

(min(num1,num2)) and checks if they divide both num1 and num2 without a

remainder. If a factor is found, it is stored as the new value of gcd. The loop

continues until all possible factors have been checked

Step 4: print() statement inside the loop is used to display the value of gcd

whenever a new factor is found that divides both num1 and num2.

Step 5:Stop the program


PROGRAM

num1=36

num2=60

gcd=1

for i in range (1,min(num1,num2)):

if num1%i==0 and num2% i==0:

gcd=i

print("GCD of ",num1,"and",num2,"is",gcd)
OUTPUT

RESULT

Thus the program has been created and executed Successfully.


[Link]: 04

DATE:
N PRIME NUMBER

AIM

To Write a Python program to generate first n prime numbers

ALGORITHM

Step1: Start the program

Step 2: This code takes an integer input from the user and generates a list of

prime numbers up to that number.

Step 3: The program starts by printing a message indicating the range of prime

numbers being generated.

Step 4: It then uses a nested loop to check if each number in the range from 1 to

numr is prime, by dividing it by all the numbers between 2 and n-1.

Step 5: If the number is not divisible by any of these numbers, it is a prime

number and is printed out. The "else" clause in the inner loop is executed only if

the loop completes without a "break" statement being encountered, indicating

that the number is prime.

Step 6:Stop the program


CODING:

numr=int(input("Enter the 'numr'value:"))

print("The list of ",numr,"prime numbers")

print("Prime numbers:",end=' ')

for n in range(1,numr):

for i in range(2,n):

if(n%i==0):

break

else:

print(n,end=' ')
OUTPUT:

RESULT:

Thus the program has been created and executed Successfully.


[Link]: 05 N NATURAL NUMBER
DATE:

AIM

To Write a Python program to find the sum of squares of n natural


numbers .

ALGORITHM

Step1: Start the program

Step2: The user to input a positive integer n, and then asks the user to input n

natural numbers.

Step3: For each number entered, it squares it and adds the result to a running

sum sum. After each iteration, the program prints out the current value of the

sum.

Step4: One thing to note is that the input statement inside the for loop should

specify that the input should be a natural number, not a float, since the program

expects natural numbers as input.

Step5:Stop the program


CODING:

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

sum=0

for i in range(1,n+1):

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

sum=sum+(m*m)

print("The sum value is ",sum)


OUTPUT:

RESULT:

Thus the program has been created and executed Successfully


[Link]: 06 SUM OF THE ELEMENTS IN AN ARRAY
DATE:

AIM

To write a python program to find the sum of the elements in an array

ALGORITHM

Step1: Initializes an array called "arr" with 5 elements: [1,2,3,4,5].

Step2: Initializes a variable called "sum" with a value of 0. This variable will be

used to store the sum of all the elements in the array.

Step3: Starts a for loop that will iterate through each element in the array. The

loop variable "i" will take on the values 0, 1, 2, 3, and 4 (since the length of the

array is 5).

Step4: Adds the current element in the array (arr[i]) to the variable "sum".

Step5: After the loop has finished iterating through all the elements in the array,

prints out the sum of all the elements.

Step6:Stop the program.


CODING:

# initialize array

arr=[1,2,3,4,5];

sum=0;

#Loop through the array to calculate sum of elements

for i in range(0,len(arr)):

sum= sum+arr[i];

print("sum of all the element of an array:"+str(sum));


OUTPUT

RESULT:

Thus the program has been created and executed Successfully


[Link]
LARGEST ELEMENT
DATE:

AIM

To write a python program to find the largest element in the array

ALGORITHM

Step1:Start the program.

Step2:The function largest() takes two arguments: the array arr and its size n.

Step3: The max variable is initialized to the first element of the array arr[0], and

then the loop begins iterating through the array elements starting from the

second element.

Step4: If any element is found to be greater than the current maximum, then the

max variable is updated to that element's value.

Step5: Finally, the function returns the maximum value. The Driver Code

initializes an array arr and its size n, calls the largest() function, and prints the

maximum value in the array.

Step6:Stop the program.


CODING:

# Python3 program to find maximum

# in arr[] of size n

# python function to find maximum

# in arr[] of size n

def largest(arr, n):

# Initialize maximum element

max = arr[0]

# Traverse array elements from second

# and compare every element with

# current max

for i in range(1, n):

if arr[i] > max:

max = arr[i]

return max

# Driver Code

arr = [10, 324, 45, 90, 9]

n = len(arr)

Ans = largest(arr, n)

print("Largest in given array ", Ans)


OUTPUT:

RESULT

Thus the program has been created and executed Successfully


[Link]: 08 PALINDROME OR NOT
DATE:

AIM:

To write a python program to check if the given string is a palindrome or not.

ALGORITHM

Step1:Start the program.

Step2: The code works by using two pointers, one starting at the beginning of

the string (i=0) and the other starting at the end of the string (j=len(str)-1).

Step3: It then compares the characters at these two positions and moves the

pointers closer to each other until they meet in the middle of the string.

Step4: If any two characters don't match during the process, the string is not a

palindrome.

Step5:Stop the program.


CODING:

str=input("Enter String: ")

i=0

j=len(str)-1

isPalindrome=True

while i<=j:

if(str[i]!=str[j]):

isPalindrome=False

break

i+=1

j-=1

if isPalindrome:

print(f"{str} is Palindrome.")

else:

print(f"{str} is not a Palindrome.")


OUTPUT:

RESULT:

Thus the program has been created and executed Successfully.


[Link]
STRING
DATE:

AIM:

To write a python program to store strings in a list and print them.

ALGORITHM:

Step1:Start the program.

Step2: First, the program initializes a variable cont with the value 'Y'. This

variable will be used later to check if the user wants to continue adding strings

or not.

Step3: The program also initializes an empty list called mylist. This list will be

used to store the user's input strings.

Step4:A while loop is used to repeatedly ask the user for input and store it in the

list until the user indicates they want to stop.

Step5:Inside the loop, the program prompts the user to enter a string using the

input() function and saves the user's input in a variable called myStr.

Step6:The program then adds myStr to the list mylist using the append()

[Link] program then asks the user if they want to continue adding strings.
If the user enters 'Y' or 'y', the loop continues. Otherwise, the loop ends and the

program moves on to the next step.

Step7:Once the loop has ended, the program prints out all the elements in the

list using a for loop that iterates through each element in the list and prints it

out.

Step9:Overall, this program is a simple example of how to use Python lists and

control structures like while and for loops to process user input.

Step10:Stop the program.


CODING:

#Program to store strings in a list and display them cont="Y"

cont='Y'

mylist=[]

while [Link]()=='Y':

myStr=input("Enter a String :")

[Link](myStr)

cont=input("Do you want to continue (Y/N)?")

print("\n\nlist elements are...\n")

n=len(mylist)

for i in range(n):

print(mylist[i])
OUTPUT:

RESULT:

Thus the program has been created and executed Successfully.


[Link] FIND THE LENGTH OF A LIST,REVERSE IT,COPY IT AND THEN
CLEAR IT
DATE:

AIM:

To write a python program to find the list operations using built-in


functions.

ALGORITHM

Step1:Start the program.

Step2:Declare a string.

Step3:Using reverse (list,reverse()) to print list.

Step4:Using copy(list 2=cloning(list) to print list.

Step5:Using def list_length(list):to print list.

Step6:Using list,clear() to print list.

Step7:Stop the program.


CODING:

# program for list operations using built-in functions

n=int(input("How many elements in a list? "))

myList=[]

for i in range(n):

myVal=int(input("Enter list element: "))

[Link](myVal)

print("The List elements are: ")

for i in range(n):

print(myList[i],end= "")

print("\nThe length of the List is: ",len(myList))

myList1=myList[::-1]

print("The reverse of the List is: ",myList1)

print("The copy of the List is: ",[Link]())

print("The List after clear is: ",[Link]())


OUTPUT:

RESULT:

Thus the program has been created and executed Successfully.

Common questions

Powered by AI

The program initializes an array and iterates through each element, adding each to a sum variable. Once the loop completes, the total sum reflects the addition of all array elements, showcasing how loops and simple arithmetic operations can efficiently sum an array .

The program uses a loop to iterate through all potential divisors of the smaller of the two numbers, starting from 1. It checks for divisors that leave no remainder when both numbers are divided, updating a gcd variable whenever a common factor is found until all have been tested .

The two-pointer technique uses one pointer at the start and one at the end of the string, comparing characters for equality and moving inward simultaneously. If a mismatch occurs at any point, the string is determined not to be a palindrome. This efficient approach ensures a thorough check while minimizing steps .

The algorithm first converts the user-inputted radius from a string to a float. It then calculates the area using the formula π*r² and the perimeter using 2*π*r, taking π as approximately 3.142. The results are printed using formatted strings, effectively providing the circle's area and perimeter based on the given radius .

This program asks the user to define a list's elements, then applies several built-in functions: 'len()' to get the list's length, slicing to reverse the list, 'copy()' to duplicate it, and 'clear()' to remove all elements. These operations allow for comprehensive understanding of list manipulation in Python .

The program initializes the first two Fibonacci numbers as 0 and 1. It starts a loop from the third term up to the nth term, with the current term calculated as the sum of the previous two. This loop modifies the values of the previous two terms in each iteration and prints the current term, continuing until the nth Fibonacci number is reached .

The program asks the user for a number n, obtaining n natural numbers as input. It squares each number and accumulates these squares into a sum. After processing all inputs, it prints the cumulative sum, effectively demonstrating the calculation of sum of squares .

The function 'largest()' examines each element of the array, using an initial assumption that the largest element is the first element (arr[0]). It iterates over the array, updating a 'max' variable if a larger element is encountered. This systematic comparison ensures the largest value is returned at the end .

The algorithm checks for primality by iterating over numbers within the given range. For each number, it uses a nested loop to try dividing the number by all integers from 2 to n-1. If the number is divisible by any of these, a 'break' statement stops the check, indicating it's not prime. If no divisors are found, the 'else' clause of the loop executes, confirming the number is prime .

The program initializes an empty list and repeatedly prompts the user to input strings, storing them in the list while continuously checking if the user wants to add more strings. After exiting the loop based on user input, it iterates over the list to print each stored string, effectively demonstrating simple list operations .

You might also like