LAB 01
LAB 01
LAB # 1:
INTRODUCTION TO PYTHON
Objectives:
● Familiarize students with Python
● To teach students the conventional coding practices in Python
Hardware/Software required:
Hardware: Desktop/ Notebook Computer
Software Tool: Python (latest stable version)
Introduction:
Python is a high-level general-purpose programming language. Because code is
automatically compiled to byte code and executed, Python is suitable for use as a scripting
language, Web application implementation language, etc. Because Python can be extended
in C and C++, Python can provide the speed needed for even compute intensive tasks.
Features of Python:
● Contains in-built sophisticated data structures like strings, lists, dictionaries, etc.
● The usual control structures: if, if-else, if-elif-else, while, plus a powerful collection
iterator (for).
● Multiple levels of organizational structure: functions, classes, modules, and packages.
They assist in organizing code. An excellent and large example is the Python standard
library.
● Compile on the fly to byte code -- Source code is compiled to byte code without a separate
compile step. Source code modules can also be "pre-compiled" to byte code files.
● Python is portable language, can run on different platforms such as Windows, Linux and
Unix etc.
● It is Dynamically typed language i.e. Data Type of value is decided in run-time, not in
advance.
● Python uses indentation to show block structure. Indent one level to show the beginning
of a block. Out-dent one level to show the end of a block. As an example, the following C-
style code:
Course Instructor: Dr. Khawar Khurshid Lab Instructor: Ammar Ahmad Khan
Artificial Intelligence
And the convention is to use four spaces (and no tabs) for each level of indentation.
Interactive Python:
If you execute Python from the command line with no script, Python gives you an interactive
prompt. This is an excellent facility for learning Python and for trying small snippets of code.
Many of the examples that follow were developed using the Python interactive prompt.
In addition, there are tools that will give you a more powerful and fancy Python interactive
mode. One example is IPython, which is available at http://ipython.scipy.org/. You may also
want to consider using IDLE. IDLE is a graphical integrated development environment for
Python. It contains a Python shell which helps you code in python by Auto-indent, Debugging
and Color-coding your program
Lab Tasks:
1. Installing Python:
>>> 6-5
1
Course Instructor: Dr. Khawar Khurshid Lab Instructor: Ammar Ahmad Khan
Artificial Intelligence
>>> 2*5
10
>>> 5**2
25
>>> 21/3
7
>>> 23/3
7
>>> 23.0/3.0
7.6666...
>>> 23%3
2
5. Operators in Python
+ Addition 4+5 9
- Subtraction 8-5 3
* Multiplication 4*5 20
/ Division 19/3 6
% Remainder 19%3 5
** Exponent 2**4 16
Operators Descriptions
Course Instructor: Dr. Khawar Khurshid Lab Instructor: Ammar Ahmad Khan
Artificial Intelligence
() Parentheses
+ - Addition, Subtraction
7. Comments in Python:
9. Strings:
Python Example:
Course Instructor: Dr. Khawar Khurshid Lab Instructor: Ammar Ahmad Khan
Artificial Intelligence
word1 = "Good"
word2 = "Morning"
print(word1[2])
Expression Function
!= not equal to
== equal to
else:
Course Instructor: Dr. Khawar Khurshid Lab Instructor: Ammar Ahmad Khan
Artificial Intelligence
z=4
if z > 70:
print ("Something is very wrong")
elif z < 7:
Output:
Index 0 1 2 3 4 5 6 7
0 1 2 3 4 5 6 7
Char p . a i s h a
acter P . a i s h h
Course Instructor: Dr. Khawar Khurshid Lab Instructor: Ammar Ahmad Khan
Artificial Intelligence
Example:
print (name, "starts with", name[0])
Output:
P. aishh starts with P
big_name = str.upper(name)
print (big_name, "has", length, "characters")
Output:
Characters map to numbers using standardized mappings such as ASCII and Unicode.
chr(number) - converts a number into a string.
Example: chr(99) is "c"
Course Instructor: Dr. Khawar Khurshid Lab Instructor: Ammar Ahmad Khan
Artificial Intelligence
a=a+1
print (a)
'for' loop
for i in range(1, 5):
print (i)
for i in range(1, 5):
print (i)
else:
print ('The for loop is over')
range ():
If you do need to iterate over a sequence of numbers, the built-in function range() comes
in handy. It generates lists containing arithmetic progressions:
Example:
for i in range(5):
print(i)
17. Functions:
Define a Function?
Course Instructor: Dr. Khawar Khurshid Lab Instructor: Ammar Ahmad Khan
Artificial Intelligence
return;
How to call a function?
function_name(parameters)
Code Example - Using a function
a = multiplybytwo(70)
The computer would see this:
a=140
Function Scope:
def changeme( mylist ):
mylist = [10,20,30];
changeme( mylist );
print ("Values outside the function: ", mylist)
18. Lists:
Lists are what they seem - a list of values. Each one of them is numbered, starting from zero.
You can remove values from the list and add new values to the end. Example: Your many
cats' names. Compound data types used to group together other values. The most versatile is
the list, which can be written as a list of comma-separated values (items) between square
brackets. List items need not all have the same type.
print cats[2]
cats.append('Catherine')
Course Instructor: Dr. Khawar Khurshid Lab Instructor: Ammar Ahmad Khan
Artificial Intelligence
>>> a[1:-1]
['eggs', 100]
>>> a[:2] + ['bacon', 2*2]
['spam', 'eggs', 'bacon', 4]
>>> 3*a[:3] + ['Boo!']
['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boo!']
>>> a= ['spam', 'eggs', 100, 1234]
>>> a[2] = a[2] + 23
>>> a
['spam', 'eggs', 123, 1234]
22. Clear the list: replace all items with an empty list:
>>> a[:] = []
>>> a
[]
23. Length of list:
>>> a = ['a', 'b', 'c', 'd']
>>> len(a)
4
24. Nest lists:
>>> q = [2, 3]
>>> p = [1, q, 4]
>>> len(p)
3
>>> p[1]
[2, 3]
list.append(x): Add an item to the end of the list; equivalent to a[len(a):] = [x].
Course Instructor: Dr. Khawar Khurshid Lab Instructor: Ammar Ahmad Khan
Artificial Intelligence
Example:
my_list = [1, 2, 3]
my_list.append(4)
list.extend(L): Extend the list by appending all the items in the given list, equivalent to
a[len(a):] = L.
Example:
my_list = [1, 2, 3]
my_list.extend([4, 5, 6])
list.insert(i, x): Insert an item at a given position. The first argument is the index of the
element before which to insert, so a.insert(0, x) inserts at the front of the list, and
a.insert(len(a), x) is equivalent to a.append(x).
Example:
my_list = [1, 2, 3]
list.remove(x): Remove the first item from the list whose value is x. It is an error if there is
no such item.
Example:
my_list = [1, 2, 3, 2]
list.pop([i]): Remove the item at the given position in the list, and return it. If no index is
specified, a.pop() removes and returns the last item in the list.
Example:
Course Instructor: Dr. Khawar Khurshid Lab Instructor: Ammar Ahmad Khan
Artificial Intelligence
my_list = [1, 2, 3, 4]
print(popped_item) # Output: 2
# Without an index
print(popped_item) # Output: 4
my_list = [1, 2, 2, 3, 2]
count = my_list.count(2)
print(count) # Output: 3
my_list = [1, 2, 3, 4]
my_list.reverse()
my_list = [1, 2, 3, 4]
my_list.reverse()
26. Tuples:
Tuples are just like lists, but you can't change their values. Again, each value is numbered
starting from zero, for easy reference.
Course Instructor: Dr. Khawar Khurshid Lab Instructor: Ammar Ahmad Khan
Artificial Intelligence
Example:
months = ('January' , 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September',
'October', 'November', ' December’)
index Value
0 Jan
1 Feb
2 Mar
3 April
4 May
5 Jun
6 Jul
7 Aug
8 Sep
9 Oct
10 Nov
11 Dec
>>> fruit
True
Course Instructor: Dr. Khawar Khurshid Lab Instructor: Ammar Ahmad Khan
Artificial Intelligence
False
27. Dictionaries:
Dictionaries are like what their name suggests - a dictionary. In a dictionary, you have an
'index' of words, and for each of them a definition.
In python, the word is called a 'key', and the definition a 'value'. The values in a dictionary
are not numbered - they are not in any specific order, either - the key does the same thing.
You can add, remove, and modify the values in dictionaries.
LAB EVALUATION:
In the main body of the program call respective function depending on user’s choice.
Program should not terminate till user chooses last option that is “Quit”.
Course Instructor: Dr. Khawar Khurshid Lab Instructor: Ammar Ahmad Khan
Artificial Intelligence
Q3: Write a program that lets the user enter in some English text, then converts the
text to Pig-Latin.
To review, Pig-Latin takes the first letter of a word, puts it at the end, and appends
“ay”. The only exception is if the first letter is a vowel, in which case we keep it as it is
and append “hay” to the end.
E.g. “hello” -> “ellohay”, and “image” -> “imagehay”
Hint: Split the entered string through split() method and then iterate over the resultant list, e.g.
“My name is John Smith”.split(“ ”) -> [“My”, “name”, “is”, “John”, “Smith”]
NOTE: A lab report is expected to be submitted for each lab. (A simple PDF will be sufficient).
Course Instructor: Dr. Khawar Khurshid Lab Instructor: Ammar Ahmad Khan