S.No Program No. 1 1 2 3 3 3 4 3 5 3 6 4 7 5 8 6 9 7 10 8 11 8 12 10 13 11 14 12 15 13 16 14 17 16 18 17 19 18 20 21 21 24

Download as pdf or txt
Download as pdf or txt
You are on page 1of 37

PAGE

S.NO PROGRAM
No.
1 Introduction To Python Programming 1
2 Write a python program to print ” Hello “ message 3
Write a program to perform addition, subtraction, multiplication, division
3 3
on two input numbers
4 Write a program to calculate Employee payroll 3
5 Python program to take in the marks of 5 subjects and display the grade. 3
Python Program to Find All Odd Palindrome Numbers in a Range
6 4
without using Recursion
7 Python Program to Count the Number of Words in a Text File 5

8 Python Program to Read a Number n and Print the Series “1+2+…..+n= “ 6


Python Program to Find the Second Largest Number in a List using
9 7
Bubble Sort
10 Python Program to Find Sum of Series 1 + 1/2 + 1/3 + 1/4 + ……. + 1/N 8
11
Python Program to Print Largest Even and Largest Odd Number in a List 8
Python Program to Print Numbers in a Range Without using Loops or
12 10
using functions
13 Python Program to Merge Two Lists and Sort it 11
14 Python Program to Split Even and Odd Elements into Two Lists 12
Python Program to Count the Occurrences of Each Word in a Given
15 13
String Sentence
16 Python Program to Map Two Lists into a Dictionary 14

17 Python Program to Remove a Key from a Dictionary 16


Python Program that Displays Letters that are not Common in Two
18 17
Strings
Python Program to Create a Class which Performs Basic Calculator
19 18
Operations
Python Program to Append, Delete and Display Elements of a List using
20 21
Classes
21 Introduction to MatLab 24
Programs on Basic Mathematical and formatting programs in MatLab
a. Matlab program for addition of 2 numbers using MatLab
22 command prompt 27
b. Evaluation of an mathematical equation using math operations
c. Finding out the square , cube and square root of a number
Programs on Simple Math functions and conditional statements
a. Program on math functions sin() and exp() and constant pi
23 b. Program on for loop to print the repeated number 27
c. Check whether the given number is >5 or not.
d. Check whether the given number is in specified range.
Arrays and vectors in MatLab
a. Addition and multiplication of 1D array and 2D array
respectively, element-by-element multiplication.
24 28
b. Defining vectors and performing an elementary function sin () on
this vectorial variable.
c. Solving the given linear equation
Programs on Nested if and equations
a. Write a program to find area of circle of radius3
25 b. Print the biggest number among the 3 given numbers using nested 30
if else
c. Program to find the distance between 2 points
26 Write a program to demonstrate line spacing on graph plane 31
Programs on Graphs
a. Write a program to demonstrate two graph with diff input sine and
27 32
cosine
b. Write a program to demonstrate 2D graph
IT Workshop Lab

PC352IT

Instruction: 2 periods per week Duration of SEE: 3 hours


CIE: 25marks SEE:50marks
Credits: 1

Objectives:

1. To learn programming of python with a focus of basic structure.


2. To gain programming skills of python using function and OOP concept.
3. To gain practical knowledge of MATLAB toolkit along with operations in matrices and plotting
2D graph.

Outcomes:

After completing this course, the student will be able to:

1. Implement basic syntax in python.

2. Analyse and implement different kinds of OOP concept in real world problems.

3. Implement MATLAB operations and graphic functions.

List of Programming Exercises:

1 Python Variables, Executing Python from the Command Line, Editing Python Files, Python
Reserved Words
2 Comments, Strings and Numeric Data Types, Simple Input and Output.
3 Control Flow and Syntax, Indenting, if Statement, Relational Operators, Logical Operators,
Bit Wise Operators, while Loop, break and continue, for Loop, Lists, Tuples, Sets,
Dictionaries.
Functions: Passing parameters to a Function, Variable Number of Arguments, Scope,
4 Passing Functions to a Function, Mapping Functions in a Dictionary, Lambda, Modules,
Standard Modules.
OOP concepts: Classes, File Organization, Special Methods, Inheritance, Polymorphism,
5 Special Characters, Character Classes, Quantifiers, Dot Character, Greedy Matches,
Matching at Beginning or End, Match Objects, Compiling Regular Expressions.
6 MATLAB Menus, Toolbars, Computing with MATLAB, Script Files and the
Editor/Debugger, MATLAB help System.
MATLAB controls: Relational Logical Variables. Conditional Statements: if – else – elseif,
7 switch , Loops: for – while – break, continue. User-Defined Functions

8 Arrays, Matrices and Matrix Operations Debugging MATLAB Programs. Working with
Data Files, and Graphing Functions: XY Plots –Sub-plots.

Suggested Readings:

1 Mark Summerfield,‖ Programming inPython


2 A Complete introduction to the Python Language‖, Addison-Wesley Professional,2009.
3 Martin C. Brown,‖ PYTHON: The Complete Reference‖, McGraw-Hill,2001.
4 W.J. Palm III, Introduction to MATLAB 7 for Engineers, McGraw-Hill International
Edn,2005.
5 Wesley J Chun,‖ Core Python Applications Programming‖, Prentice Hall,2012.
6 Allen B Downey,‖ Think Python‖, O„Reilly,2012.
7 Stormy Attaway, ―MATLAB: A Practical Introduction to Programming and Problem
Solving‖.3 rd Edition.
INTRODUCTION TO PYTHON PROGRAMMING

Python is developed by Guido van Rossum. Guido van Rossum started implementing Python in 1989.
Python is a very simple programming language so even if you are new to programming, you can learn
python without facing any issues.

Interesting fact: Python is named after the comedy television show Monty Python’s Flying Circus. It is
not named after the Python snake.

Features of Python programming language

1. Readable: Python is a very readable language.

2. Easy to Learn: Learning python is easy as this is a expressive and high level programming language,
which means it is easy to understand the language and thus easy to learn.

3. Cross platform: Python is available and can run on various operating systems such as Mac, windows,
Linux, Unix etc. This makes it a cross platform and portable language.

4. Open Source: Python is a open source programming language.

5. Large standard library: Python comes with a large standard library that has some handy codes and
functions which we can use while writing code in Python.

6. Free: Python is free to download and use. This means you can download it for free and use it in your
application. Python is an example of a FLOSS (Free/Libre Open Source Software), which means you
can freely distribute copies of this software, read its source code and modify it.

7. Supports exception handling: If you are new, you may wonder what is an exception? An exception
is an event that can occur during program exception and can disrupt the normal flow of program.
Python supports exception handling which means we can write less error prone code and can test
various scenarios that can cause an exception later on.

8. Advanced features: Supports generators and list comprehensions. We will cover these features later.

9. Automatic memory management: Python supports automatic memory management which means
the memory is cleared and freed automatically. You do not have to bother clearing the memory.

What Can You Do with Python?

You may be wondering what all are the applications of Python. There are so many applications of
Python, here are some of the them.
1. Web development – Web framework like Django and Flask are based on Python. They help you
write server side code which helps you manage database, write backend programming logic,
mapping urls etc.
2. Machine learning – There are many machine learning applications written in Python. Machine
learning is a way to write a logic so that a machine can learn and solve a particular problem on its

1
own. For example, products recommendation in websites like Amazon, Flipkart, eBay etc. is a
machine learning algorithm that recognises user’s interest. Face recognition and Voice recognition
in your phone is another example of machine learning.
3. Data Analysis – Data analysis and data visualisation in form of charts can also be developed using
Python.
4. Scripting – Scripting is writing small programs to automate simple tasks such as sending
automated response emails etc. Such type of applications can also be written in Python
programming language.
5. Game development – You can develop games using Python.
6. You can develop Embedded applications in Python.
7. Desktop applications – You can develop desktop application in Python using library like TKinter
orQT.

How to install Python

Python installation is pretty simple, you can install it on any operating system such as Windows, Mac
OS X, Ubuntu etc. Just follow the steps in this article – Python Installation
You can install Python on any operating system such as Windows, Mac OS X, Linux/Unix and others.
To install the Python on your operating system, go to https://www.python.org/downloads/.You will see
a screen like this.

This is the official Python website and it will detect the operating system and based on that it would
recommend you to download Python. Here I am using Mac OS X so it gave me the download options
for Python 2 and Python 3 for Mac OS X. I would recommend you to download the latest version of
Python 3 (Python 3.6.4 in the screenshot).

Installation steps are pretty simple. You just have to accept the agreement and finish the installation.

NOTE:If you are using Mac OS X then you may notice that Python is already installed in your system,
however it would most likely be a Python 2 so you can download the latest Python 3 version from here
and install it in your system.

2
MJCET IT WORKSHOP

1. Write a python program to print ” Hello “ message.

print('Hello,world!')

# ##Python has very simple syntax. You can start write your code directly, i.e.,no main funtion
inpython.Print()function prints the given object inscreen or device.###

Sample Output: Hello, world!

2. Write a program to perform addition, subtraction, multiplication, division on two input


numbers

num1=int(input("Enter First number:"))


num2=int(input("Enter second number:"))
sum1=num1+num2
diff=num1-num2
product=num1*num2
quotient=num1/num2
print(sum1)
print(diff)
print(product)
print(quotient)

Sample Input
5
5
Sample Output
10
0
25
1

3. Write aprogramto calculate Employee payroll

days=float(input("Enter No Days Present:"))


wages=float(input("Enter wages per Day:"))
basic=wages*days;
HRA=basic*0.1;DA=basic*0.05;PF=basic*0.12;netsalary=basic+HRA+DA-PF;
print("\nBasic:%lf \nHRA:%lf \nDA:%lf \nPF:%lf \nNet Salary:%lf"%(basic,HRA,DA,PF,netsalary));

SampleInput:
300
30

Sample Output:

BasicPay:3000DA: 150HRA:300PF:360 NetPay:3090

4. Python program to take in the marks of 5 subjects and display the grade.

This is a Python Program to take in the marks of 5 subjects and display the grade.

Problem Description
The program takes in the marks of 5 subjects and displays the grade.

Problem Solution
1. Take in the marks of 5 subjects from the user and store it in different variables.
2. Find the average of the marks.
3. Use an else condition to decide the grade based on the average of the marks.
4. Exit.

3
MJCET IT WORKSHOP

Program/SourceCode
Source code of the Python Program to take in the marks of 5 subjects and display the grade.

sub1=int(input("Enter marks of the first subject: "))


sub2=int(input("Enter marks of the second subject: "))
sub3=int(input("Enter marks of the third subject: "))
sub4=int(input("Enter marks of the fourth subject: "))
sub5=int(input("Enter marks of the fifth subject: "))
avg=(sub1+sub2+sub3+sub4+sub4)/5
if(avg>=90):
print("Grade:A")
elif(avg>=80&avg<90):
print("Grade:B")
elif(avg>=70&avg<80):
print("Grade:C")
elif(avg>=60&avg<70):
print("Grade:D")
else:
print("Grade:F")

Program Explanation

1. User must enter 5 different values and store it in separate variables.


2. Then sum up all the five marks and divideby5 to find the average of the marks.
3. If the average is greater than 90,“Grade:A” is printed.
4. If the average is in between 80and 90, “Grade: B” is printed.
5. If the average is in between 70 and 80, “Grade: C” is printed.
6. If the average is in between 60 and 70, “Grade: D” is printed.
7. If the average is any thing below 60, “Grade: F” is printed.

Sample Output

Case1:
Enter marks of the first subject: 85
Enter marks of the second subject: 95
Enter marks of the third subject: 99
Enter marks of the fourth subject: 93
Enter marks of the fifth subject: 100

Grade: A

Case2:
Enter marks of the first subject: 81
Enter marks of the second subject: 72
Enter marks of the third subject: 94
Enter marks of the fourth subject: 85
Enter marks of the fifth subject: 80

Grade: B

5. Python Program to Find All Odd Palindrome Numbers in Range with out using Recursion

This is a Python Program to find all numbers which are odd and palindromes between arrange of
numbers without using recursion.

4
MJCET IT WORKSHOP

Problem Description

The program takes arrange and prints all numbers which are odd and palindromes between the range
without using recursion.

Problem Solution
1. Take a upper limit and lower limit from the user.
2. Using list comprehension, store all the numbers in the list that are odd and palindromes.
3. Print the list.
4. Exit.

Program/ Source Code

a=[]
l=int(input("Enter lower limit: "))
u=int(input("Enterupperlimit:"))
a=[x for x in range(l,u+1)if x%2!=0 and str(x)==str(x)[::-1]]
print("Thenumbersare:",a)

Program Explanation

1. User must enter a upper and lower limit.


2. Using list comprehension, the numbers which are odd (determined using the modulus
operator) and that are palindromes (determined using string slicing)are stored into a list.
3. The list is printed.

Sample Output:

Case1:
Enter lower limit: 100
Enter upper limit: 150
The numbers are: [101,111,121,131,141]

Case2:
Enter lower limit: 300
Enter upper limit: 400
The numbers are: [303,313,323,333,343,353,363,373,383,393]

6. Python Program to Count the Number of Words in a Text File

Problem Description
The program takes the filename from the user and counts number of words in that file.

Problem Solution
1. Take the filename from the user.
2. Read each line from the file and split the line to forma list of words.
3. Find the length of items in the list and print it.
4. Exit.

Program/Source Code

fname= input("Enterfilename:")
num_words=0
with open(fname,'r')as f:
for line in f:
words= line.split()
num_words+=len(words)
print("Numberofwords:")
print(num_words)

5
MJCET IT WORKSHOP

Program Explanation

1. User must enter a file name.


2. The file is opened using the open() function in the read mode.
3. A for loop isused to read through each line in the file.
4. Each line is split into a list of words using split().
5. The number of words in each line is counted using len() and the count variableis incremented.
6. The number of words in the file is printed.

Sample Output

Case1:
Contents of file:
Hello world

Output:
Enter file name: data1.txt
Number of words: 2

Case2:
Contents of file:
This programming language is Python

Output:
Enter file name: data2.txt
Number of words: 5

7. Python Program to Read a Number n and Print the Series“1+2+…..+n=“

Problem Description

The program takes a number n and prints and computes the series“1+2+…+n=”.

Problem Solution

1. Take a value from the user and store it in a variable n.


2. Use a for loop where the value of i ranges between the values of 1and n.
3. Print the value of i and ‘+’operator while appending the value of i to a list.
4. Then find the sum of elements in the list.
5. Print‘=’followed by the total sum.
6. Exit.

Program/Source Code

n=int(input("Enter a number: "))


a=[]
for i in range(1,n+1):
print(i,sep="",end=" ")
if(i<n):
print("+",sep="",end=" ")
a.append(i)
print("=",sum(a))
print()

Program Explanation

1. User must first enter the value and store it in a variable n.


2. The for loop enables it o range between 1 and n(asn+1 is not included).
3. For each iteration, the value of i is printed.
4. ‘+’operator is printed only if i<n

6
MJCET IT WORKSHOP

Sample Output

Case1:
Enter a number: 4
1 +2 +3+4=10

Case2:
Enter a number: 5
1+2+3+4+5=15

8. Python Program to Find the Second Largest Number in a List using Bubble Sort

Problem Description

The program takes a list and finds the second largest number in the list using bubblesort.

Problem Solution

1. Take in the number of elements for the list and store it in a variable.
2. Take in the elements of the list one by one.
3. Then sort the list using bubble sort.
4. Print these cond last element of the sorted list which is these cond-largest number.
5. Exit.

Program/Source Code

a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
for i in range(0,len(a)):
for j in range(0,len(a)-i-1):
if(a[j]>a[j+1]):
temp=a[j]
a[j]=a[j+1]
a[j+1]=temp
print('Second largest number is:',a[n-2])

Program Explanation

1. User must enter the number of elements for the list and store it in a variable.
2. User must then enter the elements of the list one by one using a for loop and store it in a list.
3. Then bubble sort algorithm may be used to sort the elements of the list.
4. These second last element of the sorted list is then printed which is basically these second
largest element in the list.

Sample Output

Case1:
Enter number of elements: 4
Enter element: 56
Enter element: 43
Enter element: 78
Enter element: 12
Second largest number is: 56

Case2:
Enter number of elements: 6
Enter element: 23
Enter element: 45
Enter element: 94
Enter element: 10
Enter element: 34
7
MJCET IT WORKSHOP

Enter element: 95
Second largest number is: 94

9. Python Program to Find Sum of Series 1+1/2+1/3+1/4+…….+1/N

Problem Description

The program takes in the number of terms and finds the sum of series: 1+ 1/2+1/3+ …..+ 1/N.

Problem Solution

1. Take in the number of terms t of ind the sum of the series for.
2. Initialize the sum variable to 0.
3. Use a for loop ranging from1 to the number and find the sum of the series.
4. Print the sum of these ries after rounding it of f to t wodecimal places.
5. Exit.

Program/Source Code

n=int(input("Enter the number of terms: "))


sum1=0
for i in range(1,n+1):
sum1=sum1+(1/i)
print("The sum of series is",round(sum1,2))

Program Explanation

1. User must enter the number of terms t of in d the sum of.


2. The sum variable is initialized to 0.
3. The for loop isused to find the sum of the series and the number is incremented for each iteration.
4. The numbers are added to the sum variable and this continues till the value of I reaches the number
of terms.
5. Then the sum of the series is printed.

Sample Output

Case1:
Enter the number of terms: 7
The sum of series is
2.59

Case2:
Enter the number of terms: 15
The sum of series is 3.32

10. Python Program to Print Largest Even and Largest Odd Number in a List

Problem Description

The program takes in a list and prints the largest even and largest off number in it.

Problem Solution

1. Take in the number of elements to be in the list from the user.


2. Take in the elements from the user using a for loop and append to a list.
3. Using a for loop, get the elements one by one from the list and check if it odd or even and append
them to different lists.
4. Sort both the lists individually and get the length of each list.
5. Print the last elements of the sorted lists.
6. Exit.

8
MJCET IT WORKSHOP

Program/Source Code

n=int(input("Enter the number of elements to be in the list:"))


b=[]
for i in range(0,n):
a=int(input("Element: "))
b.append(a)

c=[]
d=[]
for i in b:
if(i%2==0):
c.append(i)
else:
d.append(i)
c.sort()
d.sort()
count1=0
count2=0
for k in c:
count1=count1+1
for j in d:
count2=count2+1
print("Largest even number:",c[count1-1])
print("Largest odd number",d[count2-1])

Program Explanation

1. User must enter the number of elements to be in the list.


2. User must the n enter the elements of the list one by one which is appended to the list.
3. The for loop is used to traverse through the list and obtain the elements one by one.
4. The if statement checks whether the element is odd or even.
5. The odd elements are appended to another list and the even elements are appending to
another list.
6. Both the lists are then sorted.
7. The individual lengths of both the lists are obtained using for loops.
8. The last element of the sorted lists which is the largest odd and largest even number is
printed.

Sample Output

Case1:
Enter the number of elements to be in the list:5
Element:45
Element:20
Element:80
Element:93
Element: 3
Largest even number:80
Largest odd number 93

Case2:
Enter the number of elements to be in the list:4
Element:23
Element:10
Element:34
Element:89
Largest even number: 34
Largest odd number 89

9
MJCET IT WORKSHOP

11. Python Program to Print Numbers in a Range Without using Loops or using functions

Problem Description
The program takes in the upper limit and prints all numbers within the given range using recursive
function.

Problem Solution
1. Define a recursive function.
2. Define a base case for that function that the number should be greater than zero.
3. If number is greater than 0, call the function again with the argument as the number minus1.
4. Print the number.
5. Exit.

Program/Source Code

def printno(upper):
if(upper>0):
printno(upper-1)
print(upper)
upper=int(input("Enter upper limit: "))
printno(upper)

Program Explanation
1. User must enter the upper limit of the range.
2. This value is passed as an argument for the recursive function.
3. The base case for the recursive function is that number should always be greater than 0.
4. Ifnumberisgreaterthan0, function is called again with the argument as the number minus1.
5. The number is printed.
6. The recursion continues until the number becomes lesserthan0.

Sample Output

Case1:
Enter upper limit: 5
1
2
3
4
5

Case2:
Enter upper limit: 15
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

10
MJCET IT WORKSHOP

12. Python Program to Merge Two Lists and Sort it

Problem Description
The program takes two lists, merges the m and sorts the merged list.

Problem Solution
1. Take in the number of elements for the first list and store it in a variable.
2. Take in the elements of the list one by one.
3. Similarly, take in the elements for these second list also.
4. Merge both the lists using the ‘+’ operator and then sort the list.
5. Display the elements in the sorted list.
6. Exit.

Program/Source Code

a=[]
c=[]
n1=int(input("Enter number of elements:"))
for i in range(1,n1+1):
b=int(input("Enter element:"))
a.append(b)
n2=int(input("Enter number of elements:"))
for i in range(1,n2+1):
d=int(input("Enter element:"))
c.append(d)
new=a+c.sort()
print("Sorted listis:",new)

Program Explanation
1. User must enter the number of elements for the first list and store it in a variable.
2. User must the n enter the elements of the list one by one using a for loop and store it in a
list.
3. User must similarly enter the elements of the second list one by one.
4. The ‘+’ operator is then used to merge both the lists.
5. The sort function then sorts the list in ascending order.
6. The sorted list is then printed.

Sample Output

Case1:
Enter number of elements: 5
Enter element: 10
Enter element: 20
Enter element: 35
Enter element: 55
Enter element: 71
Enter number of elements: 2
Enter element: 5
11
MJCET IT WORKSHOP

Enter element: 37
Sorted list is: [5, 10, 20, 35, 37, 55, 71]

Case2:
Enter number of elements: 3
Enter element: 2
Enter element: 4
Enter element: 8
Enter number of elements: 3
Enter element: 2
Enter element: 4
Enter element: 0
Sorted list is:[0, 2, 2, 4, 4, 8]

13. Python Program to Split Even and Odd Elements into Two Lists

Problem Description

The program takes a list and puts the even and odd elements in it into two separate lists.

Problem Solution

1. Take in the number of elements and store it in a variable.


2. Take in the elements of the list one by one.
3. Use a for loop to traverse through the elements of the list and an if statement to
check if the element is even or odd.
4. If the element is even, append it to a separate list and if it is odd, append it to a different
one.
5. Display the elements in both the lists.
6. Exit.

Program/Source Code

a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
even=[]
odd=[]
for j in a:
if(j%2==0):
even.append(j)
else:
odd.append(j)
print("The even list",even)
print("The odd list",odd)

12
MJCET IT WORKSHOP

Program Explanation

1. User must enter the number of elements and store it in a variable.


2. User must then enter the elements of the list one by one using a for loop and store it in a
list.
3. Another for loop is used to traverse through the elements of the list.
4. The if statement checks if the element is even or odd and appends them to separate lists.
5. Both the lists are printed.

Sample Output

Case1:
Enter number of elements: 5
Enter element: 67
Enter element: 43
Enter element: 44
Enter element: 22
Enter element: 455
The even list [44, 22]
The odd list [67, 43,455]

Case2:
Enter number of elements: 3
Enter element: 23
Enter element: 44
Enter element: 99
The even list [44]
The odd list [23, 99]

14. Python Program to Count the Occurrences of Each Word in a Given String Sentence

Problem Description

The program takes a string and counts the occurrence of each word in the given sentence.

Problem Solution

1. Take a string and a word from the user and store it in separate variables.
2. Initialize a count variable to 0.
3. Split the string using space as the reference and store the words in a list.
4. Use a for loop to traverse through the words in the list and use an if statement to
check if the word in the list matches the word given by the user and increment the
count.
5. Print the total count of the variable.
6. Exit.

13
MJCET IT WORKSHOP

Program/Source Code

string=raw_input("Enter string:")
word=raw_input("Enter word:")

a=[]
count=0
a=string.split(" ")
for i in range(0,len(a)):
if(word==a[i]):
count=count+1
print("Count of the word is:")
print(count)

Program Explanation

1. User must enter a string and a word and store it in separate variables.
2. The count variable is initialized to zero.
3. The string is split in to words using space as the reference and stored in a list.
4. The for loop is used to traverse through the words in the list.
5. The count is incremented each time the word in the list is equal to the word given by the
user.
6. The total count of the word is printed.

Sample Output

Case1:
Enter string: hello world
Enter word: hello
Count of the word is:
1

Case2:
Enter string: orange blue red orange
Enter word: orange
Count of the word is:
2

15. Python Program to Map Two Lists into a Dictionary

Problem Description

The program takes two lists and maps two lists into a dictionary.

Problem Solution

1. Declare two empty lists and initialize them to an empty list.


14
MJCET IT WORKSHOP

2. Consider a for loop to accept values for the two lists.


3. Take the number of elements in the list and store it in a variable.
4. Accept the values into the list using another for loop and insert in to the list
5. Repeat 4 and 5 for the values list also.
6. Zip the two lists and use dict() to convert it into a dictionary.
7. Print the dictionary.
8. Exit.

Program/ Source Code

keys=[]
values=[]
n=int(input("Enter number of elements for dictionary:"))
print("For keys:")
for x in range(0,n):
element=int(input("Enter element" + str(x+1) + ":"))
keys.append(element)
print("For values:")
for x in range(0,n):
element=int(input("Enter element" + str(x+1) + ":"))
values.append(element)
d=dict(zip(keys,values))
print("The dictionary is:")
print(d)

Program Explanation

1. User must enter the number of elements in the list and store it in avariable.
2. User must enter the values to the same number of elements in to the list.
3. The append function obtain seach element from the user and adds the same to the end of
the list as many times as the number of elements taken.
4. The same of 2 and 3 is done for the second values list also.
5. The two lists are merged to gether using the zip() function.
6. The zipped lists are then merged to form a dictionary using dict().
7. The dictionary formed from the two lists is then printed.

Sample Output

Case1:
Enter number of elements for dictionary: 3
For keys:
Enter element1:1
Enter element2:2
Enter element3:3
For values:
Enter element1:1
Enter element2:4
Enter element3:9
15
MJCET IT WORKSHOP

The dictionary is:


{1:1, 2:4, 3:9}

Case2:
Enter number of elements for dictionary:5
For keys:
Enter element1:1
Enter element2:2
Enter element3:3
Enter element4:4
Enter element5:5
For values:
Enter element1:78
Enter element2:65
Enter element3:34
Enter element4:100
Enter element5:1000
The dictionary is:
{1: 78, 2: 65, 3: 34, 4: 100, 5: 1000}

16. Python Program to Remove a Key from a Dictionary

Problem Description

The program takes a dictionary and removes a given key from the dictionary.

Problem Solution

1. Declare and initialize a dictionary to have some key-value pairs.


2. Take a key from the user and store it in a variable.
3. Using a if statement and the in operator, check if the key is present in the dictionary.
4. If it is present, delete the key- value pair.
5. If it isn’t present, prints that the key isn’t found and exit the program.
6. Exit.

Program/Source Code

d= {'a':1,'b':2,'c':3,'d':4}
print("Initial dictionary")
print(d)
key=raw_input("Enter the key to delete(a-d):")
if key in d:
del d[key]
else:
print("Key not found!")
exit(0)
print("Updated dictionary")
print(d)
16
MJCET IT WORKSHOP

Program Explanation

1. User must enter the key to be checked and store it in a variable.


2. A if statement and the in operator issued check if the key is present in the dictionary.
3. If it is present, the key-value pair is deleted.
4. If it isn’t present,“ Key not found!” is printed and the program is exited.

Sample Output

Case1:
Initial dictionary
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
Enter the key to delete(a-d):a
Updated dictionary
{'c': 3, 'b': 2, 'd': 4}

Case2:
Initial dictionary
{'a':1,'c':3,'b':2,'d':4}
Enter the key to delete (a-d): g
Key not found!

17. Python Program that Displays Letters that are not Common in Two Strings

Problem Description

The program takes two strings and displays which letters are in the two strings but not in both.

Problem Solution

1. Enter two input strings and store it in separate variables.


2. Convert both of the strings into sets and find which of the letters are in the two strings but
not in both.
3. Store the letters in a list.
4. Use a for loop to print the letters of the list.
5. Exit.

Program/Source Code

s1=raw_input("Enter first string:")


s2=raw_input("Enter second string:")
a=list(set(s1)^set(s2))
print("The letters are:")
for i in a:
print(i)

17
MJCET IT WORKSHOP

Program Explanation

1. User must enter two input strings and store it in separate variables.
2. Both of the strings are converted into sets and the letters which are present in the two
strings but not in both are found using the ‘^’ operator.
3. These letters are stored in a list.
4. A for loop is used to print the letters of the list.

Runtime Test Cases

Enter first string: hai sir how r u?


Enter second string: hai madam how r u?
The letters are:
d
m
s

Case2:
Enter first string:hello
Enter second string:World
The letters are:
e
d
h
r
W

18. Python Program to Create a Class which Performs Basic Calculator Operations

Problem Description

The program takes the input from the user and performs operation using classes.

Problem Solution

1. Create a class and using a constructor to initialize values of that class.


2. Create methods for adding, subtracting, multiplying and dividing two numbers and returning
the respective results.
3. Take the two numbers as inputs and create an object for the class passing the two numbers
as parameters to the class.
4. Using the object, call the respective function depending on the choice taken from the user.
5. Print the final result.
6. Exit

Program/ Source Code

class cal():
def init(self,a,b):
18
MJCET IT WORKSHOP

self.a=a
self.b=b
def add(self,a,b):
return a+b
def mul(self,a,b):
return a*b
def div(self,a,b):
return a/b
def sub(self,a,b):
return a-b
a=int(input("Enter first number:"))
b=int(input("Enter second number: "))

obj=cal()
choice=1
while choice!=0:
print("0.Exit")
print("1.Add")
print("2. Subtraction")
print("3.Multiplication")
print("4.Division")
choice=int(input("Enter choice:"))
if choice==1:
print("Result:",obj.add(a,b))
elif choice==2:
print("Result:",obj.sub(a,b))
elif choice==3:
print("Result:",obj.mul(a,b))
elif choice==4:
print("Result:",round(obj.div(a,b),2))
elif choice==0:
print("Exiting!")
else:
print("Invalid choice!!")
print()

Program Explanation

1. A class called cal is created and the init() method is used to initialize values of that class.
2. Methods for adding, substracting, multiplying, dividing two numbers and returning the
irrespective results are defined.
3. The menu is printed and the choice is taken from the user.
4. An object for the class is created with the two numbers taken from the user passed
as parameters.
5. Using the object, the respective method is called according to the choice taken from the user.
6. Whenthechoiceis0,the loop is exited.
7. The final result is printed.

19
MJCET IT WORKSHOP

Runtime Test Cases

Enter first number:1


Enter second number: 3
0.Exit
1.Add
2. Subtraction
3.Multiplication
4.Division

Enter choice:1
('Result:', 4)
0.Exit
1.Add
2. Subtraction
3.Multiplication
4.Division

Enter choice:2
('Result:', -2)
0.Exit
1.Add
2. Subtraction
3.Multiplication
4.Division

Enter choice:3
('Result:', 3)
0.Exit
1.Add
2. Subtraction
3.Multiplication
4.Division

Enter choice:4
('Result:', 0.0)
0.Exit
1.Add
2. Subtraction
3.Multiplication
4.Division

Enter choice:5
Invalid choice!!
0.Exit
1.Add
2. Subtraction
3.Multiplication
20
MJCET IT WORKSHOP

4.Division

Enter choice:0
Exiting!

19. Python Program to Append, Delete and Display Elements of a List using Classes

Problem Description

The program appends, deletes and displays elements of a list using classes.

Problem Solution

1. Create a class and using a constructor initialize values of that class.


2. Create methods for adding, removing and displaying elements of the list and return
the respective values.
3. Create an object for the class.
4. Using the object, call the respective function depending on the choice taken from the user.
5. Print the final list.
6. Exit

Program/ Source Code

class check():
def init(self):
self.n=[]
def add(self,a):
return self.n.append(a)
def remove(self,b):
self.n.remove(b)
def dis(self):
return(self.n)
obj=check()
choice=1
while choice!=0:
print("0.Exit")
print("1. Add")
print("2. Delete")
print("3.Display")
choice=int(input("Enter choice:"))
if choice==1:
n=int(input("Enter number to append: "))
obj.add(n)
print("List:",obj.dis())
elif choice==2:
n=int(input("Enter number to remove:"))
obj.remove(n)
print("List:",obj.dis())
21
MJCET IT WORKSHOP

elif choice==3:
print("List:",obj.dis())

elif choice==0:
print("Exiting!")
else:
print("Invalid choice!!")

Program Explanation

1. A class called check is created and the init() method isused to initialize values of that
class.
2. Methods for adding, removing and displaying elements of the list have been defined.
3. The menu is printed and the choice is taken from the user.
4. An object for the class is created.
5. Using the object, the respective method is called according to the choice taken from the user.
6. The final list is printed.

Runtime Test Cases

Case 1:
0. Exit
1. Add
2. Delete
3. Display

Enter choice: 1
Enter number to append: 23
List: [23]
0. Exit
1. Add
2. Delete
3. Display

Enter choice: 1
Enter number to append: 45
List: [23, 45]
0. Exit
1. Add
2. Delete
3. Display

Enter choice: 1
Enter number to append: 56
List: [23, 45, 56]
0. Exit
1. Add
2. Delete
22
MJCET IT WORKSHOP

3. Display

Enter choice: 2
Enter number to remove: 45
List: [23, 56]
0. Exit
1. Add
2. Delete
3. Display
Enter choice: 0
Exiting!

Case 2:
0. Exit
1. Add
2. Delete
3. Display

Enter choice: 1
Enter number to append: 10
List: [10]
0. Exit
1. Add
2. Delete
3. Display

Enter choice: 1
Enter number to append: 7
List: [10,7]
0. Exit
1. Add
2. Delete
3. Display
Enter choice: 0
Exiting!

23
MJCET IT WORKSHOP

INTRODUCTION TO MATLAB
What Is MATLAB

MATLAB is a high-performance language for technical computing. It integrates computation,


visualization, and programming in an easy-to-use environment where problems and solutions are
expressed in familiar mathematical notation. Typical uses include:
 Math and computation
 Algorithm development
 Modeling, simulation, and prototyping
 Data analysis, exploration, and visualization
 Scientific and engineering graphics
 Application development, including Graphical User Interface building

MATLAB is an interactive system whose basic data element is an array that does not require
dimensioning. This allows you to solve many technical computing problems, especially those
with matrix and vector formulations, in a fraction of the time it would take to write a program in
a scalar non interactive language such as C or Fortran.

The name MATLAB stands for matrix laboratory. MATLAB was originally written to provide
easy access to matrix software developed by the LINPACK and EISPACK projects, which
together represent the state-of-the-art in software for matrix computation.
MATLAB has evolved over a period of years with input from many users. In university
environments, it is the standard instructional tool for introductory and advanced courses in
mathematics, engineering, and science. In industry, MATLAB is the tool of choice for high-
productivity research, development, and analysis.

MATLAB features a family of application-specific solutions called toolboxes. Very important to


most users of MATLAB, toolboxes allow you to learn and apply specialized technology.
Toolboxes are comprehensive collections of MATLAB functions (M-files) that extend the
MATLAB environment to solve particular classes of problems. Areas in which toolboxes are
available include signal processing, control systems, neural networks, fuzzy logic, wavelets,
simulation, and many others.

The MATLAB System


The MATLAB system consists of five main parts:

The MATLAB language.


This is a high-level matrix/array language with control flow statements, functions, data
structures, input/output, and object-oriented programming features. It allows both "programming
in the small" to rapidly create quick and dirty throw-away programs, and "programming in the
large" to create complete large and complex application programs.

The MATLAB working environment.


This is the set of tools and facilities that you work with as the MATLAB user or programmer. It
includes facilities for managing the variables in your workspace and importing and exporting
data. It also includes tools for developing, managing, debugging, and profiling M-files,
MATLAB's applications.

Handle Graphics.
This is the MATLAB graphics system. It includes high-level commands for two-dimensional

24
MJCET IT WORKSHOP

and three-dimensional data visualization, image processing, animation, and presentation


graphics. It also includes low-level commands that allow you to fully customize the appearance
of graphics as well as to build complete Graphical User Interfaces on your MATLAB
applications.

The MATLAB mathematical function library.


This is a vast collection of computational algorithms ranging from elementary functions like
sum, sine, cosine, and complex arithmetic, to more sophisticated functions like matrix inverse,
matrix eigenvalues, Bessel functions, and fast Fourier transforms.

The MATLAB Application Program Interface (API).


This is a library that allows you to write C and Fortran programs that interact with MATLAB. It
include facilities for calling routines from MATLAB (dynamic linking), calling MATLAB as a
computational engine, and for reading and writing MAT-files.

Obtaining Help on MATLAB commands

To obtain help on any of the MATLAB commands, you simply need to type
help <command>
at the command prompt. For example, to obtain help on the gamma function, we type at the
command prompt:
help gamma
Try this now. You may also get help about commands using the "Help Desk", which can be
accessed by selecting the MATLAB Help option under the Help menu.
Note that the description MATLAB returns about the command you requested help on contains
the command name in ALL CAPS. This does not mean that you use this command by typing it
in ALL CAPS. In MATLAB, you almost always use all lower case letters when using a
command.

Variables in MATLAB

We can easily define our own variables in MATLAB. Let's say we need to use the value of
3.5sin(2.9) repeatedly. Instead of typing 3.5*sin(2.9)over and over again, we can denote this
variable as x by typing the following:
x=3.5*sin(2.9)
(Please try this in MATLAB.) Now type
x+1
and observe what happens. Note that we did not need to declare x as a variable that is supposed
to hold a floating point number as we would need to do in most programming languages.
Often, we may not want to have the result of a calculation printed-out to the command window.
To supress this output, we put a semi-colon at the end of the command; MATLAB still performs
the command in "the background". If you defined x as above, now type
y=2*x;
y
and observe what happened.

In many cases we want to know what variables we have declared. We can do this by
typing whos. Alternatively, we can view the values by openning the "Workspace" window. This
is done by selecting the Workspace option from the View menu. If you want to erase all

25
MJCET IT WORKSHOP

variables from the MATLAB memory, type clear. To erase a specific variable, say x, type clear
x. To clear two specific variables, say x and y, type clear x y, that is separate the different
variables with a space. Variables can also be cleared by selecting them in the Workspace
window and selecting the delete option

Example 1: Plot sin(x2) on the interval [-5,5]. To do this, type the following:
x=-5:0.01:5;
y=sin(x.^2);
plot(x,y)
and observe what happens.

Example 2: Plot exp(sin(x)) on the interval [-p,p]. To do this, type the following:
x=linspace(-pi,pi,101);
y=exp(sin(x));
plot(x,y)
and observe what happens. The command line space creates a vector of 101 equally spaced
values between -p and p (inclusive).
Ocassionally, we need to plot values that vary quite differently in magnitude. In this case, the
regular plot command fails to give us an adequate graphical picture of our data. Instead, we need
a command that plots values on a log scale. MATLAB has 3 such commands: loglog, semilogx,
and semilogy. Use the help command to see a description of each function. As an example of
where we may want to use one of these plotting routines, consider the following problem:

Example 3: Plot x5/2 for x = 10-5 to 105. To do this, type the following:
x=logspace(-5,5,101);
y=x.^(5/2);
plot(x,y)
and observe what happens. Now type the following command:
loglog(x,y)
The command logspace is similar to linspace, however it creates a vector of 101 points
lograthmically equally distributed between 10-5 and 105.

26
MJCET IT WORKSHOP

22. Programs on Basic Mathematical and formatting programs in MatLab


a. Matlab program for addition of 2 numbers using MatLab command prompt
b. Evaluation of an mathematical equation using math operations
c. Finding out the square, cube and square root of a number

22. a. Matlab program for addition of 2 numbers

a = 3;
b = 5;
c = a+b

Output: 8

22. b. Basic math operations

a = 3;
b = 9;
c = 2*a+b^2-a*b+b/a-10

Output: 53

22. c. Formatted output


a = 3;
b = a*a;
c = a*a*a;
d = sqrt(a);
fprintf('%4u square equals %4u \r', a, b)
fprintf('%4u cube equals %4u \r', a, c)
fprintf('The square root of %2u is %6.4f \r', a, d)

Output
3 square equals 9
3 cube equals 27
The square root of 3 is 1.7321

23. Programs on Simple Math functions and conditional statements


a. Program on math functions sin() and exp() and constant pi
b. Program on for loop to print the repeated number
c. Check whether the given number is >5 or not.
d. Check whether the given number is in specified range.

23. a. Intrinsic math functions and constants

x = pi;
y = sin(pi/2)
z = exp(-sin(pi/2))

27
MJCET IT WORKSHOP

Output
y=1
z = 0.3679

23. b. BASIC LOOPING TECHNIQUES

b = 3;
for k = 1:5
b
end

Output: 3 3 3 3 3

23. c. if command

num1 = 7;
if (num1 > 5)
fprintf('%4u is greater than 5 \r', num1)
else
fprintf('%4u is less than or equal to 5 \r', num1)
end

Output: 7 is greater than 5

23. d. Nested elseif

num1 = 4;
if (num1 >= 5)
fprintf('%4i is greater than or equal to 5 \r', num1)
elseif (num1 > 1)
fprintf('%4i is less than 5 but greater than 1 \r', num1)
elseif (num1 == 1)
fprintf('%4i equals 1 \r', num1)
elseif (num1 > -3)
fprintf('%4i is less than 1 but greater than -3 \r', num1)
else
fprintf('%4i is less than or equal to -3 \r', num1)
end

24. Arrays and vectors in MatLab


a. Addition and multiplication of 1D array and 2D array respectively , element-by-
element multiplication.
b. Defining vectors and performing an elementary function sin () on this vectorial
variable.
c. Solving the given linear equation

24. a. Assign the content of a (one-dimensional) array; Addition of two arrays

a = [2 12 25];

28
MJCET IT WORKSHOP

b = [3 7 4];
c = a+b

Output

c = 5 19 29

24. a. Multiplication of two matrices

a = [2 3; 1 4];
b = [5 1; 7 2];
c = a.*b

Output
c = 10 3
5 8

24. a. Element-by-element multiplication involving two 1-D arrays or two matrices of the
same dimension

a = [2 3 5];
b = [2 4 9];
c = a.*b

Output

c = 4 12 45

24. b. Elementary functions with a vectorial variable

a = [2 3 5];
b = sin(a)

Output

b = 0.9092 0.1411 -0.9589

24. c. Solving a system of linear equation

A = [4 1 2; 0 3 1; 0 1 2];
b = [17 ; 19 ; 13];
x = inv(A)*b

Output
x=154

29
MJCET IT WORKSHOP

25. Programs on Nested if and equations


a. Write a program to find area of circle of radius3
b. Print the biggest number among the 3 given numbers using nested if
c. Program to find the distance between 2 points

25. a. write a program to find area of circle of radius 3

r=input(‘enter Radius’);
a=pi*r*r;
fprintf(‘area of circle is %f” , a);

Sample output
12
Area of circle is 452.19

25. b. write a MATLAB program to demonstrate if and if else if

a=input(‘enter 1st number’);


b=input(‘enter 2nd number’);
c=input(‘enter 3rd number’);
if a>b && a>c
disp(a)
elseif b>a && b>c
disp(b)
else
disp(c)
end

Sample output:

enter 1st number 4


enter 2nd number 5
enter 3rd number 6

25. c. write a program to find distance between two points

a=input(‘enter x1 value’);
b=input(‘enter x2 value’);
c=input(‘enter y1 value’);
d=input(‘enter y2 value’);
e= sqrt(((x2-x1)^2+((y2-y1)^2))
Sample output:
enter x1 value 2
enter x2 value 3
enter y1 value 4
enter y2 value 5
e = 1.414

30
MJCET IT WORKSHOP

26. Write a program to demonstrate line spacing on graph plane

26. write a program to plot simple graph in matlab

x = linspace(0,10,100);
y = exp(x/10).*sin(4*x);
plot(x,y,'-o')

plot(x,y,'o')

Sample output:

x = linspace(0,10,50);
y = sin(x);
plot(x,y,'-s','MarkerSize',10,...
'MarkerEdgeColor','red',...
'MarkerFaceColor',[1 .6 .6])

Sample output

31
MJCET IT WORKSHOP

26. write a program to demonstrate line spacing on graph plane


x = linspace(0,10,25);
y = x.^2;
p = plot(x,y,'-s');
p.MarkerSize = 10;
p.MarkerIndices = 1:5:length(y);
Sample output

27. Programs on Graphs


a. Write a program to demonstrate two graph with diff input sin and cos
b. Write a program to demonstrate 2D graph

27. a. write a program to demonstrate two graph with diff input sin and cos

x = linspace(-2*pi,2*pi);
y1 = sin(x);
y2 = cos(x);
plot(x,y1,x,y2)

Sample output:

32
MJCET IT WORKSHOP

27. b. Write a program to demonstrate 2D graph

x = linspace(0,10,150);
y = cos(5*x);
plot(x,y,'Color',[0,0.7,0.9])
title('2-D Line Plot')
xlabel('x')
ylabel('cos(5x)')

Sample output

33

You might also like