Merge Lab Till 11 PF
Merge Lab Till 11 PF
LAB # 01
INTRODUCTION
OBJECTIVE
To become familiar with the Python Programming by using an Integrated Development
Environment
THEORY
Programming
The act of writing computer programs is called computer programming. A computer program is a
sequence of instructions written using a computer programming language to perform specified tasks
by the computer. There are a large number of programming languages that can be used to write
computer programs, for example: Python, C, C++, Java, PHP, Perl, Ruby etc.
Using an IDE will save a lot of time and effort in writing a program. However, one should be careful
of some of the pitfalls of using an IDE as it may not be ideal for everyone and might not be suitable
in every situation. Some IDEs are very complicated to use and may consume a lot of resources.
Many IDEs support Python Programming Language. Some of the popular IDEs are listed below.
Standalone IDEs:
• Microsoft Visual Studio Code
https://code.visualstudio.com/
• Eclipse
https://www.eclipse.org/downloads
• NetBeans
https://netbeans.org/downloads/
• Thonny
https://thonny.org/
• Anaconda
https://www.anaconda.com/distribution/
Online IDEs:
• Ideone
https://ideone.com/
• Online GDB
https://www.onlinegdb.com/online_python_debugger
Step#1: Go to https://thonny.org
Step#2: Download the version for Windows and wait a few seconds while it downloads.
Step#4: Follow the installation wizard to complete the installation process and just click "Next".
Step#5: After completing the installation, open Thonny IDE. A window as shown in the following
figure should open.
print("Hello, World! \n Python is fun") instructs the computer to print on the screen the string of
characters enclosed by the quotation marks.
\n is an escape sequence that means newline. It causes the cursor to position to the beginning of the
next line on the screen.
pound sign (#) is a comment on a line, called a line comment, or enclosed between three consecutive
single quotation marks (''') on one or several lines, called a paragraph comment.
Python programs are case sensitive. It would be wrong, for example, to replace print in the program
with Print. Several special characters can be seen (#, ", ()) in the program. They are used in almost
every program. Table 1.1 summarizes their uses.
Step#1: Go to File > New. Then save the file with .py extension.
Step#3: Then Go to Run > Run current script or simply click F5 to run it
EXERCISE
A. Create a file named lab1.py. Write the following code in the file. Execute it and show the
output. (You can use the Snipping Tool to take a snapshot of your output window).
1. Code:
# My first program
print("\nWelcome in the world of programming!")
Output:
2. Code:
#My second program
print("Welcome in the\n ")
print("world of programming! ")
Output:
B. Write a program in Python language that prints your bio-data on the screen. Show your
program and its output
LAB # 02
OBJECTIVE
Implement different type of data types, variables and operators used in Python.
THEORY
Variable
Variables are nothing but reserved memory locations to store values. This means that when you create
a variable you reserve some space in memory.
Example
x= 5
y= "John"
print(x)
print (y)
Output:
>>> %Run task1.py
5
John
Variables do not need to be declared with any particular type and can even change type after they have been
set.
Example:
x= 4
x= "Sally"
print(x)
Output:
>>> %Run task2.py
Sally
Example:
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
Output:
>>> %Run task3.py
Orange
Banana
Cherry
Example:
x= "awesome"
print("Python is " , x)
Output:
>>> %Run task4.py
Python is awesome
Python Keywords
Keywords are the words whose meaning have already been explained to the Python compiler. The
keywords cannot be used as variable names,function name or any identifier because if we do so we
are trying to assign a new meaning to the keyword, which is not allowed by the computer. Keywords
are also called ‘Reserved words’. Some keywords are as follows:
Data Types
Department of Computer Science & Information Technology
Sir Syed University of Engineering & Technology 2|Page
Programming Fundamentals (CS-116L) LAB # 02
Data types specify how we enter data into our programs and what type of data we enter. Python Data
Types are used to define the type of a variable.
Python has five standard data types −
• Numbers (int, float)
• String
• List
• Tuple
• Dictionary
You can get the data type of any object by using the “type( )” function.
Operators
Operators are special symbols in Python that carry out arithmetic or logical computation.
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators
EXERCISE
A. Point out the errors, if any,and also paste the output in the following Python statements.
1. x=5:
print(x)
2. 1TEXT
=
"SSUET"
NUMBER = 1
print(NUMBER+ TEXT)
3. a = b
= 3 =
4
B.
Evaluate the operation in each of the following statements, and show the resultant value after
each statement is executed.
1. a = 2 % 2 + 2 * 2 - 2 / 2;
2. b = 3
/ 2 +
5 * 4
/ 3 ;
3. c = b
= a =
3 + 4
;
C. Write
the
following
Python programs:
2. Write a program that performs the following four operations and prints their result on the screen.
a. 50 + 4
b. 50 – 4
c. 50 * 4
d. 50 / 4
3. Write a Python program to convert height (in feet and inches) to centimeters. Convert height of
5 feet 2 inches to centimeters.
4. Write a program to compute distance between two points by creating variables (Pythagorean
Theorem)
Distance =((x2−x1)^2+(y2−y1)^2)^1/2
LAB # 03
OBJECTIVE
Taking input from user and controlling output position.
THEORY
Syntax : input(prompt)
The message can be a string, or any other object, the object will be converted into a string before
written to the screen.
Example:
name=input('Please enter your name: "') print("Hello, " , name ,
"!")
Output:
>>> %Run task1.py Please enter your name:ABC
Hello, ABC!
>>>
Whatever you enter as input, input function convert it into a string. if you enter an integer value still
input() function convert it into a string. You need to explicitly convert it into an integer in your code
using typecasting.
Example:
# Program to check input
num = input ("Enter number :")
print(num)
name1 = input("Enter name : ")
print(name1)
We can also type cast this input to integer, float or string by specifying the input() function inside the
type.
Typecasting the input to Integer/Float: There might be conditions when you might require integer
input from user/console, the following code takes two input(integer/float) from console and typecasts
them to integer then prints the sum.
Example
# input num1 =
int(input()) num2
= int(input())
Escape Sequence
In Python strings, the backslash "\" is a special character, also called the "escape" character. An
escape sequence is a sequence of characters that does not represent itself when used inside a character
or string literal, but is translated into another character or a sequence of characters that may be
difficult or impossible to represent directly.
Escape Description
Example Output
Sequence
\\ Prints Backslash print ("\\") \
\` Prints single-quote print ("\'") '
\" Pirnts double quote print ("\"") "
print hello
\n ASCII linefeed ( LF )
("hello\nworld") world
ASCII backspace ( BS ) removes print ("az" + "\b"
\b ac
previous character + "c")
Department of Computer Science & Information Technology
Sir Syed University of Engineering & Technology 2|Page
Programming Fundamentals (CS-116L) LAB # 03
EXERCISE
A. Point out the errors or undefined/missing syntax, if any, in the following python programs.
1. print("Hello \b World!")
3. age = 23
message = "Happy " + age + "rd Birthday!" print(message)
1. a=5
print("a =", a, sep='0', end=',')
3. n1=int(input('"enter n1 value'))
n2=int(input('enter n2 value'))
1. Write a program to print a student’s bio data having his/her Date of birth, Roll no, Section,
Percentage and grade of matriculation and Intermediate. All the fields should be entered from the
console at run time.
2. Write a program that asks the user what kind of food they would like. Print a message about that
food, such as “Let me see if I can find you a Chowmein”. Food name must be in uppercase.
(hint: use upper( ) for food name)
3. Take the marks of 5 courses from the user and calculate the average and percentage, display the
result:
Eachcourse=50 marks
Total_marks= course1+course2+course3+course4+course5
average=Total_marks/5
percentage=(Total_marks x 100)/250
LAB # 04
DECISIONS
OBJECTIVE
To get familiar with the concept of conditional statement for simple decision making.
THEORY
Decision making statements in programming languages decides the direction of flow of program
execution.
The if…elif…else statement is used in Python for decision making.
The if Statement
Like most languages, python uses the keyword if to implement the decision control instruction. It is
used to decide whether a certain statement or block of statements will be executed or not i.e if a
certain condition is true then a block of statement is executed otherwise not. The general form of if
statement looks like this:
Syntax:
if condition:
# Statements to execute if
# condition is true
As a general rule, we express a condition using python’s ‘relational’ operators. The relational
operators allow us to compare two values to see whether they are equal to each other, unequal, or
whether one is greater than the other. Here is how they look and how they are evaluated in python.
Example:
# python program to illustrate If statement
i = 10
if (i > 15):
print (i, "is greater than 15")
print ("I am not greater")
Output:
>>> %Run task1.py
I am not greater
>>>
Syntax
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
Example:
# python program to illustrate If else statement
i = 20;
if (i < 15):
print (i,“is smaller than 15")
print ("i'm in if Block")
else:
print (i,"is greater than 15")
print ("i'm in else Block")
print ("i'm not in if and not in else Block")
Output:
>>> %Run task2.py
20 is greater than 15
i'm in else Block
i'm not in if and not in else Block
>>>
Example:
# Python program to illustrate if-elif-else
i = 30
if (i == 10):
print ("i is 10")
elif (i == 20):
print ("i is 20")
elif (i == 30):
print ("i is 30")
else:
print ("i is not present")
Output:
>>> %Run task3.py
i is 30
>>>
EXERCISE
C. Point out the errors, if any, and paste the output also in the following Python programs.
1. Code
a = 500,b,c;
if ( a >= 400 ):
b = 300
c = 200
print( "Value is:", b, c )
2. Code
&number = eval(input("Enter an integer: "))
print(type(number))
if number % 5 == 0
print("HiFive")
else
print("No answer")
3. Code
if score >= 60.0
grade = 'D'
elif score >= 70.0
grade = 'C'
elif score >= 80.0
grade = 'B'
elif score >= 90.0
grade = 'A'
else:
grade = 'F'
Output
2. Code
num = 3
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")
Output
3. Code
age = 15
if age < 4:
price = 0
elif age < 18:
price = 1500
else:
price = 2000
print("Your admission cost is Rs" + str(price) + ".")
Output
1. Any integer is input through the keyboard. Write a program to find out whether it is an odd number
or even number.
2. Write a program that asks for years of service and qualification from the user and calculates the
salary as per the following table:
Years of Service Qualifications Salary
>= 10 Masters 150,000
>= 10 Bachelors 100,000
< 10 Masters 100,000
< 10 Bachelors 70,000
3. Write an if-elif-else chain that determines a person’s stage of life, take input value for the variable
age, and then apply these conditions:
• If the person is less than 2 years old, print a message that the person is a baby.
• If the person is at least 2 years old but less than 4, print a message that the person is a toddler.
• If the person is at least 4 years old but less than 13, print a message that the person is a kid.
• If the person is at least 13 years old but less than 20, print a message that the person is a teenager.
• If the person is at least 20 years old but less than 65, print a message that the person is an adult.
• If the person is age 65 or older, print a message that the person is an elder.
LAB # 05
Control Statements
OBJECTIVE:
To get familiar with the concept of control statement for simple controlling and repetition of program
statements.
Theory:
In general, statements are executed sequentially: The first statement in a function is executed
first, followed by the second, and so on. There may be a situation when you need to execute
a block of code several number of times.
Programming languages provide various control structures that allow for more complicated
execution paths.
A loop statement allows us to execute a statement or group of statements multiple times.
The following diagram illustrates a loop statement:
Python programming language provides following types of loops to handle looping
requirements.
Example-1: Example-2:
i=1 i=1
while i < 4: while i < 4:
print i print i
i+=1 i+=1
print “END” print “END”
Output-1: Output-2:
1 END 1
2 END 2
3 END 3
END
Example: Write a program to display factorial of a given number. Program:
n=input("Enter the number: ")
f=1
while n>0:
f=f*n
n=n-1
print "Factorial is", f
Output:
Enter the number: 5 Factorial is 120
The first element of the sequence is assigned to the variable written after „for‟ and then the
statements are executed. Next, the second element of the sequence is assigned to the variable and
then the statements are executed second time. In this way, for each element of the sequence, the
statements are executed once. So, the for loop is executed as many times as there are number of
elements in the sequence.
1 END 1
2 END 2
3 END 3
END
Output-1: Output-2:
Example-3: Example-4: 10 9 8 7 6 5 4 3 2 1
Name= "python"
for x in range(10,0,-1):
for letter in Name:
print x,
print letter
Output-3: Output-4:
py t h o n
Program:
Output:
Enter the number: 5 F
factorial is 12
TASK:
Perform the following tasks using Python source code using loops
• To generate a random number from 3 to 13.
• To print the odd number from 10 to 100 and even numbers from 200 to 96.
• To take an integer value from a user and print the factorial of that number.
• To take two integer values from the user and print the table. The first indicates the table number
and the second value represents the limit of the table.
• To take two integer values from the user and print out the highest and lowest value.
• To calculate the factorial of 3 numbers which will be provided by the user
LAB # 06
NESTED STATEMENTS,
BREAK AND CONTINUE STATEMENTS
OBJECTIVE
Working on nested statements and control loop iteration using break and continue.
THEORY
Nested Statements:
A Nested statement is a statement that is the target of another statement. Nested if:
A Nested if is an if statement that is the target of another if statement. Nested if statements
means an if statement inside another if statement.
Syntax:
if (condition1):
# Executes when condition1 is true if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
Example:
#using nested if x=int(input("enter
number=")) y=int(input("enter 2nd
number=")) if x > 2:
if y > 2:
z = x + y
print("z is", z)
else:
print("x is", x)
Output:
>>> %Run task1.py
enter number=3
enter 2nd number=8
z is 11
>>>
Nested loops:
Nested loops consist of an outer loop and one or more inner loops. Each time the outer loop
repeats, the inner loops are reinitialized and start again.
Department of Computer Science & Information Technology
Sir Syed University of Engineering & Technology 9|Page
Programming Fundamentals (CS-116L) LAB # 06
Example:
height=int(input("Enter height: ")) for
row in range(1, height):
for column in range(1,height):
print(row, end=" ")
print()
Output:
>>> %Run task2.py
Enter height: 7
111111
222222
333333
444444
555555 666666
Keywords break and continue:
The break and continue keywords provide additional controls to a loop.
Syntax: break
Example:
# Use of break statement inside loop
for word in "string":
if word == "i":
break
print(word)
print("The end")
Output:
>>> %Run 'lab1-task1!.py' s t r
The end
>>>
Syntax: continue
Example:
# Program to show the use of continue statement inside
Loops for val in "string":
if val == "i":
continue
print(val)
print("The end")
Output:
>>> %Run 'lab1-task1!.py' s t r n
g The end
>>>
EXERCISE
A. Point out the errors, if any, and paste the output in the following Python programs.
1. Code
prompt = "\nPlease enter the name of a city you have visited:"
prompt+="\n(Enter 'quit' when you are finished.)"
while True:
city = str(input(prompt))
if city == quit:
break;
else:
print("I'd love to go to " , city.title() , "!") Output
2. Code
if x>2: if y>2:
z=x+y
print(“z is”, y)
else:
print (“x is”, x)
Output
3. Code
balance = int(input("enter yourbalance1:"))
while true:
if balance <=9000:
continue;
balance = balance+999.99
print("Balance is", balance)
Output
1. Code
i = 10 if
(i==10):
#First if statement
if (i < 15): print ("i is
smaller than 15")
# Nested - if statement
# Will only be executed if statement above
# it is true
if (i < 12):
print ("i is smaller than 12 too") else:
print ("i is greater than 15")
Output
2. Code
i = 1 j = 2 k i = 1 j =
= 3 if i > j: 2 k = 3
if i > k: if i > j:
print('A') if i> k:
else: print('A') else:
print('B') print('B')
Output
3. Code
# nested for loops for i in
range(0, 5): for j
in range(i):
print(i, end=' ')
print()
Output
1. Write a program to add first seven terms twice of the following series:
LAB # 07
FUNCTIONS
OBJECTIVE
Create python function using different argument types.
THEORY
Functions can be used to define reusable code and organize and simplify code. Basically, we can
divide functions into the following two types:
A function is a block of organized, reusable code that is used to perform a single, related action.
Functions provide better modularity for your application and a high degree of code reusing.
As already known, Python gives you many built-in functions like print(), etc. But also allow to
create your own functions. These functions are called user-defined functions.
Defining a Function:
A function definition consists of the function’s name, parameters, and body. Python allows to define
functions to provide the required functionality. Here are simple rules to define a function in Python.
• Function blocks begin with the keyword def followed by the function name and parentheses
( ( ) ).
• Any input parameters or arguments should be placed within these parentheses. You can also
define parameters inside these parentheses.
• The code block within every function starts with a colon (:) and is indented.
Syntax:
def functioname (list of parameters):
Statement
Example:
Calling a Function:
Calling a function executes the code in the function. If the function returns a value, a call to that
function is usually treated as a value.
Example:
def greet_user(username): """Display a
simple greeting""" print("Hello," ,
username , "!") greet_user('Jesse')
Output:
>>> %Run task1.py Hello, Jesse !
>>>
Return Value:
The python return statement is used in a function to return something to the caller program. Use the
return statement inside a function only.
Example:
def xFunction(x, y):
print(“Add”, x + y) return
xFunction(2, 3)
Output:
>>> %Run task2.py
Add: 5
>>>
When a function doesn’t have a return statement and return statement has no value, the function
returns None.
Argument Types:
An argument is a piece of information that is passed from a function, When a function is called, it
place the value to work with in parentheses.
Following are the ways to call a function by using the following types of formal arguments:
• Required arguments
• Keyword arguments
• Default arguments
Required Arguments:
Required arguments are the arguments passed to a function in correct positional order. Here, the
number of arguments in the function call should match exactly with the function definition.
Example:
def square(x):
y=x*x return
y x=10
result=square(x)
print("The result of" , x , "squared is", result)
Output:
>>> %Run task2.py
The result of 10 squared is 100 >>>
Keyword Arguments:
Keyword arguments are related to the function calls. When thw keyword argument is used in a
function call, the caller identifies the arguments by the parameter name. This allows to skip the
arguments or place them out of order because the Python interpreter is able to use the keywords
provided to match the values with parameters.
Example:
def print_info(name,age):
"This prints a passed info into this
function"
print("Name:", name) print("Age:" , age)
return
print_info(name ='Mike',age=50)
Output:
>>> %Run task3.py
Name: Mike
Age: 50
>>>
Default Arguments:
A default argument is an argument that assumes a default value if a value is not provided in the
function call for that argument.
Example:
def print_info(name,age=35):
"This prints a passed info into this
function" print("Name:", name)
print("Age:" , age) return
print_info(name ='Mike',age=50)
print_info(name ='Mary')
Output:
>>> %Run task4.py
Name: Mike
Age: 50
Name: Mary
Age: 35 >>>
EXERCISE
A. Point out the errors, if any, and paste the output also in the following Python programs.
1. Code
define sub(x, y)
return x + y
Output
2. Code
define describe_pet(pet_name, animal_type='dog'):
print("\nI have a " , animal_type ,".")
print("My " , animal_type + "'s name is " , pet_name +
".")
Output
2. Code
def type_of_int(i): if i
// 2 == 0: return
'even' else:
return 'odd'
Output
Output
2. Code
def return_none(): return
print(return_none())
Output
3. Code
def test_range(n):
if n in range(3,9):
print( n,"is in the range")
else :
print("The number is outside the given range.")
test_range(7)
test_range(10)
test_range(4)
Output
1. Write a function called favorite_book() that accepts one parameter, title. The function should
print a message, such as One of my favorite books is Alice in Wonderland. Call the function,
making sure to include a book title as an argument in the function call.
2. Write a function called max( ), that returns the maxium of three integer numbers.
4. Write a function called describe_city() that accepts the name of a city and its country. The
function should print a simple sentence, such as Reykjavik is in Iceland. Give the parameter for
the country a default value. Call your function for three different cities, at least one of which is
not in the default country.
LAB # 08
LISTING
OBJECTIVE
Exploring list/arrays in python programming.
THEORY
A list can store a collection of data of any size. It is a collection which is ordered and changeable.
The elements in a list are separated by commas and are enclosed by a pair of brackets [ ].
Creating a lists:
A list is a sequence defined by the list class but also have alternative for creation of list without
built-in function.
Syntax: With Built-in function list( )
list1 = list() # Create an empty list
list2 = list([2, 3, 4])
# Create a list with elements 2, 3, 4
list3 = list(["red", "green", "blue"])
#Create a list with strings
list4 = list(range(3, 6))
# Create a list with elements 3, 4, 5
list5 = list("abcd") # Create a list with characters a, b, c, d
Example:
#Create list
list_1 = ["apple", "banana", "cherry"]
#display list print("Current List:",list_1)
Example:
myList = ["The", "earth", "revolves", "around", "sun"]
print("Postive index:",myList[4]) print("Negative
index:",myList[-2])
Output:
>>> %Run task1.py
Postive index: sun Negative index: around
Output:
>>> %Run task2.py
Slicing 2 to 5 index: [4, 5, 6]
Slicing before 3rd index value: [1, 2, 4] Slicing
after 3rd index value: [5, 6, 7, 8]
EXERCISE
A. Point out the errors, if any, and paste the output also in the following Python programs.
1. Code
Output
2. Code
motorcycles = {'honda', 'yamaha', 'suzuki'}
print(motorcycles) del motorcycles(0)
print(motorcycles)
Output:
3. Code
Def dupe_v1(x):
y = []
for i in x:
if i not in y:
y(append(i))
return y
a = [1,2,3,4,3,2,1]
print a
print dupe_v1(a)
Output:
Output
2. Code
def multiply_list elements ):
(
t = 1
r
fo x in :
elements
t *= x ([1,2,9]))
return t
print(multiply_list
Output
3. Code
def add(x,lst=[] ):
if x not in lst:
lst.append(x)
return lst
def main():
list1 = add(2)
print(list1)
list2 = add(3, [11, 12, 13, 14])
print(list2) main()
Output
1. Write a program that store the names of a few of your friends in a list called ‘names’. Print
each person’s name by accessing each element in the list, one at a time.
2. Write a program that make a list that includes at least four people you’d like to invite to
dinner. Then use your list to print a message to each person, inviting them to dinner.
But one of your guest can’t make the dinner, so you need to send out a new set of invitations. Delete
that person on your list, use del statement and add one more person at the same specified index, use
the insert( ) method. Resend the invitation.
3. Write a program that take list = [30, 1, 2, 1, 0], what is the list after applying each of the
following statements? Assume that each line of code is independent.
• list.append(40)
• list.remove(1)
• list.pop(1)
• list.pop()
• list.sort()
• list.reverse()
4. Write a program to define a function called ‘printsquare’ with no parameter, take first 7 integer
values and compute their square and stored all square values in the list.
LAB # 09
OBJECTIVE
Searching and sorting data in the form of list.
THEORY
Searching:
Searching is a very basic necessity when you store data in different data structures/list. The simplest
appraoch is to go across every element in the data structure/list and match it with the value you are
searching for. This is known as Linear search.
In Python, the easiest way to search for an object is to use Membership Operators , to check whether
a value/variable exists in the sequence like string, list, tuples, sets, dictionary or not.
Syntax:
• in - Returns True if the given element is a part of the sequence.
• not in - Returns True if the given element is not a part of the sequence.
Example:
# declare a list and a string
str1 = "Hello world"
list1 = [10, 20, 30, 40, 50]
Output:
>>> %Run task1.py
Yes! w found in Hello world
Yes! 30 found in [10, 20, 30, 40, 50]
Sorting:
Sorting, like searching, is a common task in computer programming.
A Sorting is used to rearrange a given list/array elements according to a comparison operator on the
elements. The comparison operator is used to decide the new order of element in the respective data
structure.
Many different algorithms have been developed for sorting like selection sort, insertion sort , bubble
sort etc.
Bubble sort:
Bubble sort is one of the simplest sorting algorithms. The two adjacent elements of a list are checked
and swapped if they are in wrong order and this process is repeated until we get a sorted list. The
steps of performing a bubble sort are:
• Compare the first and the second element of the list and swap them if they are in wrong order.
• Compare the second and the third element of the list and swap them if they are in wrong order.
• Proceed till the last element of the list in a similar fashion.
• Repeat all of the above steps until the list is sorted.
Example:
a = [16, 19, 11, 15, 10, 12, 14]
for j in range(len(a)):
#initially swapped is false
swapped = False
i = 0
while i<len(a)-1:
#comparing the adjacent elements
if a[i]>a[i+1]:
#swapping
a[i],a[i+1] = a[i+1],a[i]
#Changing the value of swapped
swapped = True
i = i+1
#if swapped is false then the list is sorted
#we can stop the loop
if swapped == False:
break
print (a)
Output:
>>> %Run task2.py
[10, 11, 12, 14, 15, 16, 19]
>>>
EXERCISE
F. Point out the errors, if any, and paste the output also in the following Python programs.
3. Code
'apple' is in ['orange', 'apple', 'grape']
Output
2. Code
def countX(lst, x):
return lst.count(x)
Output:
Output
2. Code
test_list = [1, 4, 5, 8, 10]
print ("Original list : " , test_list)
if(test_list == sorted(test_list)):
print ("Yes, List is sorted.")
else :
print ("No, List is not sorted.")
Output
1. Write a program that take function which implements linear search. It should take a list and an
element as a parameter, and return the position of the element in the list. The algorithm consists of
iterating over a list and returning the index of the first occurrence of an item once it is found. If the
element is not in the list, the function should return ‘not found’ message.
2. Write a program that create function that takes two lists and returns True if they have at least one
common member. Call the function with atleast two data set for searching.
3. Write a program that create function that merges two sorted lists and call two list with random
numbers.
LAB # 10
OBJECTIVE
Getting familiar with other data storing techniques - Tuple and Dictionary.
THEORY
Tuple:
A tuple is a sequence of immutable Python objects. Tuples are like lists, but their elements are fixed,
that once a tuple is created, you cannot add new elements, delete elements, replace elements, or
reorder the elements in the tuple.
Syntax for creating tuple:
tup1 =() #Empty tuple
tup2 = ('physics', 'chemistry') #Tuple of string)
tup3 = (1, 2, 3, 4, 5 ) #Tuple of integer
Output:
>>> %Run task1.py
tup1[2]: 1997
tup2[1:5]: (2, 3, 4, 5)
Tuple Functions:
cmp(tuple1, tuple2) Compares elements of both tuples.
len(tuple) Gives the total length of the tuple.
Dictionary:
A dictionary is a container object that stores a collection of key/value pairs. It enables
fast retrieval, deletion, and updating of the value by using the key. A dictionary is also known as a
map, which maps each key to a value.
Output:
>>> %Run task2.py
value: xyz
value: 26
Output:
>>> %Run task3.py
Add item:{'111-31':'John', '111-32':'Peter', '111-33': 'Susan'}
Delete item: {'111-32': 'Peter', '111-33': 'Susan'}
Dictionary Methods:
keys(): tuple Returns a sequence of keys in form of tuple.
values(): tuple Returns a sequence of values.
items(): tuple Returns a sequence of tuples. Each tuple is (key, value) for an item.
clear(): None Deletes all entries.
get(key): value Returns the value for the key.
popitem(): tuple Returns a randomly selected key/value pair as a tuple and removes
the selected item.
EXERCISE
G. Point out the errors, if any, and paste the output also in the following Python programs.
4. Code
t = (1, 2, 3)
t.append(4)
t.remove(0)
del tup[0]
Output
2. Code
1user_0=['username':'efermi','first':'enrico','last':'fermi',]
for key, value in 1user_0.items():
print("\nKey: " ,key)
print("Value: " ,value)
Output:
4. Code
def main():
Department of Computer Science & Information Technology
Sir Syed University of Engineering & Technology 33 | P a g e
Programming Fundamentals (CS-116L) LAB # 10
Output
1. Write a program that create a buffet-style restaurant offers only five basic foods. Think of five
simple foods, and store them in a tuple. (Hint:Use a for loop to print each food the restaurant
offers. Also the restaurant changes its menu, replacing two of the items with different foods and
display the menu again.
2. Write a program for “Guess the capitals” using a dictionary to store the pairs of states and
capitals so that the questions are randomly displayed. The program should keep a count of the
number of correct and incorrect responses.
3. Write a pogram that make a dictionary called favorite_places. Think of three names to use as keys
in the dictionary, and store three favorite places for each person through list. Loop through the
dictionary, and print each person’s name and their favorite places.
Output look alike:
abc likes the following places:
- Bear Mountain
- Death Valley
- Tierra Del Fuego
•
LAB # 11
MODULES AND PACKAGES
OBJECTIVE
Getting familiar with the envoirnment for using modules and packages.
THEORY
Modules
A module allows you to logically organize your Python code. A file containing a set of functions
you want to include in your application.
Create a Module
To create a module just save the code you want in a file with the file extension .py:
Example
Save this code in a file named mymodule.py
def greeting(name):
print("Hello, " ,name)
Use a Module
Now use different ways to call the module we just created, by using the import statement:
i) import module1[, module2[,... moduleN]
ii) import module as m
iii) from module import functionName
Example
Import the module named mymodule, and call the greeting function:
import mymodule
mymodule.greeting("XYZ")
Built-in Modules
There are several built-in modules in Python, which you can import, here is the example of math
and sys module;
Example:
from math import pi
r=int(input("Enter:"))
print("Area:" , pi*(r**2))
Output:
>>> %Run task1.py
enter:3
Area: 28.27
Output:
>>> %Run task2.py
3.7.5 (tags/v3.7.5:5c02a39a0b, Oct 14 2019, 23:09:19) [MSC v.1916 32 bit (Intel)]
Packages
A package is a collection of python modules, i.e., a package is a directory of python modules
containing an additional __init__.py file. Each package in Python is a directory which must contain
a special file called __init__.py. This file can be empty, and it indicates that the directory it contains
is a Python package, so it can be imported the same way a module can be imported. There are 130k
+ packages and still growing , numpy is one of the most running and useful python’s package
NumPy
NumPy is a purposely an array-processing package. It provides a high-performance
multidimensional array object, and tools for working with these arrays. It is the fundamental
package for scientific computing with python.
Installation:
In Thonny, there is a menu and select Tools option and then select Manage packages,
search numpy and install it.
EXERCISE
H. Point out the errors, if any, and paste the output also in the following Python programs.
1. Code:
import sys as s
print(sys.executable)
print(sys.getwindowsversion())
Output:
2. Code:
import datetime
from datetime import date
import times
# Returns the number of seconds
print(time.time())
# Converts a number of seconds to a date object
print(datetime.datetime.now())
Output:
3. Code:
From math import math
# using square root(sqrt) function contained
print(Math.sqrt(25) )
print(Math.pi)
# 2 radians = 114.59 degreees
print(Math.degrees(2))
Output:
4. Code:
import calendar
yy = 2017
mm = 11
# display the calendar
print(calendar.month(yy, mm))
Output:
5. Code:
import sys
print(sys.argv)
for i in range(len(sys.argv)):
if i==0:
print("The function is",sys.argv[0])
else: print("Argument:",sys.argv[i])
Output:
6. Code:
import numpy as np
# Creating array object
arr = np.array( [[ 1, 2, 3],
[ 4, 2, 5]] )
Output:
2. Write a NumPy program to create a 3x3 matrix with values ranging from 2 to 10.