Documente Academic
Documente Profesional
Documente Cultură
AI Lab Manual
By
UZMA JAMIL
Lab #8
Lab #9
Lab #10
Lab #11
Lab #12
Lab #13
Lab #14
Lab #15
What is Python?
Python is a popular programming language. It was created by Guido van
Rossum, and released in 1991.
It is used for:
Good to know
The most recent major version of Python is Python 3, which we shall be
using in this tutorial. However, Python 2, although not being updated with
anything other than security updates, is still quite popular.
In this tutorial Python will be written in a text editor. It is possible to write
Python in an Integrated Development Environment, such as Thonny,
Pycharm, Netbeans or Eclipse which are particularly useful when
managing larger collections of Python files.
Python Install
Many PCs and Macs will have python already installed.
To check if you have python installed on a Windows PC, search in the start bar
for Python or run the following on the Command Line (cmd.exe):
To check if you have python installed on a Linux or Mac, then on linux open the
command line or on Mac open the Terminal and type:
python --version
If you find that you do not have python installed on your computer, then you
can download it for free from the following website: https://www.python.org/
The way to run a python file is like this on the command line:
Let's write our first Python file, called helloworld.py, which can be done in any
text editor.
helloworld.py
print("Hello, World!")
Simple as that. Save your file. Open your command line, navigate to the
directory where you saved your file, and run:
Hello, World!
Congratulations, you have written and executed your first Python program.
C:\Users\Your Name>python
Or, if the "python" command did not work, you can try "py":
C:\Users\Your Name>py
From there you can write any python, including our hello world example from
earlier in the tutorial:
C:\Users\Your Name>python
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello, World!")
C:\Users\Your Name>python
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello, World!")
Hello, World!
Whenever you are done in the python command line, you can simply type the
following to quit the python command line interface:
exit()
PyCharm- Introduction
PyCharm is the most popular IDE used for Python scripting language. This chapter will give you an
introduction to PyCharm and explains its features.
PyCharm offers some of the best features to its users and developers in the following aspects:
The user interface of PyCharm editor is shown in the screenshot given below. Observe that the editor
includes various features to create a new project or import from an existing project.
From the screenshot shown above, you can see the newly created project Demo and the site-packages
folder for package management along with various other folders.
You can download the PyCharm Editor and read its official documentation at this link:
https://www.jetbrains.com/pycharm/
PyCharm – Installation
In this chapter, you will learn in detail about the installation process of PyCharm on your local computer.
Steps Involved
You will have to follow the steps given below to install PyCharm on your system. These steps show the
installation procedure starting from downloading the PyCharm package from its official website to
creating a new project.
Step 1
Download the required package or executable from the official website of PyCharm
https://www.jetbrains.com/pycharm/download/#section=windows. Here you will observe two versions of
package for Windows as shown in the screenshot given below:
Note that the professional package involves all the advanced features and comes with free trial for few
days and the user has to buy a licensed key for activation beyond the trial period. Community package is
for free and can be downloaded and installed as and when required. It includes all the basic features
needed for installation. Note that we will continue with community package throughout this tutorial.
Step 2
Download the community package (executable file) onto your system and mention a destination folder as
shown below:
Step 3
Now, begin the installation procedure similar to any other software package.
Step 4
Once the installation is successful, PyCharm asks you to import settings of the existing package if any.
This helps in creating a new project of Python where you can work from the scratch. Note that unlike
other IDEs, PyCharm only focusses on working with projects of Python scripting language.
PyCharm – Understanding Basics
This chapter will discuss the basics of PyCharm and make you feel comfortable to begin working in
PyCharm editor.
When you launch PyCharm for the first time, you can see a welcome screen with entry points to IDE such
as:
Creating or opening the project
Checking out the project from version control
Viewing the documentation
Configuring the IDE
Recall that in the last chapter, we created a project named demo1 and we will be referring to the same
project throughout this tutorial. Now we will start creating new files in the same project to understand the
basics of PyCharm Editor
The above snapshot describes the project overview of demo1 and the options to create a new file. Let us
create a new file called main.py.
This code can be run within IDE environment. The basic demonstration of running a program is discussed
below:
Note that we have included some errors within the specified code such that console can execute the code
and display output as the way it is intended to.
FOR MORE:
https://www.tutorialspoint.com/pycharm/pycharm_tutorial.pdf
Lab Activity 2
Syntax:
Print(“Hello world!”)
The input() method reads a line from input, converts into a string and returns it. The
syntax of input() method is:
Syntax:
input([prompt])
Comments:
Creating a Comment:
Comments starts with a #, and Python will ignore them:
Syntax:
#This is a comment
print("Hello, World!")
Output:
Hello, World!
Comments can be placed at the end of a line, and Python will ignore the rest of
the line:
Syntax:
print("Hello, World!") #This is a comment
Output:
Hello, World!
Comments does not have to be text to explain the code, it can also be used to
prevent Python from executing code:
Syntax:
#print("Hello, World!")
print("Cheers, Mate!")
Output:
Cheers, Mate!
Escape Sequence:
These are non-printing characters. They are special character set, each with specific
meaning. An escape sequence always begins with a back slash and is followed by one or
more special characters
Creating Variables
Syntax:
x = 5
y = "John"
print(x)
print(y)
Output:
5
John
Variables do not need to be declared with any particular type and can even
change type after they have been set.
Syntax:
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Output:
Sally
Syntax:
x = "John"
# is the same as
x = 'John'
Variable Names
A variable can have a short name (like x and y) or a more descriptive name
(age, carname, total_volume). Rules for Python variables:
Syntax:
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
Output:
Orange
Banana
Cherry
Output Variables
The Python print statement is often used to output variables.
Syntax:
x = "awesome"
print("Python is " + x)
Output:
Python is awesome
You can also use the + character to add a variable to another variable:
Syntax:
x = "Python is "
y = "awesome"
z = x + y
print(z)
Output:
Python is awesome
Experiment Description: Exercise #1
Source Code
Write or paste print of code here. Attach extra page if needed.
OUTPUT
Draw out put or past screen shot of output screen here.
Experiment Description: Exercise #2
Source Code
Write or paste print of code here. Attach extra page if needed.
OUTPUT
Draw out put or past screen shot of output screen here.
Experiment Description: Exercise #3
Source Code
Write or paste print of code here. Attach extra page if needed.
OUTPUT
Draw out put or past screen shot of output screen here.
Experiment Description: Exercise #4
Source Code
Write or paste print of code here. Attach extra page if needed.
OUTPUT
Draw out put or past screen shot of output screen here.
Experiment Description: Exercise #5
Source Code
Write or paste print of code here. Attach extra page if needed.
OUTPUT
Draw out put or past screen shot of output screen here.
NOTE: Lab instructor ask students to practice lab from the given pool of exercises
Develop / Write a program to print the value that enter by user. Also use comments in
your code.
Develop / Write a program that ask number of different subjects then display on screen.
Also use comments in your code.
Develop / Write program that Get input of your name, address, age in years,
weight and height from keyboard and display this information. Also use
comments in your code.
Lab Activity 3
Python TypeCasting
Casting is when you convert a variable value from one type to another. This is, in Python, done
with functions such as int() or float() or str() . A very common pattern is that you convert a
number, currently as a string into a proper number.
We use type cast because python is only work with string as it take input from user string by default.
When we need other data type then we use type caste for required output to convert from one to other.
Syntax:
int()
float()
str()
Operators
Operators are used to perform operations on variables and values.
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Arithmetic Operators
Arithmetic operators are used with numeric values to perform common
mathematical operations:
Assignment Operators
Assignment operators are used to assign values to variables:
Comparison Operators
Comparison operators are used to compare two values:
Logical Operators
Logical operators are used to combine conditional statements:
Identity Operators
Identity operators are used to compare the objects, not if they are equal, but if
they are actually the same object, with the same memory location:
Membership Operators
Membership operators are used to test if a sequence is presented in an object:
Bitwise Operators
Bitwise operators are used to compare (binary) numbers:
Strings
String Literals
String literals in python are surrounded by either single quotation marks, or
double quotation marks.
Syntax:
#You can use double or single quotes:
print("Hello")
print('Hello')
Output:
Hello
Hello
Assign String to a Variable
Assigning a string to a variable is done with the variable name followed by an
equal sign and the string:
Syntax:
a = "Hello"
print(a)
Output:
Hello
Multiline Strings
You can assign a multiline string to a variable by using three quotes:
Syntax:
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
Output:
Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.
Slicing
You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to return a part
of the string.
Syntax:
Output:
llo
Negative Indexing
Get the characters from position 5 to position 1, starting the count from the end
of the string:
Syntax:
b = "Hello, World!"
print(b[-5:-2])
Output:
orl
String Length
To get the length of a string, use the len() function.
Syntax:
a = "Hello, World!"
print(len(a))
Output:
13
String Methods
Python has a set of built-in methods that you can use on strings.
The strip() method removes any whitespace from the beginning or the end:
Syntax:
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"
Syntax:
a = "Hello, World!"
print(a.lower()) # returns "hello, world!"
Syntax:
a = "Hello, World!"
print(a.upper()) # returns "HELLO, WORLD!"
Syntax:
a = "Hello, World!"
print(a.replace("H", "J")) # returns "Jello, World!"
Learn more about String Methods with our String Methods Reference
String Concatenation
To concatenate, or combine, two strings you can use the + operator.
Syntax:
a = "Hello"
b = "World"
c = a + b
print(c)
Output:
HelloWorld
Another Example
Syntax:
a = "Hello"
b = "World"
c = a + " " + b
print(c)
Output:
Hello World
Experiment Description: Exercise #1
Source Code
Write or paste print of code here. Attach extra page if needed.
OUTPUT
Draw out put or past screen shot of output screen here.
Experiment Description: Exercise #2
Source Code
Write or paste print of code here. Attach extra page if needed.
OUTPUT
Draw out put or past screen shot of output screen here.
Experiment Description: Exercise #3
Source Code
Write or paste print of code here. Attach extra page if needed.
OUTPUT
Draw out put or past screen shot of output screen here.
Experiment Description: Exercise #4
Source Code
Write or paste print of code here. Attach extra page if needed.
OUTPUT
Draw out put or past screen shot of output screen here.
Experiment Description: Exercise #5
Source Code
Write or paste print of code here. Attach extra page if needed.
OUTPUT
Draw out put or past screen shot of output screen here.
Lab Activity 4
Collections (Arrays)
There are four collection data types in the Python programming language:
List
A list is a collection which is ordered and changeable. In Python lists are written
with square brackets.
Create a List:
Syntax:
Output:
Access Items
You access the list items by referring to the index number:
Syntax:
Output:
Banana
Syntax:
Output:
Syntax:
Output:
3
Add Items
To add an item to the end of the list, use the append() method:
Syntax:
Output:
Remove Item
There are several methods to remove items from a list:
Output:
['apple', 'cherry']
Copy a List
You cannot copy a list simply by typing list2 = list1, because: list2 will
only be a reference to list1, and changes made in list1 will automatically also
be made in list2.
There are ways to make a copy, one way is to use the built-in List
method copy().
Syntax:
Output:
FOR MORE:
Do self study to explore more functions of Lists.
List Methods
Python has a set of built-in methods that you can use on lists.
Tuple
A tuple is a collection which is ordered and unchangeable. In Python tuples are
written with round brackets.
Create a Tuple:
Syntax:
Output:
('apple', 'banana', 'cherry')
Tuple Functions
Access Tuple Items
You can access tuple items by referring to the index number, inside square
brackets:
Syntax:
Output:
banana
But there is a workaround. You can convert the tuple into a list, change the list,
and convert the list back into a tuple.
Syntax:
print(x)
Output:
Syntax:
Output:
Add Items
Once a tuple is created, you cannot add items to it. Tuples are unchangeable.
Syntax:
Output:
Syntax:
thistuple = ("apple",)
print(type(thistuple))
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
Output:
<class 'tuple'>
<class 'str'>
Remove Items
Tuples are unchangeable, so you cannot remove items from it, but you can
delete the tuple completely:
Syntax:
Output:
print(thistuple) #this will raise an error because the tuple no longer exists
FOR MORE:
Do self study to explore more functions of Touple.
Tuple Methods
Python has two built-in methods that you can use on tuples.
Lab Activity 5
Dictionary
A dictionary is a collection which is unordered, changeable and indexed. In
Python dictionaries are written with curly brackets, and they have keys and
values.
Syntax:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Output:
Dictionary Functions
Accessing Items
You can access the items of a dictionary by referring to its key name, inside
square brackets:
Syntax:
x = thisdict["model"]
Output:
Change Values
You can change the value of a specific item by referring to its key name:
Syntax:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
print(thisdict)
Output:
Syntax:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
Output:
Dictionary Length
To determine how many items (key-value pairs) a dictionary has, use
the len() method.
Syntax:
print(len(thisdict))
Output:
3
Adding Items
Adding an item to the dictionary is done by using a new index key and assigning
a value to it:
Syntax:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
Output:
Removing Items
There are several methods to remove items from a dictionary:
The pop() method removes the item with the specified key name:
Syntax:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
Output:
Dictionary Methods
Python has a set of built-in methods that you can use on dictionaries.
Set
A set is a collection which is unordered and unindexed. In Python sets are
written with curly brackets.
Create a Set:
Syntax:
Output:
Note: Sets are unordered, so you cannot be sure in which order the items will
appear.
Set Functions
Access Items
You cannot access items in a set by referring to an index, since sets are
unordered the items has no index.
But you can loop through the set items using a for loop, or ask if a specified
value is present in a set, by using the in keyword.
Syntax:
Output:
apple
banana
cherry
Change Items
Once a set is created, you cannot change its items, but you can add new items.
Add Items
To add one item to a set use the add() method.
To add more than one item to a set use the update() method.
Syntax:
thisset.add("orange")
print(thisset)
Output:
Syntax:
thisset = {"apple", "banana", "cherry"}
print(len(thisset))
Output:
3
Remove Item
To remove an item in a set, use the remove(), or the discard() method.
Syntax:
thisset.remove("banana")
print(thisset)
Output:
Note: If the item to remove does not exist, remove() will raise an error.
FOR MORE:
Do self study to explore more functions of Sets.
Set Methods
Python has a set of built-in methods that you can use on sets.
Lab Activity 6
Equals: a == b
Not Equals: a != b
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
If statement:
a = 33
b = 200
if b > a:
print("b is greater than a")