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

Python Programs

The document is a lab record for an MCA program containing various Python programming exercises. It includes tasks such as adding two numbers, calculating factorials, checking for Armstrong numbers, determining if a number is prime, and reversing words in a string. Each task is accompanied by example code and outputs to illustrate the solutions.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
6 views14 pages

Python Programs

The document is a lab record for an MCA program containing various Python programming exercises. It includes tasks such as adding two numbers, calculating factorials, checking for Armstrong numbers, determining if a number is prime, and reversing words in a string. Each task is accompanied by example code and outputs to illustrate the solutions.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 14

VIS

HNUPUR :: BHIMAVARAM

I MCA I SEMESTER
MOOCS LAB RECORD

DEPARTMENT OF MCA
INDEX
S. No Name of the Programs Page
No
1 Write a Python program to add two numbers? 1-2

2 Write a Python Program for factorial of a number 3

3 Write a Python Program to check Armstrong Number 4

4 Write a Python program to check whether a number is Prime or not 5

5 Write a Python Program for How to check if a given number is Fibonacci 6-7
number?
6 Write a Python program to interchange first and last elements in a list 7

7 Write a Python Ways to check if element exists in list 8

8 Write a Reverse words in a given String in Python 9

9 Write a Python Program to Check if a String is Palindrome or Not 10-11

10 Write a Python program to sort a list of tuples by second Item 12


1. Write a Python program to add two numbers?

Adding numbers in Python is a very easy task, and we have provided you 5 different ways to add
numbers in Python.
There are many methods to add two number in Python:
 Using “+” operator
 Defining a function that adds two number
 Using operator.add method
 Using lambda function
 Using Recursive function

Examples:
Input: num1 = 5, num2 = 3
Output: 8
Input: num1 = 13, num2 = 6
Output: 19

Method 1: Add Two Numbers with “+” Operator


Here num1 and num2 are variables and we are going to add both variables with the + operator in Python.

Program:

num1 = 13
num2 = 06
# Adding two nos
sum = num1 + num2
# printing values
print("Sum of", num1, "and", num2 , "is", sum)

Output:

Sum of 13 and 06 is 19

Method 2: Add Two Numbers with User Input


Add two numbers in Python, the user is first asked to enter two numbers, and the input is scanned using
the Python input() function and stored in the variables number1 and number2.
Then, the variable’s number1 and number2 are added using the arithmetic operator +, and the result is
stored in the variable sum.

Program:

number1 = input("First number: ")


number2 = input("\nSecond number: ")
# Adding two number
# User might also enter float numbers
sum = float(number1) + float(number2)
# Display the sum
# will print value in float
print("The sum of {0} and {1} is {2}" .format(number1, number2, sum)) 1 |Page
Output:

First number: 13.5 Second number: 1.54


The sum of 13.5 and 1.54 is 15.04

Method 3: Add Two Numbers Using operator.add() Method


Initialize two variables num1, and num2. Find sum using the operator.add() by passing num1, and num2
as arguments and assign to su. Display num1,num2 and su

Program:

num1 = 15
num2 = 12
# Adding two nos
import operator
su = operator.add(num1,num2)
# printing values
print("Sum of {0} and {1} is {2}" .format(num1,num2, su))

Output:
Sum of 15 and 12 is 27

Method 4: Add Two Number Using Lambda Function


Here we are going to use Python Lambda function for addition of two number with Python

Python Lambda Function:


Python Lambda Functions are anonymous functions means that the function is without a name. As we
already know the def keyword is used to define a normal function in Python. Similarly,
the lambda keyword is used to define an anonymous function in Python.

Program:
add_numbers = lambda x, y: x + y

# Take input from the user


num1 = 1
num2 = 2
# Call the lambda function to add the two numbers
result = add_numbers(num1, num2)
# Print the result
print("The sum of", num1, "and", num2, "is", result)

Output:

The sum of 1 and 2 is 3

2|Page
2. Write a Python Program for factorial of a number

This Python program uses a recursive function to calculate the factorial of a given number. The factorial
is computed by multiplying the number with the factorial of its preceding number.

Program:1

def factorial(n):

# single line to find factorial


return 1 if (n==1 or n==0) else n * factorial(n - 1)

# Driver Code
num = 5
print("Factorial of",num,"is",factorial(num))

Output:

Factorial of 5 is 120

Method 2: Factorial Function in Maths

In Python, math module contains a number of mathematical operations, which can be performed with
ease using the module. math.factorial() function returns the factorial of desired number.

Program:2

import math

def factorial(n):

return(math.factorial(n))

# Driver Code

num = 5

print("Factorial of", num, "is", factorial(num))


Output:

Factorial of 5 is 120

3|Page
3. Write a Python Program to check Armstrong Number

Given a number x, determine whether the given number is Armstrong number or not. A positive
integer of n digits is called an Armstrong number of order n (order is number of digits) if.

Formula::

abcd... = pow(a,n) + pow(b,n) + pow(c,n) + pow(d,n) + ....

Example:
Input : 153
Output : Yes
153 is an Armstrong number.
1*1*1 + 5*5*5 + 3*3*3 = 153

Input : 120
Output : No
120 is not a Armstrong number.
1*1*1 + 2*2*2 + 0*0*0 = 9
Program:1
# Python program to determine whether
# the number is Armstrong number or not

# Function to calculate x raised to


# the power y
def power(x, y):

if y == 0:
return 1
if y % 2 == 0:
return power(x, y // 2) * power(x, y // 2)

return x * power(x, y // 2) * power(x, y // 2)

# Function to calculate order of the number


def order(x):

# Variable to store of the number


n=0
while (x != 0):
n=n+1
x = x // 10

return n

# Function to check whether the given


# number is Armstrong number or not 4|Page

def isArmstrong(x):
n = order(x)
temp = x
sum1 = 0

while (temp != 0):


r = temp % 10
sum1 = sum1 + power(r, n)
temp = temp // 10

# If condition satisfies
return (sum1 == x)

# Driver code
x = 153
print(isArmstrong(x))

x = 1253
print(isArmstrong(x))

Output::
True
False

4. Write a Python program to check whether a number is Prime or not


Given a positive integer N, the task is to write a Python program to check if the number
is Prime or not in Python.
Example: Check Prime Number

Program:

# Negative numbers, 0 and 1 are not primes


if num > 1:

# Iterate from 2 to n // 2
for i in range(2, (num//2)+1):

# If num is divisible by any number between


# 2 and n / 2, it is not prime
if (num % i) == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")
else:
print(num, "is not a prime number")

Output:
11 is a prime number 5|Page

Explanation: The idea to solve this problem is to iterate through all the numbers starting from 2 to (N/2)
using a for loop and for every number check if it divides N. If we find any number that divides, we return
false. If we did not find any number between 2 and N/2 which divides N then it means that N is prime
and we will return True.

5. Write a Python Program for How to check if a given number is Fibonacci number?
Given a number \’n\’, how to check if n is a Fibonacci number. First few Fibonacci numbers are 0, 1,
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ..

Examples :
Input: 8
Output: Yes
Input: 34
Output: Yes
Input: 41
Output: No

# python program to check if x is a perfect square

import math

# A utility function that returns true if x is perfect square

def isPerfectSquare(x):

s = int(math.sqrt(x))

return s*s == x

# Returns true if n is a Fibonacci Number, else false

def isFibonacci(n):

# n is Fibonacci if one of 5*n*n + 4 or 5*n*n - 4 or both

# is a perfect square

return isPerfectSquare(5*n*n + 4) or isPerfectSquare(5*n*n - 4)

# A utility function to test above functions

for i in range(1, 11):

if (isFibonacci(i) == True):

print(i, "is a Fibonacci Number")

else:
print(i, "is a not Fibonacci Number ")
Output:

1 is a Fibonacci Number 6|Page


2 is a Fibonacci Number
3 is a Fibonacci Number
4 is a not Fibonacci Number
5 is a Fibonacci Number
6 is a not Fibonacci Number
7 is a not Fibonacci Number
8 is a Fibonacci Number
9 is a not Fibonacci Number
10 s a not Fibonacci Number
6. Write a Python program to interchange first and last elements in a list
Given a list, write a Python program to swap the first and last element of the list using Python.
Method:1
Examples: The last element of the list can be referred to as a list[-1]. Therefore, we can simply
swap list[0] with list[-1].
Program:1

# Initialize a list
my_list = [1, 2, 3, 4, 5]

# Interchange first and last elements


my_list[0], my_list[-1] = my_list[-1], my_list[0]

# Print the modified list


print("List after swapping first and last elements:", my_list)

Output:

List after swapping first and last elements: [5, 2, 3, 4, 1]

Method 2:Interchange first and last elements using Temporary Value


Find the length of the list and simply swap the first element with (n-1)th element.

Program::
# Swap function
def swapList(newList):
size = len(newList)

# Swapping
temp = newList[0]
newList[0] = newList[size - 1]
newList[size - 1] = temp

return newList

# Driver code
newList = [12, 35, 9, 56, 24]

print(swapList(newList))
7|Page

OutPut::
[24, 35, 9, 56, 12]

7. Write a Python Ways to check if element exists in list


we will explore various methods to check if element exists in list in Python. The simplest
way to check for the presence of an element in a list is using the in Keyword.

Program:1

a = [10, 20, 30, 40, 50]

# Check if 30 exists in the list


if 30 in a:
print("Element exists in the list")
else:
print("Element does not exist")

Output:

Element exists in the list

Method:2 Using a loop

Using for loop we can iterate over each element in the list and check if an element exists. Using this
method, we have an extra control during checking elements.

Program::2

a = [10, 20, 30, 40, 50]

# Check if 30 exists in the list using a loop


key = 30
flag = False

for val in a:
if val == key:
flag = True
break

if flag:
print("Element exists in the list")
else:
print("Element does not exist")

Output:

Element exists in the list

8|Page
8. Write a Reverse words in a given String in Python

We are given a string and we need to reverse words of a given string

Examples:

Input : str =" geeks quiz practice code"


Output : str = code practice quiz geeks
Input : str = "my name is laxmi"
output : str= laxmi is name my

Program:1

#Input string
string = "geeks quiz practice code"
# reversing words in a given string
s = string.split()[::-1]
l = []
for i in s:
# appending reversed words to l
l.append(i)
# printing reverse words
print(" ".join(l))

Output::

code practice quiz geeks

Method::2 Reverse Words Using Stack


Another approach to reverse the words in a given string is to use a stack. A stack is a data structure
that supports push and pop operations. You can use a stack to reverse the words in a string by
pushing the words onto the stack one by one and then popping them off the stack to form the
reversed string.

Here is an example of how you can use a stack to reverse the words in a given string in Python:

Program::1
# initializing string
string = "geeks quiz practice code"

# creating an empty stack


stack = []

# pushing words onto the stack


for word in string.split():
stack.append(word)

# creating an empty list to store the reversed words


reversed_words = []

9|Page
# popping words off the stack and appending them to the list
while stack:
reversed_words.append(stack.pop())

# joining the reversed words with a space


reversed_string = " ".join(reversed_words)

# printing the reversed string


print(reversed_string)

Output::
code practice quiz geeks
9. Write a Python Program to Check if a String is Palindrome or Not

Given a string, write a python function to check if it is palindrome or not. A string is said to be a
palindrome if the reverse of the string is the same as the string. For example, “radar” is a
palindrome, but “radix” is not a palindrome.

Examples:

Input : malayalam
Output : Yes
Input : geeks
Output : No

Method 1: Python Program to Check if a String is Palindrome or Not Using Native Approach
Here we will find reverse of the string and then Check if reverse and original are same or not.

Program:
# function which return reverse of a string

def isPalindrome(s):

return s == s[::-1]

# Driver code

s = "malayalam"

ans = isPalindrome(s)

if ans:

print("Yes")

else:
print("No")

Output:
Yes 10 | P a g e
Method 2: Check if a String is Palindrome or Not Using Iterative Method
Run a loop from starting to length/2 and check the first character to the last character of the string
and second to second last one and so on …. If any character mismatches, the string wouldn’t be a
palindrome.

Program:2
# function to check string is
# palindrome or not
def isPalindrome(str):
# Run loop from 0 to len/2
for i in range(0, int(len(str)/2)):
if str[i] != str[len(str)-i-1]:
return False
return True

# main function
s = "malayalam"
ans = isPalindrome(s)

if (ans):
print("Yes")
else:
print("No")
Output:
Yes
10. Write a Python program to sort a list of tuples by second Item
Sorting a list of tuples by the second item is a common task especially when we have to deal
with structured data. Python provides several ways to achieve this making use of its built-in
capabilities. Below are different methods to solve this problem.
Method1: Using sorted()
The sorted() function combined with a key parameter allows sorting based on specific tuple
elements, sorted() returns a new sorted list without altering the original list.

Program1:
a = [(1, 3), (4, 1), (2, 2)]
# Sort by second item 11 | P a g e
sorted_list = sorted(a, key=lambda x: x[1])
print("Sorted List:", sorted_list)
Output:

Sorted List: [(4, 1), (2, 2), (1, 3)]


Method2: Using sort()

The list.sort() method is similar to sorted() but sorts the list in-place modifying the original list
directly. It is efficient when we don’t need to retain the original list.
Program:2
a = [(5, 2), (1, 6), (3, 4)]
# Sort by second item (in-place)
a.sort(key=lambda x: x[1])
print("Sorted List:", a)
Output:
Sorted List: [(5, 2), (3, 4), (1, 6)]

12 | P a g e

You might also like