Uploaded by Zaid Iftikhar

CV lab1

advertisement
Department of Electrical Engineering
Faculty Member: Dr Hafsa Iqbal
Dated: 21/09/2023
Course/Section: BEE – 12D
Semester: 7
CS-477 Computer Vision
Lab#1 Python Programming-An introduction
Name
Reg. No
Junaid Ahmed
340524
Muhammad Zaid
Iftikhar
334845
Sami Ullah
333816
Muhammad Hamza
Nawaz
PLO4-CLO4
PLO5-CLO5
PLO8-CLO6
PLO9-CLO7
Investigation
Modern Tool
Usage
Ethics
Individual and
Team Work
(5 marks)
(5 marks)
(5 marks)
(5 marks)
Lab1: Python Programming-An introduction
Objectives: The following are the main objectives of this lab:
• Create variables of different data types in python
• Use arithmetic and logical operations in python
• Implement conditional statements and loops in python
• Create functions and call them in python
• Implement lists and dictionaries in python
• Read and write to files in python
Lab Instructions
 This lab activity comprises of following parts: Lab Exercises, and Post-Lab Viva/Quiz session.
 The lab report shall be uploaded on LMS.
 Only those tasks that completed during the allocated lab time will be credited to the students.
Students are however encouraged to practice on their own in spare time for enhancing their
skills.
Lab Report Instructions
All questions should be answered precisely to get maximum credit. Lab report must ensure following
items:
 Lab objectives
 Python codes
 Results (graphs/tables) duly commented and discussed
 Conclusion
Introduction
This laboratory exercise is meant to introduce the fundamental aspects of the python programming
language which will be very important in the later labs of the course.
Theory
Python is an interpreted language which is commonly used in many fields including networks,
databases, robotics and artificial intelligence etc. It has an easy-to-learn syntax and is ideal for
developing prototypes in a short amount of time. Python scripts are written in .py file which is then
interpreted and executed by the python interpreter.
A brief summary of the relevant keywords and functions in python is provided below. (For more
details, check the slides for this lab)
print()
input()
range()
len()
if
else
elif
while
for
break
continue
def
output text on console
get input from user on console
create a sequence of numbers
gives the number of characters in a string or list
contains code that executes depending on a logical condition
connects with if and elif, executes when conditions are not met
equivalent to else if
loops code as long as a condition is true
loops code through a sequence of items in an iterable object
exit loop immediately
jump to the next iteration of the loop
used to define a function
Lab Objectives
The objectives of this lab are to familiarize students with the basics and fundamental commands and
syntax of python. This will allow students to build their basics for the future lab assignments related to
computer vision. In the last task of the lab, students will also be introduced to the basics of file handling
which will be used later in the computer vision related lab assignments.
Lab Task 1
Write a program that prompts the user for two numbers as input. Then, the program must
compare the two numbers and print if they are equal or not. If the numbers are not equal, it
must also print which number is greater (or lesser) than the other. The syntax for conditional
statements is given below:
if condition:
statement_1
else:
statement_2
Code:
num1 = input("Please enter first number: ")
num2 = input("Please enter second number: ")
if num1 == num2: #checks if equal
print("Both numbers are equal")
elif num1 > num2:#checks if one is greater than the other
print("the first number (" ,num1, ") is greater than the second number."
)
else:
print("the second number (", num2 , ") is greater than the first. ")
Results:
Lab Task 2
Create a list with the sequence 1, 2, 3… 20. Then using the slice operation (:) on this list, print
the following sub-lists:
5, 6, 7… 20
1, 2, 3… 12
7, 8, 9 … 16
4, 5
11, 12, 13, 14
Code:
my_list = list(range(1, 21))
sublist1
sublist2
sublist3
sublist4
sublist5
=
=
=
=
=
my_list[4:19] # 5, 6, 7, ..., 20
my_list[:12] # 1, 2, 3, ..., 12
my_list[6:16] # 7, 8, 9, ..., 16
my_list[3:5] # 4, 5
my_list[10:14] # 11, 12, 13, 14
print("Sub-list
print("Sub-list
print("Sub-list
print("Sub-list
print("Sub-list
1:",
2:",
3:",
4:",
5:",
sublist1)
sublist2)
sublist3)
sublist4)
sublist5)
Results:
Lab Task 3
Write a function that takes 2 lists as arguments. Both the lists must be of the same length. The
function should calculate the product of the corresponding items and place them in a third list.
You must NOT use the product operator (*). You need to provide the function definition and
the function call in the code. (Hint: You need to make use of loops in your function.) The
function definition syntax is given as follows:
def function_name:
statement_1
…
return output
Code:
def calculate_product(list1, list2):
# Check if the lists have the same length
if len(list1) != len(list2):
raise ValueError("Input lists must have the same length")
# Initialize an empty result list
result = []
# Calculate the product of corresponding items and append to the result
list
for i in range(len(list1)):
product = 0
for j in range(list1[i]):
product += list2[i]
result.append(product)
return result
def main():
print("The product for two lists, [1,2,3] and [4,1,9] is: ",
calculate_product([1,2,3],[4,1,9]))
Results:
Lab Task 4
In this task, you will make use of dictionaries. Write a program that first prompts the user to
input five strings which will be the keys of the dictionary. Then, the program must prompt the
user to input the values of the respective keys. When entering the values, the user must be
shown the key whose value is being input. Once all values are entered, display the dictionary.
Code:
my_dict = {} #initializes empty dictionary and lists
key = []
value = []
for i in range(5): #keys taken as inputs
key.append(input(f"Enter key {i + 1}: "))
for i in range(5): #values for different keys taken as input and stored into
dictionary
value.append(input(f"Enter the value for '{key[i]}': "))
my_dict[key[i]] = value[i]
print("Dictionary:")
for key, value in my_dict.items():
print(f"{key}: {value}")
Results:
Lab Task 5
In this task, you will focus on file handling. Write code that first creates a text file “lab2.txt”
with the message “My name is <your_name>”. Then, your code must open the file in read
mode and display the contents of the text file. Next, the file must be opened in append mode
and the message “My registration number is <reg_number>” must be added to the text file.
Finally, the file is read again to display the modified contents.
Code:
file = open('lab2.txt', 'w')#opens the file in write mode to write a line
file.write("My name is Zaid.")
file.close()
file = open('lab2.txt', 'r')#opens in read mode to read and write that onto
console
print(file.read())
file.close()
file = open('lab2.txt', 'a')#opens in append mode to add a line
file.write(" My registration number is 334845.")
file.close()
file = open('lab2.txt', 'r')#opens in read mode to read and write that onto
console
print(file.read())
file.close()
Results:
Conclusion:
This lab was very important in teaching the python key concepts to students. Students were given
different problems to solve while using the basic syntax of python. This lab provided us with the
fundamental concepts that are to be used later in the lab assignments.
Download