Python Laboratory Excersices

L1_2.2 Python Programs


Step 1: Type the Python program using a text editor such as gedit or vi or emacs or Kwrite and save as test1.py ($ gedit test1.py)
Step 3: Modify the above program to display the source code.

# Step 1
# ******** #

# display Hello World

print "Hello world !\n"

# Step 3
# ******** #

print "# display Hello World\n"
print "print \"Hello world !\\n\"\n"

L1_2.3 Syntax Errors and Bugs


Shown below is a Python program intended to compute the roots of the quadratic equation ax2 + bx + c = 0 provided that b2 - 4ac ≥ 0, given integers a, b and c.

# Code with errors

a = int(input("Enter a :))   # Error_1 : Syntax error
b = int(input("Enter b :"))
c = int(input("Enter c :"))
delta = b*b - 4*c
if delta < 0:
print "complex roots !"    # Error_2 : Indentation error
else:
 t= math.sqrt(delta)   # Error_3 : Math module has not been imported
 r1= (-b -t) / (2*a)
 r2= (-b +t) / (2*a)
 print "Roots are: ", r1, r2  # display the roots
 
 
# Corrected code

import math
a = int(input("Enter a :"))
b = int(input("Enter b :"))
c = int(input("Enter c :"))

if a==0:
 print "Coefficient a should be non-zero.\n"
else:
 delta = b*b - 4*c
 if delta < 0:
  print "complex root !"
 else:
  t= math.sqrt(delta)
  r1= (-b -t) / (2*a)
  r2= (-b +t) / (2*a)
  print "Roots are: ", r1, r2 # display the roots

L1_2.4 Comparing Python and C


Shown below is a C program intended to compute the roots of the quadratic equation ax2 + bx + c = 0 provided that b2 - 4ac ≥ 0, given integers a, b and c. This C programm was developed by referring to the Python program above.

#include <stdio.h>
#include <math.h>
int main( )
{
 int  a, b, c, delta;
 float t, r1, r2;
 printf("Enter a :");
 scanf("%d", &a);
 printf("Enter b :");
 scanf("%d", &b);
 printf("Enter c :");
 scanf("%d", &c);
 if (a==0)
  printf ("Coefficient a should be non-zero.\n");
 else {
  delta = b*b - 4*a*c;
  if (delta < 0)
   printf("Complex roots !\n");
  else {
   t = sqrt(delta);
   r1 = (-b -t) / (2*a);
   r2 = (-b +t) / (2*a);
   printf("Roots are: %f %f\n", r1, r2);
  }
 }
 return 0;
}

Compile the code as follows. This will produce an executable file a.out.

$ gcc test2.c -lm

Run the executable as follows.

$ ./a.out -lm

L3 Conditional Control Structures


L3.E1

Develop a program to input a temperature reading in either Celsius (C) or Fahrenheit (F) scale and convert it to the other scale. The temperature reading consists of a decimal integer followed by letter "F" or "f" if the temperature is in Fahrenheit scale or letter "C" or "c" if it is in Celsius scale. You may use a similar format for the output of the program. You must draw a flowchart to express the algorithm of your program.

Note : 9C = 5(F - 32)


# Get input from user
Temp = raw_input("Temperature reading : ")

# Identify scale
Scale = str(Temp[-1])

# Identify the value
T = int(Temp[:-1])


# Check if Scale is Celsius
if (Scale == "C" or Scale == "c"):
    # Calculate the corresponding Fahrenheits value
    Result = str((9 * T) / 5 + 32) + "F"

    # Display result
    print Result

# Check if Scale is Fahrenheits
elif (Scale == "F" or Scale == "f"):
    # Calculate the corresponding Celsius value
    Result = str(5 * (T - 32) / 9) + "C"

    # Display result
    print Result

# If input doesn't contain a "F" or "C" print error message.
else:
    print "Wrong Input"

L3.E2

Given a date as a triplet of numbers (y, m, d), with y indicating the year, m the month (m = 1 for January, m = 2 for February, etc..) and d the day of the month, the corresponding day of the week f (f = 0 for Sunday, f = 1 for Monday, etc..) can be found as follows:

  1. If m < 3, let m = m + 12 and let y = y - 1
  2. Let a = 2m + 6(m + 1) / 10
  3. let b = y + y/4 - y/100 + y/400
  4. let f1 = d + a + b + 1
  5. Let f = f1 mod 7
  6. Stop

Develop a program that will read a date and print the corresponding day of the week. All divisions indicated above are integer divisions. You must draw a flowchart to express the algorithm of your program.



# Get date from user
Date = tuple(input("Enter date (y,m,d) : "))

# Assign values to Year, Month and Date
y = Date[0]
m = Date[1]
d = Date[2]

# Check if "m" is less than 3
if (m < 3):
    # If "m" is less than 3, "m" is "m + 12" and "y" is "y - 1"
    m = m + 12
    y = y - 1

# ----- Calculations -----
a = (2 * m) + 6 * (m + 1) / 10
b = y + (y / 4) - (y / 100) + (y / 400)
f1 = d + a + b + 1
f = f1 % 7

# Match "f" value with corresponding day and display day
if (f == 0):
    print "Sunday"
elif (f == 1):
    print "Monday"
elif (f == 2):
    print "Tuesday"
elif (f == 3):
    print "Wednesday"
elif (f == 4):
    print "Thursday"
elif (f == 5):
    print "Friday"
elif (f == 6):
    print "Saturday"

L3.E3

Develop a program to implement a simple arithmetic calculator. First display a menu of 4 operations to the user to choose from (e.g., 1 - addition, 2 - subtraction, 3 - multiplication, 4 - division). After the operation is selected, ask the user to enter two numbers. Then perform the selected operation between the two numbers and display the result. After implementing the basic calculator, try to enhance it by adding features (e.g., add more operations to the menu such as integer division and modulo division, add exception handling, handle division by zero, formatting of results,...)


# Displaying calculator menu
print "*--------------------------*"
print "*--   Calculator  Menu   --*"
print "*-- 1 . Addition         --*"
print "*-- 2 . Subtraction      --*"
print "*-- 3 . Multiplication   --*"
print "*-- 4 . Division         --*"
print "*-- 5 . Integer Division --*"
print "*-- 6 . Modulo Division  --*"
print "*--------------------------*\n"

# Get operation type from user
Operation = int(raw_input("Select an operation : "))

# Get two numbers from user
num1 = int(raw_input("Enter first value : "))
num2 = int(raw_input("Enter second value : "))

# Evaluate operation number and perform the corresponding operation with two values given.
# Addition
if (Operation == 1):
    Result = num1 + num2

# Subtraction
elif (Operation == 2):
    Result = num1 - num2
    if Result < 0:
        Result = "(" + str(Result) + ")"

# Multiplication
elif (Operation == 3):
    Result = num1 * num2

# Division
elif (Operation == 4):
    if (num2 == 0):    # Handle dividing by zero
        Result = "Cannot divide by zero"
    else:
        Result = num1 / num2

# Integer division
elif (Operation == 5):
    Result = num1 // num2

# Modulo division
elif (Operation == 6):
    Result = num1 % num2

# Operation value anything other than 1 - 6
else:
    print "Wrong operation ID"

print Result,
print "\n"

L5 Loop Control Structures


L5.E1

Develop a program that takes as input a series of positive integers and outputs whether each is a prime. The program should terminate if a negative integer is given as the input. A prime number is a number that is divisible by only one and itself. However one is not considered a prime number.


# Creating a boolean variable to manipulate the while loop.
positive = True

# There're consecutive inputs. So we need a loop.
while(positive):

    # Getting input from user
    try:
        num = int(input())

    # Check input data for errors.
    except (TypeError, ValueError, NameError, SyntaxError):     
        print "Try again with a number :)"
        # End the loop...
        continue

    # For 1 is not a prime... continue the main loop without breaking.
    if num == 1:
        positive = True
        continue
    
    # Check whether the input is positive or negative to terminate the program.
    elif num >= 0:

        if num == 0:
            continue

        # Prime number divides by only 1 and that number itself. If not, 'num' is not a prime.
        for x in range(2, num):
            if num % x == 0:
                break
        # If 'num' has no divisibles upto that number, then it is a prime.
        else:
            print "prime"

        # Keeps the loop running because 'num' is positive
        positive = True

    # Terminates the loop by making the while condition false because 'num' is negative.    
    else:
        positive = False

L5.E2

Develop a program that takes as input a series of positive integers and outputs whether each is a perfect number. The program should terminate if a negative integer is given as the input. A perfect number is a number whose factors other than itself add up to itself. Examples: 6 = 1 + 2 + 3, 28 = 1 + 2 + 4 + 7 + 14


# Creating a boolean variable to manipulate the while loop.   
positive = True

while(positive):
    # Get input from user
    try:
        value = int(input())

    # Check input data for errors.
    except (TypeError, ValueError, NameError, SyntaxError):     
        print "Try again with a number :)"
        # End the loop...
        continue

    # This loop might come across with an out of range error.
    try:
        # Check if the value is positive to continue the loop.
        if (value >= 0):

            if value == 0:
                continue

            # Create a number to add up all the factors of value.
            number = 0

            # Creating a list of numbers below value excluding value.
            for i in range(1, value):
    
                # If a number is a factor of value, add it to 'number'.
                if (value % i == 0):
                    number += i
    
            # If the number is equal to value, it is a perfect number.
            if (number == value):
                print "perfect"
    
            # If not, it's not a perfect number.
            else:
                continue
    
            # Keeps the loop running because value is positive.
            positive = True
    
        # Terminates the loop by making the while condition false because value is negative.
        else:
            positive = False

    # In case of an out of range error,        
    except (MemoryError):
        print "Number is too large to process :("
        # End the programme...
        positive = False
        break

L5.E3

Develop a program to implement the "Guess the Number" game. In this game, the program thinks of a random integer in the range[1, 20] and asks the user to guess it. The user gets only four attempts, and for each wrong guess, the program will tell if the guess is too high or too low. To win the game, the user has to correctly guess the number within four attempts.


# Importing random module.
import random

# Introducing the game.
print "Welcome to \"Guess the Number\""
print "You got 4 attempts to guess the number between 1 and 20 and WIN :)"
print "Good Luck!!!\n"

# Generate a random number between 1 and 20.
rnd_num = random.randint(1, 20)

# Defining number of attempts
attempts = 4


# This loops the game for 4 times and ends after 4 attempts.
while(attempts > 0):
    
    # Get guess from user
    try:
        guess = int(input("Enter your guess : "))

    # Check input data for errors.
    except (TypeError, ValueError, NameError, SyntaxError):     
        print "Try again with a number :)"
        # End the loop...
        continue

    # If the guess is same as the random number, won and

    if (guess > 20 or guess < 1):
        print "Number is between 1 and 20. Try again :)"
        attempts -= 1
        continue
    
    if (guess == rnd_num):
        print "Congratz!!! You guessed it right!!!"
        # Game over
        break
    
    else:
        # Attempts get reduced everytime the guess is wrong.
        attempts -= 1

        # Create an empty string to store the distance message
        low_or_high = ""
        
        # If the guess is more than the number,
        if (guess > rnd_num):
            # say it's too high.
            low_or_high = "Your guess is too high. "

        # If the guess is less than the number,
        elif (guess < rnd_num):
            # say it's too low.
            low_or_high = "Your guess is too low. "

        # Display a message saying if the guess is high or low and number of attempts left.
        if attempts > 0:
            print "Try again!!! " + low_or_high + str(attempts) + " attempts left..."
        else:
            print "Sorry try again."

L6 Lists


L6.E1

Develop a program to compute and display the total and the average of 10 integer inputs from the keyboard. You must use a list to store the 10 integers.


# Define a boolean variable to use in the while loop
proceed = True

while (proceed):

    # Get input from user
    usr_in = raw_input("Enter 10 Integers : ")

    # Store the values to a list
    lst = usr_in.split(" ")

    # User have to enter 10 values. If not prompt him to enter again.
    if len(lst) != 10:
        print "You have to enter 10 values..."
        continue

    # Create an empty variable to store the sum of digits in the list
    Total = 0

    # List might contain non integers,
    try:
        for i in range(10):
            Total += int(lst[i])
            
    except (ValueError):
        print "Try again with 10 numerical values... :)"
        continue

    # Calculate the average
    Average = float(Total) / 10
    
    # Display results
    print "Total =", Total
    print "Average = %.2f" % Average

    # End the loop
    proceed = False

L6.E2

Develop a program to find and display the minimum and the maximum among 10 numbers entered from the keyboard. You must use a list to store the numbers entered. The numbers can be non-integers.


# Define a boolean variable to be used in the while loop
proceed = True

while (proceed):

    # Get 10 numbers from user
    usr_in = raw_input("Enter 10 Integers : ")

    # Store the values to a list
    lst = usr_in.split(" ")

    # User have to enter 10 values. If not prompt him to enter again.
    if len(lst) != 10:
        print "You have to enter 10 values..."
        continue

    # Create empty variables to store the maximum number and the minimum number
    Maxi = 0
    Mini = lst[0]

    # Create an empty variable to store the corresponding index value
    Max_index_value = 0
    Min_index_value = 0

    # ----- MINIMUM ------ #
    
    # List might contain non integers,
    try:
        for i in range(10):

            # If the preceding value is smaller than the following value,
            # following number is the maximum.
            if (Maxi < float(lst[i])):
                Maxi = float(lst[i])
                Max_index_value = i

    except (ValueError):
        print "Try again with numbers... :)"
        continue
    
    # Display the maximum number
    print "Maximum =", lst[Max_index_value]


    # ----- MINIMUM ------ #

    # List might contain non integers,
    try:
        for j in range(10):

            # If the preceding value is greater than the following value,
            # following number is the minimum.
            if (Mini > float(lst[j])):
                Mini = float(lst[j])
                Min_index_value = j

    except (ValueError):
        print "Try again with numbers... :)"
        continue
    
    # Display the minimum number
    print "Minimum =", lst[Min_index_value]

    # End the loop
    proceed = False

L6.E3

Suppose there are 4 students each having marks of 3 subjects. Develop a program to read the marks from the keyboard and calculate and display the total marks of each student. Use a 2D list to store the marks.


# Create an empty list of 4 sub lists to store marks.
marks_lst = [[0] for x in range(4)]

# Create an empty variable to make the while loop runs 4 times.
student = 0

# Prompt user to enter marks
print "Enter the marks of four students, on four rows :"

# Get input from user.
while (student < 4):
    
    value = raw_input()

    # Split the values into the main list
    marks_lst[student] = value.split(" ")

    # For there are 3 subjects,
    if len(marks_lst[student]) != 3:
        print "Three subjects are there... :)"
        continue
    
    # In case if someone tries non-integers here :)
    try:
        for i in range(3):
            Type = type(int(marks_lst[student][i]))

    except (ValueError):
        print "Marks can only be numbers..."
        continue

    # Go for the next student data
    student += 1

# Create a new list to store the totals of each student seperately.
Lst = [0 for x in range(4)]

for i in range(4):

    # Create a dummy value to store the summation inside the loop
    Total = 0
    
    for j in range(3):
        Total += int(marks_lst[i][j])
    # Assign the value to the corresponding Lst item 
    Lst[i] = str(Total)

# Display the result
print "\nTotal marks of four students : "
print "\n".join(Lst)

L6.E4

Develop a program to read names of two sports that you and your friends love to play and watch. Then generate all sentences where the subject is in ["I", "We"], the verb is in ["play", "watch"] and the object is in the two sports. Use lists to store the words and generate the sentences by iterating through the lists using deeply nested loops.


# Create the subject list
subject_lst = ["I", "We"]

# Create the verb list
verb_lst = ["play", "watch"]

verified = True

while (verified):

    # Get input sports from user
    sports = raw_input("Enter two sports you love : ")

    # Assign those input sports values to a list
    sports_lst = sports.split(" ")

    if len(sports_lst) != 2:
        print "You have to enter only two sports... :)"
        continue

    string1 = sports_lst[0]
    string2 = sports_lst[1]

    if string1.isalpha() and string2.isalpha():
        pass
    else:
        print "That's not right... :("
        continue

    # Subject is common in the first 4 lines.
    for i in range(2):

        # Sport is common in the first two times.
        for j in range(2):

            # Verb is alternating through out the sentence.
            for k in range(2):
                print subject_lst[i] + " " + verb_lst[k] + " " + sports_lst[j] + ". ",

    verified = False

L7 Functions


L7.E1

Develop a program to read in two matrices A and B with dimensions 3 x 4 and 4 x 3 respectively, and compute and display their product AB (of dimensions 3 x 3), Assume that the elements of the matrices are integers. You must use functions while implementing this program.

Hint: Define global variables of two-dimensional arrays to store the value of the matrices A and B. Break down the program into thre functions as follows.

  1. Read in the elements of matrices A and B
  2. Compute the product of the two matrices
  3. Display the resultant matrix AB

global A
global B
global AB


def print_matrix():
    "Function to print a given matrix"

    # Number of rows in the matrix
    rows = len(AB)
    # Number of colomns in the matrix
    cols = len(AB[0])

    # Access each row by i
    for i in range(rows):

        # Access each colomn by j
        for j in range(cols):

            print AB[i][j],
        print "\n",
# ---------------------------------------------------------------------------------------------- #

        
def read_matrix(Matrix):
    "Function to get and assign value to a matrix format"
    # Matrix = Name of the matrix

    # Number of rows in the matrix
    rows = len(Matrix)
    # Number of colomns in the matrix
    cols = len(Matrix[0])

    # Define a variable to use in the while loop
    num = 0

    while (num < rows):

        # Get input from user
        value = raw_input()

        # Split 'value' and assign it to the relevant matrix
        Matrix[num] = value.split(" ")

        # Check if the whole row is filled
        if len(Matrix[num]) != cols:
            print "Please enter", str(cols), "values... :)"
            continue

        # Check if row values are numerics
        try:
            for i in range(cols):
                Type = type(int(Matrix[num][i]))

        except (ValueError, TypeError):
            print "You can enter numerical values only... :("
            continue
        
        num += 1
# ---------------------------------------------------------------------------------------------- #
        

def multiply_matrix():
    "Function to multiply two matrices and assign the relevant value to another format matrix"
    
    rows = len(A)
    cols = len(B)

    for i in range(rows):

        for j in range(rows):

            # Define an empty variable to add up the multiplied values
            count = 0
            
            for k in range(cols):
                count = count + (int(A[i][k]) * int(B[k][j]))

            # Assign the sum of multiplied value to the relevant cell of the resultant matrix
            AB[i][j] = count
# ---------------------------------------------------------------------------------------------- #

    

# Creating global 2D lists to store values of the matrices
A = [[0 for x in range(4)] for x in range(3)]
B = [[0 for x in range(3)] for x in range(4)]
AB = [[0 for x in range(3)] for x in range(3)]


# ------------ MAIN PROGRAMME ------------ #

print "Matrix A;"
read_matrix(A)

print "\nMatrix B;"
read_matrix(B)

# Multiply A and B using the function
multiply_matrix()

# Display results
print "\nMatrix AB;"
print_matrix()

# ----------------- END ----------------- #

Comments

Popular posts from this blog

Mocking Point Clouds in ROS Rviz

Find Maximum Number in a Nested List Recursively