Python Programs
Python Programs
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
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
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
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
Program:
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
Program:
add_numbers = lambda x, y: x + y
Output:
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):
# Driver Code
num = 5
print("Factorial of",num,"is",factorial(num))
Output:
Factorial of 5 is 120
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
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::
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
if y == 0:
return 1
if y % 2 == 0:
return power(x, y // 2) * power(x, y // 2)
return n
def isArmstrong(x):
n = order(x)
temp = x
sum1 = 0
# If condition satisfies
return (sum1 == x)
# Driver code
x = 153
print(isArmstrong(x))
x = 1253
print(isArmstrong(x))
Output::
True
False
Program:
# Iterate from 2 to n // 2
for i in range(2, (num//2)+1):
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
import math
def isPerfectSquare(x):
s = int(math.sqrt(x))
return s*s == x
def isFibonacci(n):
# is a perfect square
if (isFibonacci(i) == True):
else:
print(i, "is a not Fibonacci Number ")
Output:
# Initialize a list
my_list = [1, 2, 3, 4, 5]
Output:
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]
Program:1
Output:
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
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:
8|Page
8. Write a Reverse words in a given String in Python
Examples:
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::
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"
9|Page
# popping words off the stack and appending them to the list
while stack:
reversed_words.append(stack.pop())
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:
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