CAMELLIA INSTITUTE OF TECHNOLOGY
Python Lab – PCC CS393
                                INDEX
EXPERIMENT            TOPIC      EXPERIMENT SUBMISSION   SIGNATURE
    NO.                             DATE       DATE      OF FACULTY
1            INTRODUCTION
2            FLOW OF CONTROL
3            LIST
4            STRING
5            TUPLE
6            DICTIONARY
EXPERIMENT 1
INTRODUCTION
1. Add Two Numbers in Python.
Sol.:
        # Python3 program to add two numbers
        num1 = 15
        num2 = 12
        # Adding two nos
        sum = num1 + num2
        # printing values
        print("Sum of", num1, "and", num2 , "is", sum)
2. Add Two Numbers with User Input.
Sol.:
        # Python3 program to add two numbers
        number1 = float(input("First number: "))
        number2 = float(input("\nSecond number: "))
        # Adding two numbers - User might also enter float numbers
        sum = number1 + number2
        # Display the sum: will print value in float
        print("The sum of {0} and {1} is {2}" .format(number1, number2, sum))
3. Python Program for Simple Interest.
Sol.:
        P = int(input("Enter the principal amount :"))
        T = int(input("Enter the time period :"))
        R = int(input("Enter the rate of interest :"))
        si = (P * T * R)/100
        print('The Simple Interest is', si)
4. Python Program for Compound Interest. The formula to calculate compound interest annually
is given by: A = P(1 + R/100)T
Compound Interest = A – P
Where,
A is amount
P is the principal amount
R is the rate and
T is the time span
Sol.:
        # Python3 program to find compound interest for input taking from user.
        # Taking input from user.
        principal = int(input("Enter the principal amount: "))
        rate = float(input("Enter rate of interest: "))
        time = int(input("Enter time in years: " ))
        # Calculates compound interest
        amount = principal * (1 + rate / 100)**time
        CI = amount - principal
        print("Compound interest is ", CI)
5. Python Program to Find Area of a Circle.
Sol.:
        # Python program to find Area of a circle - using inbuild library
        # This program is using function
        import math
        def area(r):
         area = math.pi* pow(r,2)
         return print('Area of circle is:' ,area)
        # Driver program
        area(4)
6. Print ASCII value of a given character.
Sol.:
        c = 'g'
        # Print the ASCII value of assigned character in variable c
        # ord(): converts a string of length one to an integer representing the Unicode code
        print("The ASCII value of '" + c + "' is", ord(c))
EXPERIMENT 2
FLOW OF CONTROL
1. Find Maximum of two numbers in Python
Sol.:
        a)
        # using built-in max() function
        a=7
        b=3
        print(max(a, b))
        b)
        # using conditional statements
        a=5
        b = 10
        if a > b:
             print(a)
        else:
             print(b)
        c)
        # Using Ternary Operator
        a=7
        b=2
        res = a if a > b else b
        print(res)
2. Program to Find the Factorial of a Number.
Sol.:
        a)
        # Input: a positive integer number
        num = int(input(‘Enter a positive integer: ‘))
        # Initialize the factorial variable to 1
        factorial = 1
        # Calculate the factorial using a for loop
        for i in range(1, num + 1):
             factorial *= i
        # Output: The factorial of the number
        print(f”The factorial of {num} is {factorial}")
        b)
        # Get Factorial of a Number using a Recursive Approach
        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))
        c)
        # Using math.factorial() function calculate the factorial
        import math
        def factorial(n):
             return(math.factorial(n))
        # Driver Code
        num = 5
        print("Factorial of", num, "is",factorial(num))
3. Python Program to Check Prime Number.
Sol.:
        a)
        num = 11
        # 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")
        b)
        def is_prime(n):
             if n <= 1:
              return False
          for i in range(2, int(n**0.5) + 1):
              if n % i == 0:
                  return False
          return True
        # driver code
        num=int(input(‘Enter a positive integer: ‘))
        print(num,’ is prime’ if is_prime(num) else ‘ is not prime’)
4. Write a Python program to print the sum of series 13 + 23 + 33 + 43 + …….+ n3 till the n-th
term.
Sol.:
        # Program to find sum of series with cubes of first n natural numbers
        # Function - Returns the sum of series
        def sumOfSeries(n):
          sum = 0
          for i in range(1, n + 1):
              sum += i*i*i
          return sum
        # Driver code
        n=5
        print(sumOfSeries(n))
5. Python Program to Check Armstrong Number.
A positive integer of n digits is called an Armstrong number of order n (order is number of digits)
if abcd... = pow(a,n) + pow(b,n) + pow(c,n) + pow(d,n) + ....
Example:
Input : 153
Output : Yes
153 is an Armstrong number.
13 + 53 + 33 = 153
Sol.:
# python 3 program to check whether the given number is armstrong or not
n = 153 # or n=int(input()) -> taking input from user
s = n # assigning input value to the s variable
b = len(str(n))
sum1 = 0
while n != 0:
  r = n % 10
  sum1 = sum1+(r**b)
  n = n//10
if s == sum1:
  print("The given number ", s, " is armstrong number")
else:
  print("The given number ", s, " is not armstrong number")
EXPERIMENT NO. 3
LIST
1. Python program to interchange first and last elements in a list.
Sol.:
        # 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)
2. Python program to print even numbers in a list.
Sol.:
        a)
        # Using loop
        a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        # Iterate through each element in the list
        for val in a:
             # Checks if a number is divisible by 2 (i.e., even).
             if val % 2 == 0:
               print(val, end = " ")
        b)
        # Using list comprehension
        a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        # Create a list of even numbers using list comprehension
        res = [val for val in a if val % 2 == 0]
        print(res)
3. Count occurrences of an element in a list.
Sol.:
        a)
        # Using count()
        a = [1, 3, 2, 6, 3, 2, 8, 2, 9, 2, 7, 3]
        # Count occurrences of 2
        print(a.count(2))
        # Count occurrences of 3
        print(a.count(3))
        b)
        # Using loop – find the occurrence of 3
        a = [1, 3, 2, 6, 3, 2, 8, 2, 9, 2, 7, 3]
        # Initial count is zero
        count = 0
        # Iterate over the list
        for val in a:
             # If num is equal to 3
             if val == 3:
               # Increase the counter
                count += 1
        print(count)
4. Sum of number digits in List.
Sol.:
        # Function to sum digits of a number
        def dsum(val):
             total = 0 # Initialize the total sum of digits
             # Loop until number is reduced to zero
             while val > 0:
                # Add last digit to the total
                total += val % 10
                # Remove last digit from number
                val //= 10
             # Return total sum of digits
             return total
        a = [123, 456, 789]
        # Calculate sum of digits for each number - using list comprehension
        res = [dsum(val) for val in a]
        print(res)
EXPERIMENT 4
STRING
1. Program to Check if a String is Palindrome or Not.
Sol.:
        # function which return reverse of a string
        def isPalindrome(s):
             return s == s[::-1]
        # Driver code
        s = "malayalam"
        ans = isPalindrome(s)
        print("Yes" if ans else "No")
2. Reverse Words in a Given String.
Sol.:
        # Input string
        s = "COMPUTER SCIENCE AND ENGINEERING"
        # Split the string into words, reverse the list of words, and join them back
        reversed_words = ' '.join(s.split()[::-1])
        print(reversed_words)
3. Program to remove letters from a string.
Sol.:
        a)
        s = "hello world"
        s = s.replace("l", "")
        print(s)
        b)
        s = "hello world"
        # Initialize an empty string to store modified version of 's'
        s1 = ""
        # Iterate over each character in string 's'
        for c in s:
             # Check if current character is not 'o'
             if c != "o":
               # If it's not 'o', append character to 's1'
                s1 += c
        print(s1)
4. Program to print even length words in a string.
Sol.:
        # Python code to print even length words in string
        #input string
        n="This is a python language"
        #splitting the words
        s=n.split(" ")
        for i in s:
         #checking the length of words
         if len(i)%2==0:
           print(i)
5. Python program to check the strings which contains all vowels.
Sol.:
        s = "computer"
        v = 'aeiou'
        # check if each vowel exists in the string
        if all(i in s.lower() for i in v):
           print("True")
        else:
           print("False")
6. Python program for removing i-th character from a string.
Sol.:
        s = "PythonProgramming"
        # Index of the character to remove
        i=6
        # Removing i-th character
        res = s[:i] + s[i+1:]
        print(res)
EXPERIMENT NO 5
TUPLE
1. Maximum and minimum k elements in tuple.
Sol.:
        # Maximum and Minimum K elements in Tuple Using sorted() + loop
        # initializing tuple
        test_tup = (5, 20, 3, 7, 6, 8)
        # printing original tuple
        print("The original tuple is : " + str(test_tup))
        # initializing K
        K=2
        res = []
        test_tup = list(sorted(test_tup))
        for idx, val in enumerate(test_tup):
           if idx < K or idx >= len(test_tup) - K:
              res.append(val)
        res = tuple(res)
        # printing result
        print("The extracted values : " + str(res))
2. Write a program to swap two numbers without using a temporary variable.
Sol.:
        #Program to swap two numbers
        num1 = int(input('Enter the first number: '))
        num2 = int(input('Enter the second number: '))
        print("\nNumbers before swapping:")
        print("First Number: ",num1)
        print("Second Number: ",num2)
        (num1,num2) = (num2,num1)
        print("\nNumbers after swapping:")
        print("First Number: ",num1)
        print("Second Number: ",num2)
3. Write a program to compute the area and circumference of a circle using a function.
Sol.:
        # Function to compute area and circumference of the circle.
        def circle(r):
               area = 3.14*r*r
               circumference = 2*3.14*r
               return (area,circumference)          # returns a tuple having area and circumference
               # end of function
        # Driver program
        radius = int(input('Enter radius of circle: '))
        area,circumference = circle(radius)
        print('Area of circle is:',area)
        print('Circumference of circle is:',circumference)
4. Write a program to input n numbers from the user. Store these numbers in a tuple. Print the
maximum and minimum number from this tuple.
Sol.:
        numbers = tuple() #create an empty tuple 'numbers'
        n = int(input("How many numbers you want to enter?: "))
        for i in range(0,n):
               num = int(input())
               #it will assign numbers entered by user to tuple 'numbers’
               numbers = numbers +(num,)
        print('The numbers in the tuple are:')
        print(numbers)
        print("The maximum number is: “, max(numbers))
        print("The minimum number is: “, min(numbers))
EXPERIMENT 6
DICTIONARY
1. Write a program to enter names of employees and their salaries as input first and then display
all these records.
Sol.:
        num = int(input("Enter the number of employees whose data to be stored: "))
        count = 1
        employee = dict()                               #create an empty dictionary
        while count <= num:
                   name = input("Enter the name of the Employee: ")
                   salary = int(input("Enter the salary: "))
                   employee[name] = salary
                   count += 1
        print("\n\nEMP_NAME\tSALARY")
        for k in employee:
                   print(k,'\t\t',employee[k])
2. Write a program to count the number of times a character appears in a given string.
Sol.:
        st = input("Enter a string: ")
        dic = {}                                        #creates an empty dictionary
        for ch in st:
                   if ch in dic:                 #if next character is already in the dictionary
                           dic[ch] += 1
                   else:
                           dic[ch] = 1           #if ch appears for the first time
        for key in dic:
                   print(key,':',dic[key])
3. Write a program to convert a number entered by the user into its corresponding number in
words. For example, if the input is 876 then the output should be ‘Eight Seven Six’.
Sol.:
        # function to convert number into corresponding number in words.
        def convert(num):
                   #numberNames is a dictionary of digits and corresponding number names
                   numberNames = {0:'Zero',1:'One',2:'Two',3:'Three',4:'Four’,\
                                                 5:'Five',6:'Six',7:'Seven',8:'Eight',9:'Nine’}
               result = ‘’
               for ch in num:
                       key = int(ch) #converts character to integer
                       value = numberNames[key]
                       result = result + ' ' + value
               return result
        num = input("Enter any number: ")                       #number is stored as string
        result = convert(num)
        print("The number is:",num)
        print("The number Name is:",result)
4. Check if binary representations of two numbers are anagram.
Given two numbers you are required to check whether they are anagrams of each other or not
in binary representation.
Examples:
Input : a = 8, b = 4
Output : Yes
Binary representations of both numbers have same 0s and 1s.
Input : a = 4, b = 5
Output : No
Sol.:
from collections import Counter
def checkAnagram(num1,num2):
  # convert numbers into in binary and remove first two characters of
  # output string because bin function '0b' as prefix in output string
  bin1 = bin(num1)[2:]
  bin2 = bin(num2)[2:]
  # append zeros in shorter string
  zeros = abs(len(bin1)-len(bin2))
  if (len(bin1)>len(bin2)):
        bin2 = zeros * '0' + bin2
  else:
        bin1 = zeros * '0' + bin1
  # convert binary representations into dictionary
  dict1 = Counter(bin1)
  dict2 = Counter(bin2)
  # compare both dictionaries
  if dict1 == dict2:
     print('Yes')
  else:
     print('No')
# Driver program
if __name__ == "__main__":
  num1 = 8
  num2 = 4
  checkAnagram(num1,num2)