[go: up one dir, main page]

0% found this document useful (0 votes)
48 views15 pages

Lab 01

This lab introduces students to the fundamentals of the Python programming language. It contains 6 tasks to write and execute Python code using variables, conditionals, loops and functions. The tasks involve calculating expressions, checking multiples, comparing numbers, determining sign properties and calculating factorials without using multiplication.

Uploaded by

Rehan Basharat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views15 pages

Lab 01

This lab introduces students to the fundamentals of the Python programming language. It contains 6 tasks to write and execute Python code using variables, conditionals, loops and functions. The tasks involve calculating expressions, checking multiples, comparing numbers, determining sign properties and calculating factorials without using multiplication.

Uploaded by

Rehan Basharat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Department of Electrical Engineering

Faculty Member: LE Munadi Sial Date: 13-Sep-2023


Semester: 7th Group:

CS471 Machine Learing


Lab 1: Introduction to Python

PLO4 - PLO4 - PLO5 - PLO8 - PLO9 -


CLO4 CLO4 CLO5 CLO6 CLO7
Name Reg. No Viva /Quiz / Analysis Modern Ethics Individual
Lab of data in Tool and Team
Performance Lab Usage Work
Report

5 Marks 5 Marks 5 Marks 5 Marks 5 Marks


Ayesha Khanam 332084

Muhammad Rehan 333394


Basharat

Ahsan Bilal 341480

Machine Learning
Introduction

This laboratory exercise will introduce the fundamental aspects of the Python
programming language which is a very popular language and used extensively in
the area of Machine Learning.

Objectives

The following are the main objectives of this lab:

• Write and execute python code in Google Colaboratory (Colab)


• Create and use variables of different data types in python
• Use arithmetic and logical operations in python
• Implement conditional statements in python
• Implement WHILE and FOR loops in python
• Define and call functions in python

Lab Conduct

• Respect faculty and peers through speech and actions


• The lab faculty will be available to assist the students. In case some aspect of
the lab experiment is not understood, the students are advised to seek help
from the faculty.
• In the tasks, there are commented lines such as #YOUR CODE STARTS
HERE# where you have to provide the code. You must put the
code/screenshot/plot between the #START and #END parts of these
commented lines. Do NOT remove the commented lines.
• Use the tab key to provide the indentation in python.
• When you provide the code in the report, keep the font size at 12

Machine Learning
Theory
Python is an open-source, interpreted language which is widely used for machine
learning tasks in research, academia and industry. It has an easy-to-learn syntax
and is ideal for writing programs in a short duration. The python interpreter can
be downloaded from the website and installed on the system. By default, the
IDLE program is installed. For machine learning, it is recommended to switch to
a more powerful IDE such as PyCharm, Spyder and Jupyter etc. For this lab, we
will use Google Colab for writing python code. Google Colab is a cloud-based
platform that allows you to write python code in your web browser and provides
free access to computing resources such as GPUs.

A brief summary of the relevant keywords and functions in python is provided


below:

print() output text on console


input() get input from user on console
range() create a sequence of numbers
len() gives the number of characters in a string
if contains code that executes depending on a logical condition
else connects with if and elif, executes when conditions are not met
elif equivalent to else if
while loops code as long as a condition is true
for loops code through a sequence of items in an iterable object
break exit loop immediately
continue jump to the next iteration of the loop
def used to define a function

Machine Learning
Lab Task 1 _________________________________________________________________________ [2]
Write a program which evaluates the following three expressions for when x =
1,2,3,4 and 5.

(a) Fill the following table with the answers:

x=1 x=2 x=3 x=4 x=5


Expression 1 14 60 164 350 642

Expression 2 4.6 12.2 22.8 36.4 53.0

(b) Provide the code for both expressions in the indicated regions:

### EXPRESSION 1 CODE STARTS HERE ###


def calculate_expression(x):
result = 4 * x**3 + 5 * x**2 + 3 * x + 2
return result

for x in range(1, 6):


result = calculate_expression(x)
print(f"When x = {x}, the result is {result}")
### EXPRESSION 1 CODE ENDS HERE ###

Machine Learning
### EXPRESSION 2 CODE STARTS HERE ###
def evaluate_expression(x):
result = ((3*x**2 + 7*x)/2) - (2*x/5)
return result
for x in range(1,6):
result = evaluate_expression(x)
print(f"When x = {x}, the result is {result}")
### EXPRESSION 2 CODE ENDS HERE ###

Lab Task 2 _________________________________________________________________________ [1]


Write a program that reads in two integer inputs, then determines and prints if
the first is a multiple of the second. To input a variable, use the following syntax:

variable = input(“prompt_message”)

Remember that the above function returns a string which is stored in the
variable. You need to explicitly convert the string variable to an integer type
using the int() casting. Provide the code and screenshot of the result.

### TASK 2 CODE STARTS HERE ###


# Read the first integer input
input1 = input("Enter the first integer: ")
# Read the second integer input
input2 = input("Enter the second integer: ")
# Convert the input strings to integers
num1 = int(input1)
num2 = int(input2)
# Check if the first number is a multiple of the second
if num1 % num2 == 0:

Machine Learning
print(f"{num1} is a multiple of {num2}")
else:
print(f"{num1} is not a multiple of {num2}")
### TASK 2 CODE ENDS HERE ###

Lab Task 3 _________________________________________________________________________ [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 as follows:

if condition:
statement_1
else:
statement_2
### TASK 3 CODE STARTS HERE ###
# Prompt the user for the first number

num1 = float(input("Enter the first number: "))

# Prompt the user for the second number

num2 = float(input("Enter the second number: "))

# Compare the two numbers

if num1 == num2:

Machine Learning
print("Both numbers are equal.")

else:

if num1 > num2:

print(f"{num1} is greater than {num2}.")

else:

print(f"{num1} is lesser than {num2}.")

### TASK 3 CODE ENDS HERE ###

Machine Learning
Lab Task 4 _________________________________________________________________________ [1]
Write a program that takes two numbers as inputs. Then, the program must
compare the two numbers and print appropriately from among the following
lines:
• Both numbers are positive
• Both numbers are negative
• Both numbers are zero
• At least one number is zero
• One number is positive and the other number is negative

### TASK 4 CODE STARTS HERE ###


# Prompt the user for the first number

num1 = float(input("Enter the first number: "))

# Prompt the user for the second number

num2 = float(input("Enter the second number: "))

# Check and print based on the comparison

if num1 > 0 and num2 > 0:

print("Both numbers are positive.")

elif num1 < 0 and num2 < 0:

print("Both numbers are negative.")

elif num1 == 0 and num2 == 0:

Machine Learning
print("Both numbers are zero.")

elif num1 == 0 or num2 == 0:

print("At least one number is zero.")

else:

print("One number is positive and the other number is negative.")

### TASK 4 CODE ENDS HERE ###

Lab Task 5 _________________________________________________________________________ [1]


Write a program that calculates the factorial of a number. To calculate the
factorial, you will need to make use of a while loop. The syntax of the while loop
is given as follows:

while condition:
statement_1
statement_2

Machine Learning
### TASK 5 CODE STARTS HERE ###
# Prompt the user for an integer input

num = int(input("Enter a non-negative integer: "))

# Check if the input is negative

if num < 0:

print("Factorial is undefined for negative numbers.")

else:

# Initialize variables

factorial = 1

i=1

# Calculate the factorial using a while loop

while i <= num:

factorial *= i

i += 1

# Print the result

print(f"The factorial of {num} is {factorial}")

### TASK 5 CODE ENDS HERE ###

Machine Learning
Lab Task 6 _________________________________________________________________________ [1]
Write a function that takes 2 integer arguments and returns their product but
you must NOT use the product operator (*). You will need to provide the
function definition and the function call. (Hint: You need to make use of loops in
your function.) The function definition syntax is given below:

def function_name:
statement_1
statement_2

return output

### TASK 6 CODE STARTS HERE ###


def multiply(x, y):

result = 0

# Check if either x or y is negative, and set a flag for the final result sign

is_negative = (x < 0) ^ (y < 0)

# Convert x and y to their absolute values

x = abs(x)

y = abs(y)
Machine Learning
while y > 0:

if y % 2 == 1:

result += x

x <<= 1

y >>= 1

# If one of the input numbers was negative, make the result negative

if is_negative:

result = -result

return result

# Function call example

num1 = 5

num2 = 3

result = multiply(num1, num2)

print(f"The product of {num1} and {num2} is {result}")

### TASK 6 CODE ENDS HERE ###

Machine Learning
Lab Task 7 _________________________________________________________________________ [1]
Write a program that prompts the user for 3 strings variables. The user will
input the strings separately at the prompt, e.g. “TRI”, “GONO” and “METRY”. The
strings will then be passed to a function as arguments. The function must use a
for loop to iterate through the characters and print each character on a new
line. The function must also print the total number of characters in the final
string. For this, you can use the len() function. Note that the “TRIGONOMETRY”
string is just an example and you need to use your own string for the
submission. You also need to take screenshot of this task showing the entire
output. The for loop syntax is given as follows:

for index in iterable:


statement_1
statement_2

### TASK 7 CODE STARTS HERE ###


def Strings(str1, str2, str3):

comb_str = str1 + str2 + str3

print("Characters in the combined string:")

for char in comb_str:

print(char)

Total_Characters = len(comb_str)

print(f"Total number of characters: {Total_Characters}")

str1 = input("Enter the first string: ")

Machine Learning
str2 = input("Enter the second string: ")

str3 = input("Enter the third string: ")

Strings(str1, str2, str3)

### TASK 7 CODE ENDS HERE ###

Lab Task 8 _________________________________________________________________________ [1]


Write a program that generates the following number sequences and print the
output. You can use the range() function for this task. Use a loop to invoke the
range function iteratively.

1, 2, 3… 20
2, 4, 6… 40
3, 6, 9… 60

Machine Learning
4, 8, 12 … 80

10, 20, 30… 200

### TASK 8 CODE STARTS HERE ###


for i in range(1, 11):

for j in range(1, 21):

result = i * j

if j == 20:

# Print without a newline for the last number in each line

print(result)

else:

# Print with a comma and space for other numbers in the line

print(result, end=", ")

### TASK 8 CODE ENDS HERE ###

Machine Learning

You might also like