Professional Documents
Culture Documents
Department of Computing
Class: BSCS-6
Introduction
The purpose of this lab is to get familiar with Python programming language. The
programming assignments in this course will be written in Python, an interpreted, object-
oriented language that shares some features with both Java and Scheme. In this lab we will
walk through the primary syntactic constructions in Python, using short examples. I
encourage you to type all python commands your own machine. Make sure it responds the
same way.
Tools/Software Requirement
Python,
Let us try to quickly compare the syntax of python with that of C++/C#:
C++/C# Python
Comment begins with // #
Statement ends with ; No semi-colon needed
Blocks of code Defined by Defined by indentation (usually four spaces)
{}
Indentation of code and Is Must be same for same block of code (for example
use of white space irrelevant for a set of statements to be executed after a
particular if statement)
Conditional statement if-else if- if – elif – else:
else
Parentheses for loop Required Not required but loop condition followed by a colon
execution condition :
while a < n: print(a)
Python Operators
Calculations are simple with Python, and expression syntax is straightforward: the operators
+, -, * and / work as expected; parentheses () can be used for grouping.
* Multiplication 4*5 20
% Modulus 19%3 5
** Exponent 2**4 16
Comments in Python:
#I am a comment. I can say whatever I want!
Indentation:
Unlike many other languages, Python uses the indentation in the source code for
interpretation. So for instance, for the following script:
if 0 == 1:
print 'We are in a world of arithmetic pain'
Bahria University, Islamabad Campus
Department of Computer Science
print 'Thank you for playing'
will output
if 0 == 1:
print 'We are in a world of arithmetic pain'
print 'Thank you for playing'
there would be no output. So, be careful how you indent! It's best to use four spaces for
indentation -- that's what the course code uses.
Tabs vs Spaces
Because Python uses indentation for code evaluation, it needs to keep track of the level of
indentation across code blocks. This means that if your Python file switches from using tabs
as indentation to spaces as indentation, the Python interpreter will not be able to resolve the
ambiguity of the indentation level and throw an exception. Even though the code can be
lined up visually in your text editor, Python "sees" a change in indentation and most likely
will throw an exception (or rarely, produce unexpected behavior).
Variables:
Example
v = 1
Relational operators:
Bahria University, Islamabad Campus
Department of Computer Science
Expression Function
!= not equal to
== is equal to
Boolean Logic:
Boolean logic is used to make more complicated conditions for if statements that rely on
more than one condition. Python’s Boolean operators are and, or, and not. The and operator
takes two arguments, and evaluates as True if, and only if, both of its arguments are True.
Otherwise it evaluates to False.
The or operator also takes two arguments. It evaluates if either (or both) of its arguments are
False.
Unlike the other operators we’ve seen so far, not only takes one argument and inverts it. The
result of not True is False, and not False is True.
Operator Precedence:
Operator Description
() Parentheses
** Exponentiation (raise to the power)
~+- Complement, unary plus and minus
Strings:
Example
word1 = "My"
word2 = "First"
word3 = "Python" print (word1,
word2) sentence = word1 + " " +
word2 + " " +word3
print (sentence)
”)
print (a)
Indexes of String:
Characters in a string are numbered with indexes starting at 0:
Example:
name = "J. Smith“
Index
0 1 2 3 4 5 6 7
Character
J . S m i t h
Output:
J. Smith starts with J input:
input: Reads a string of text from user input.
Example: name = input("What's
name!")
Output:
What's your name? Ali
Ali... what a nice name!
There are many built-in methods which allow you to manipulate strings.
1. Like Java, Python has a built in string type. The + operator is overloaded to do string
concatenation on string values.
2. Length of string
>>> len('Help')
4
3. Upper case
>>> 'artificial'.upper()
'ARTIFICIAL'
4. Lowercase
>>> 'HELP'.lower()
'help'
Bahria University, Islamabad Campus
Department of Computer Science
We can also store expressions into variables. Notice that we can use either single quotes ' '
or double quotes " " to surround string. This allows for easy nesting of strings.
Conditional Statements:
‘if' - Statement
y = 1
if y==
1:
if a >
5:
happen.") else:
‘elif' - Statement : The elif keyword is pythons way of saying "if the previous conditions
were not true, then try this condition".
Example
Bahria University, Islamabad Campus
Department of Computer Science
z = 4 if
z > 70:
Loops in Python:
The 'while' loop: With the while loop we can execute a set of statements as
long as a condition is true.
Example
a = 0
while a <
10:
a = a + 1
print (a)
The 'for' loop: With the for loop we can execute a set of statements, once for
each item in a list, tuple, set etc
Example
print (i )
for i in
range(1, 5):
print (i)
else:
multiplybytwo(x):
return x*2
a = multiplybytwo(70)
range()
Function:
If you need to iterate over a sequence of numbers, the built-in function range() comes in
handy. It generates iterator containing arithmetic progressions:
>>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Python comes equipped with some useful built-in data structures, broadly similar to Java's
collections package.
Lists
Example
Example
Bahria University, Islamabad Campus
Department of Computer Science
>>> otherFruits = ['kiwi','strawberry']
>>> fruits + otherFruits
>>> ['apple', 'orange', 'pear', 'banana', 'kiwi',
'strawberry']
Example
>>> fruits[-2]
'pear'
>>> fruits.pop()
'banana'
>>> fruits
['apple', 'orange', 'pear']
>>> fruits.append('grapefruit')
>>> fruits
['apple', 'orange', 'pear', 'grapefruit']
>>> fruits[-1] = 'pineapple'
>>> fruits
['apple', 'orange', 'pear', 'pineapple']
The items stored in lists can be any Python data type. So for instance we can have lists of
lists:
LAB TASK:
1. Install Python on your machine by following installation manual provided
2. Declare string variable of your name and print your name in uppercase with number
of characters. Count number of characters by built-in function
print('Zero')
elif x == 1:
print('Single')
else:
print('More')
This lab has briefly touched on some major aspects of Python that will be relevant to the
course. Here are some more useful tidbits:
>>> reload(shop)
Troubleshooting
These are some problems (and their solutions) that new Python learners commonly
encounter.
Problem:
ImportError: No module named py
Solution:
When using import, do not include the ".py" from the filename.
Bahria University, Islamabad Campus
Department of Computer Science
For example, you should say: import shop
NOT: import shop.py
Problem:
NameError: name 'MY VARIABLE' is not defined
Even after importing you may see this.
Solution:
To access a member of a module, you have to type MODULE NAME.MEMBER NAME,
where MODULE NAME is the name of the .py file, and MEMBER NAME is the name
of the variable (or function) you are trying to access.
Problem:
TypeError: 'dict' object is not callable
Solution:
Dictionary looks up are done using square brackets: [ and ]. NOT parenthesis: ( and ).
Problem:
ValueError: too many values to unpack
Solution:
Make sure the number of variables you are assigning in a for loop matches the
number of elements in each item of the list. Similarly for working with tuples.
For example, if pair is a tuple of two elements (e.g. pair =('apple', 2.0))
then the following code would cause the "too many values to unpack error":
(a,b,c) = pair
Problem:
AttributeError: 'list' object has no attribute 'length' (or something similar)
Solution:
Finding length of lists is done using len(NAME OF LIST).
Problem:
Changes to a file are not taking effect.
Bahria University, Islamabad Campus
Department of Computer Science
Solution:
1. Make sure you are saving all your files after any changes.
2. If you are editing a file in a window different from the one you are using to
execute python, make sure you reload(YOUR_MODULE) to guarantee your
changes are being reflected. reload works similarly to import.
More References