Lab 1 4 (AI) 1
Lab 1 4 (AI) 1
Lab no 1
Fundamentals of Artificial
Intelligence
Objectives:
Fundamental of Artificial Intelligence
Introduction to Artificial Intelligence
Types of Artificial Intelligence
Machine learning vs. Deep learning vs. Artificial intelligence
Python for Artificial Intelligence
Features and importance of Python for Artificial Intelligence
Installation of Python
Discus platform for python programming (Google Colab , Jupiter Notebook)
It is used for:
Variable in Python
When you develop a program, you need to manage values, a lot of them.
To store values, you use variables.
Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: I R T A Z A H Y D E R ID No: 902-
2023
In Python, a variable is a label that you can assign a value to it. And a
variable is always associated with a value. For example:
Naming variables
When you name a variable, you need to adhere to some rules. If you don’t,
you’ll get an error.
The following are the variable rules that you should keep in mind:
Variable names can contain only letters, numbers, and underscores (_).
They can start with a letter or an underscore (_), not with a number.
Variable names cannot contain spaces. To separate words in
variables, you use underscores for example sorted_list.
Datatypes
Python string
A string is a series of characters. In Python, anything inside quotes is a string.
And you can use either single quotes or double quotes. For example:
Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: I R T A Z A H Y D E R ID No: 902-
2023
To span a string multiple lines, you use triple-quotes “””…””” or ”’…”’. For
example:
Length of a string
To get the length of a string, you use the len() function. For example:
Slicing strings
Slicing allows you to get a substring from a string. For example:
Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: I R T A Z A H Y D E R ID No: 902-
2023
Number
Python supports integers, floats, and complex numbers.
Int
The integers are numbers such as -1, 0, 1, 2, 3, .. and they have type int.
Floats
Any number with a decimal point is a floating-point number. The term float
means that the decimal point can appear at any position in a number.
Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: I R T A Z A H Y D E R ID No: 902-
2023
Underscores in numbers
When a number is large, it’ll become difficult to read. For example:
To make the long numbers more readable, you can group digits using underscores, like this:
When storing these values, Python just ignores the underscores. It does so when displaying
the numbers with underscores on screen:
Conversion in Python
To get an input from users, you use the input() function. For example:
Operators
Comparison
operators
Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: I R T A Z A H Y D E R ID No: 902-
2023
In programming, you often want to compare a value with another value. To
do that, you use comparison operators. Python has six comparison operators,
which are as follows:
Logical operators
You may want to check multiple conditions at the same time. To do so, you
use logical operators.
and
or
not
Task
1. What is a variable?
2. When should we use “”” (tripe quotes) to define strings?
3. Assuming (name = “John Smith”), what does name[1] return?
4. What about name[-2]?
5. What about name[1:-1]?
6. How to get the length of name?
7. What is the result of f“{2+2}+{10%3}”?
8. What are the 3 types of numbers in Python?
9. Write a program to get two number from user and print sum,
difference, module, division and multiplication of the numbers,
also show the type of the enter data.
Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: I R T A Z A H Y D E R ID No: 902-
2023
Task
1. What is a
variable? Answer:
A variable in Python is a name that stores a value. It acts like a container
that holds data, which can be changed later.
Example:
Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: I R T A Z A H Y D E R ID No: 902-
2023
4. What about name[-2]?
Answer:
Negative indices count from the end. name[-2] means the second-to-last character.
Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: I R T A Z A H Y D E R ID No: 902-
2023
8. What are the 3 types of numbers in
Python? Answer:
The following are the 3 types of numbers in python
int → Integer numbers (e.g., 10, -5)
float → Decimal numbers (e.g., 3.14, -2.5)
complex → Complex numbers (e.g., 2 + 3j)
9. Write a program to get two number from user and print sum, difference,
module, division and multiplication of the numbers, also show the type
of the enter data.
Answer:
Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: I R T A Z A H Y D E R ID No: 902-
2023
Output:
Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: IRTAZA ID No: 902-
HYDER 2023
Lab no 2
Loop and Conditional Statements in Python
Objectives:
Introduction of loop and conditional statements.
Demonstration of List, tuples and dictionary.
Implementation of loop (while and for)
Implementation of Conditional statements (if, if-else, if-else-if and switch)
Lists are just like dynamically sized arrays, declared in other languages (vector in C++
and ArrayList in Java). Lists need not be homogeneous always which makes it the most
powerful tool in Python. A single list may contain Datatypes like Integers, Strings, as
well as Objects. Lists are mutable, and hence, they can be altered even after their
creation.
# Creating a List
List = [10, 20, 14]
print("\nList of numbers: ")
print(List)
# using index
List = ["Test", "For", "Test"]
print("\nList Items: ")
print(List[0])
print(List[2])
Tuple is a collection of Python objects much like a list. The sequence of values stored
in a tuple can be of any type, and they are indexed by integers.
# Creating an empty Tuple
Tuple1 = ()
print("Initial empty Tuple: ")
print(Tuple1)
Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: IRTAZA ID No: 902-
HYDER 2023
Dictionary in Python is an unordered collection of data values, used to store data
values like a map, which, unlike other Data Types that hold only a single value as an
element, Dictionary holds key:value pair. Key-value is provided in the dictionary to
make it more optimized.
# Creating a Dictionary
# with Integer Keys
Dict = {1: 'Test', 2: 'For', 3: 'Test'} print("\
nDictionary with the use of Integer Keys: ")
print(Dict)
# Creating a
Dictionary # with
Mixed keys
Dict = {'Name': 'Test', 1: [1, 2, 3, 4]}
print("\nDictionary
Decision with the use of Mixed
making statement:
IfKeys: ") print(Dict)
statements are control flow statements which helps us to run a particular code only
when a certain condition is satisfied. For example, you want to print a message on the
screen only when a condition is true then you can use if statement to accomplish this in
programming. In this guide, we will learn how to use if statements in Python
programming with the help of examples.
if condition:
block_of_code
flag = True
if flag==True:
print("Welcome")
print("To")
print("BeginnersBook.com")
flag = True
if flag:
print("Welcome")
print("To")
print("BeginnersBook.com")
Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: IRTAZA ID No: 902-
HYDER 2023
num = 22
if num % 2 == 0:
print("Even Number")
else:
print("Odd Number")
Notes:
1. There can be multiple ‘elif’ blocks, however there is only ‘else’ block is allowed.
2. Out of all these blocks only one block_of_code gets executed. If the condition is true
then the code inside ‘if’ gets executed, if condition is false then the next
condition(associated with elif) is evaluated and so on. If none of the conditions is true
then the code inside ‘else’ gets executed.
num = 1122
if 9 < num < 99:
print("Two digit number")
elif 99 < num < 999:
print("Three digit number")
elif 999 < num < 9999:
print("Four digit number")
else:
print("number is <= 9 or >= 9999")
Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: IRTAZA ID No: 902-
HYDER 2023
print("Two digit Negative Number")
Loop:
range(start, stop): generates a set of whole numbers starting from start to stop-1.
For example:
range(5, 9) is equivalent to [5, 6, 7, 8]
range(start, stop, step_size): The default step_size is 1 which is why when we didn’t
specify the step_size, the numbers generated are having difference of 1. However by
specifying step_size we can generate numbers having the difference of step_size.
For example:
range(1, 10, 2) is equivalent to [1, 3, 5, 7, 9]
Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: IRTAZA ID No: 902-
HYDER 2023
Lets use the range() function in for loop:
While Loop
While loop is used to iterate over a block of code repeatedly until a given condition
returns false.
The main difference is that we use while loop when we are not certain of the number of
times the loop requires execution, on the other hand when we exactly know how many
times we need to run the loop, we use for loop.
Syntax of while loop
while condition:
#body_of_while
Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: IRTAZA ID No: 902-
HYDER 2023
num = 1
# loop will repeat itself as long as
# num < 10 remains true
while num <
10:
print(num)
#incrementing the value of
num num = num + 3
Nested while loop in Python
When a while loop is present inside another while loop then it is called nested while loop.
Lets take an example to understand this concept.
i=1
j=5
while i < 4:
while j < 8:
print(i, ",", j)
j=j+1
i=i+1
num = 10
while num >
6:
print(num)
num = num-1
else:
print("loop is finished")
Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: IRTAZA ID No: 902-
HYDER 2023
Task:
Write code that reverses and sorts lists, dictionary and tuple.
Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: IRTAZA ID No: 902-
HYDER 2023
Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: IRTAZA ID No: 902-
HYDER 2023
Write a Python program to sum all the items in a dictionary.
Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: IRTAZA ID No: 902-
HYDER 2023
Lab no 3
Function and class in Python
Objectives:
What is function python?
Implementation of function in python.
Type of function in python?
Implementation of function type.
What is class?
Implementation of class in python
Implementation of constructor in python
Functions:
In Python, a function is a group of related statements that performs a specific task. Functions
help break our program into smaller and modular chunks. As our program grows larger and
larger, functions make it more organized and manageable. It avoids repetition and makes the
code reusable.
def function_name(parameters):
"""docstring"""
statement(s)
def my_function():
print("Hello from a
function")
Types of Functions
Basically, we can divide functions into the following two types:
Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: IRTAZA ID No: 902-
HYDER 2023
Arguments
Information can be passed into functions as arguments. Arguments are specified after the
function name, inside the parentheses. You can add as many arguments as you want, just
separate them with a comma.
Number of Arguments
By default, a function must be called with the correct number of arguments. Meaning that if your
function expects 2 arguments, you have to call the function with 2 arguments, not more, and not
less.
my_function("Emil", "Refsnes")
def my_function(*kids):
print("The youngest child is " + kids[2])
Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: IRTAZA ID No: 902-
HYDER 2023
If you do not know how many keyword arguments that will be passed into your function, add
two asterisks: ** before the parameter name in the function definition. This way the function will
receive a dictionary of arguments, and can access the items accordingly:
def my_function(**kid):
print("His last name is " + kid["lname"])
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Class
Python is an object-oriented programming language. Unlike procedure-oriented programming,
where the main emphasis is on functions, object-oriented programming stresses on objects. An
object is simply a collection of data (variables) and methods (functions) that act on those data.
Similarly, a class is a blueprint for that object.
We can think of a class as a sketch (prototype) of a house. It contains all the details about the
floors, doors, windows, etc. Based on these descriptions we build the house. House is the object.
As many houses can be made from a house's blueprint, we can create many objects from a class.
An object is also called an instance of a class and the process of creating this object is
called instantiation.
class Person:
"This is a person
class" age = 10
def greet():
print('Hello')
# Output: 10
print(Person.age)
Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: IRTAZA ID No: 902-
HYDER 2023
# Output: <function Person.greet>
print(Person.greet)
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
The self-Parameter
The self-parameter is a reference to the current instance of the class, and is used to access variables
that belong to the class.
It does not have to be named self, you can call it whatever you like, but it has to be the first
parameter of any function in the class:
del p1.age
del p1
Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: IRTAZA ID No: 902-
HYDER 2023
Task:
1. Follow the steps:
Create a class, Triangle. Its init () method should take self, angle1, angle2, and
angle3 as arguments. Make sure to set these appropriately in the body of the init
()method.
Create a method named check_angles. The sum of a triangle's three angles is It should
return True if the sum of self.angle1, self.angle2, and self.angle3 is equal 180, and False
otherwise.
Create a variable named my_triangle and set it equal to a new instance of your Triangle
class. Pass it three angles that sum to 180 (e.g. 90, 30, 60).
Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: IRTAZA ID No: 902-
HYDER 2023
2. Import the math module in whatever way you prefer. Call its sqrt function on
the number 13689 and print that value to the console.
First, def a function called cube that takes an argument called number.
Make that function return the cube of that number (i.e. that number multiplied by itself
and multiplied by itself once again).
Define a second function called by_three that takes an argument called number. if that
number is divisible by 3,by_threeshould call cube(number) and return its result.
Otherwise, by_three should return False. -Check if it works.
Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: I R T A Z A H Y ID No: 902-
DER 2023
Lab no 4
Collection in python
Objectives:
What is collection in python?
Implementation of List, dictionary and tuples.
Implementation of Json in python.
Implementation of Numpy in python.
Implementation of pandas in python.
Json:
JSON (JavaScript Object Notation) is a popular data format used for representing structured
data. It's common to transmit and receive data between a server and web application in
JSON format.
Python has a built-in package called json, which can be used to work with JSON data.
import json
Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: I R T A Z A H Y ID No: 902-
DER 2023
When you convert from Python to JSON, Python objects are converted into the
JSON (JavaScript) equivalent:
Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: I R T A Z A H Y ID No: 902-
DER 2023
Convert from JSON to Python
If you have a JSON string, you can parse it by using the json.loads() method.
What is NumPy?
NumPy is a general-purpose array-processing package. It provides a high-performance
multidimensional array object, and tools for working with these arrays.
Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: I R T A Z A H Y ID No: 902-
DER 2023
Pandas:
Pandas are an open-source, BSD-licensed Python library providing high-performance, easy-to-
use data structures and data analysis tools for the Python programming language. Python with
Pandas is used in a wide range of fields including academic and commercial domains including
finance, economics, Statistics, analytics, etc. We will learn the various features of Python Pandas
and how to use them in practice.
Key Features of Pandas
Fast and efficient DataFrame object with default and customized indexing.
Tools for loading data into in-memory data objects from different file formats.
Data alignment and integrated handling of missing data.
Reshaping and pivoting of date sets.
Label-based slicing, indexing and subsetting of large data sets.
Columns from a data structure can be deleted or inserted.
Group by data for aggregation and transformations.
High performance merging and joining of
data. Pandas deals with the following three data
structures
Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: I R T A Z A H Y ID No: 902-
DER 2023
Series
DataFrame
Panel
These data structures are built on top of Numpy array, which means they are fast.
Building and handling two or more dimensional arrays is a tedious task, burden is placed on the
user to consider the orientation of the data set when writing functions. But using Pandas data
structures, the mental effort of the user is reduced.
For example, with tabular data (DataFrame) it is more semantically helpful to think of the
index (the rows) and the columns rather than axis 0 and axis 1.
Pandas Series
A pandas Series can be created using the following constructor
Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: I R T A Z A H Y ID No: 902-
DER 2023
DataFrame
A Pandas DataFrame is a 2 dimensional data structure, like a 2 dimensional array, or a table with
rows and columns.
Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: I R T A Z A H Y ID No: 902-
DER 2023
Task
1. Write a Python program to convert JSON data to Python object.
Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: I R T A Z A H Y ID No: 902-
DER 2023
3. Write a Python program to create a new JSON file from an existing JSON file.
Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: I R T A Z A H Y ID No: 902-
DER 2023
5. Write a NumPy program to create a 3x3 matrix with values ranging from
2 to 10. Expected Output:
[[ 2 3 4]
[ 5 6 7]
[ 8 9 10]]
Artificial Intelligence
Faculty of Computing and Information Technology
(FCIT) Department of Computing Indus University,
Karachi
NAME OF STUDENT: I R T A Z A H Y ID No: 902-
DER 2023
7. Write a Pandas program to add, subtract, multiple and divide two
Pandas Series. Sample Series: [2, 4, 6, 8, 10], [1, 3, 5, 7, 9].
Artificial Intelligence