You are on page 1of 14

Bahria University, Islamabad Campus

Department of Computer Science

Department of Computing

CSL487: Introduction to Data Science Lab

Class: BSCS-6

Lab 1: Introduction to Python

Date: September 22, 2020

Instructor: Tayyaba Faisal


Bahria University, Islamabad Campus
Department of Computer Science

Lab 1: Introduction to Python

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,

Learning python for programmer


Output Statement
>>> print ("Hello, World!" )

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.

Command Name Exampl Output


e
+ Addition 4+5 9
Bahria University, Islamabad Campus
Department of Computer Science
- Subtraction 8-5 3

* Multiplication 4*5 20

/ Classic Division 19/3 6.3333

% Modulus 19%3 5

** Exponent 2**4 16

// Floor Division 19/3 6


Examples
# Python 3: Simple arithmetic
>>> 1 / 2
0.5

>>> 2 ** 3 #Exponent operator


8
>>> 17 / 3 # classic division returns a float
5.666666666666667
>>> 17 // 3 # floor division
5

>>> 23%3 #Modulus operator


2

>>> num = 8.0


>>> num += 2.5
>>> print num
10.5

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

Thank you for playing

But if we had written the script as

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:

Variables are containers for storing data values.Unlike other programming


languages, Python has no command for declaring a variable.A variable is
created the moment you first assign a value to it.

Example

print ("This program is a demo of variables")

v = 1

print ("The value of v is now", v)

v = v + 1 print ("v now equals itself plus one, making it

worth", v) print ("To make v five times bigger, you would

have to type v = v * 5") v = v * 5

print ("There you go, now v equals", v, "and not", v / 5 )

Relational operators:
Bahria University, Islamabad Campus
Department of Computer Science
Expression Function

< less than

<= less than or equal to

> greater than

>= greater than or equal to

!= 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

* / % // Multiply, divide, modulo, and floor division


+- Addition and subtraction

>> << Right and left bitwise shift


& Bitwise ‘AND’
^ | Bitwise exclusive ‘OR’ and regular ‘OR’

<= < > >= Comparison Operators


== != Equality Operators

= %= /= //= -= += *= **= Assignment operators


is is not Identity operators
Bahria University, Islamabad Campus
Department of Computer Science
in not in Membership operators

not or and Logical operators

Strings:

String literals in python are surrounded by either single quotation marks, or


double quotation marks.

'hello' is the same as "hello".

You can display a string literal with the print() function:

Example

word1 = "My"
word2 = "First"
word3 = "Python" print (word1,
word2) sentence = word1 + " " +
word2 + " " +word3
print (sentence)

Input from user:


The input() function prompts for input and returns a string.
a = input (“Enter Value for variable a:

”)

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

Accessing an individual character of a string:


Bahria University, Islamabad Campus
Department of Computer Science
variableName [ index ]
Example:
print (name, " starts with", name[0])

Output:
J. Smith starts with J input:
input: Reads a string of text from user input.
Example: name = input("What's

your name? ")

print (name, "... what a nice

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.

>>> 'artificial' + "intelligence"


'artificialintelligence'

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.

>>> s = 'hello world'


>>> print s
hello world

Strings and numbers:

ord(text) - converts a string into a number.


Example: ord(‘a’) is 97, ord("b") is 98, ...
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"

Conditional Statements:
‘if' - Statement
y = 1

if y==

1:

print ("y still equals 1, I was just checking")

‘if - else' - Statement


Example
a = 1

if a >

5:

print ("This shouldn't

happen.") else:

print ("This should happen.")

‘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:

print ("Something is very

wrong") elif z < 7:

print ("This is normal")

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

for i in range(1, 5):

print (i )
for i in

range(1, 5):

print (i)

else:

print ('The for loop is over')


Functions:
How to call a function?
function_name(parameters)
Bahria University, Islamabad Campus
Department of Computer Science
Example - Using a function def

multiplybytwo(x):

return x*2

a = multiplybytwo(70)

The computer would actually see this:


a=140
Define a Function?
def function_name(parameter_1,parameter_2):
{this is the code in the function} return {value (e.g. text or
number) to return to the main program}

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]

The range() function is especially useful in loops.

Built-in Data Structures

Python comes equipped with some useful built-in data structures, broadly similar to Java's
collections package.

Lists

Lists store a sequence of mutable items:

Example

>>> fruits = ['apple','orange','pear','banana']


>>> fruits[0]
'apple'

We can use the + operator to do list concatenation:

Example
Bahria University, Islamabad Campus
Department of Computer Science
>>> otherFruits = ['kiwi','strawberry']
>>> fruits + otherFruits
>>> ['apple', 'orange', 'pear', 'banana', 'kiwi',
'strawberry']

Python also allows negative-indexing from the back of the list.

Example

For instance, fruits[-1] will access the last element 'banana':

>>> 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:

>>> lstOfLsts = [['a','b','c'],[1,2,3],['one','two','three']]


>>> lstOfLsts[1][2]
3
>>> lstOfLsts[0].pop()
'c'
>>> lstOfLsts
[['a', 'b'],[1, 2, 3],['one', 'two', 'three']]

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

Output should be: TAYYABA FAISAL has 14 characters


3. Open IDE and run the following program. Try different integer values for separate
runs of the program. Play around with the indentation of the program lines of code
and run it again. See what happens. Make a note of what changes you made and how
Bahria University, Islamabad Campus
Department of Computer Science
it made the program behave. Also note any errors, as well as the changes you need to
make to remove the errors.
x = input("Please enter an integer: ")
if x < 0:
x = 0
print('Negative changed to zero') elif x == 0:

print('Zero')

elif x == 1:

print('Single')

else:

print('More')

Deliverables: Submit lab journal before the next lab.


More Python Tips and Tricks

This lab has briefly touched on some major aspects of Python that will be relevant to the
course. Here are some more useful tidbits:

 Use range to generate a sequence of integers, useful for generating traditional


indexed for loops:
 for index in range(3):
 print lst[index]
 After importing a file, if you edit a source file, the changes will not be immediately
propagated in the interpreter. For this, use the reload command:

>>> 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

Here is a problematic scenario involving a for loop:

pairList = [('apples', 2.00), ('oranges', 1.50),


('pears', 1.75)]
for fruit, price, color in pairList:
print '%s fruit costs %f and is the color %s' %
(fruit, price, color)

 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

 The place to go for more Python information: www.python.org


 A good reference book: Learning Python (From the UCB campus, you can read the
whole book online)

You might also like