Practical Workbook Computer Programming: 5 Edition Fall 2017-2018 Dept. of Computer & Information Systems Engineering
Practical Workbook Computer Programming: 5 Edition Fall 2017-2018 Dept. of Computer & Information Systems Engineering
Computer Programming
Name _____________________________
Year _____________________________
Batch _____________________________
Roll No _____________________________
Department: __________________________________
The Practical Workbook for ―Computer Programming‖ introduces the basic as well as
advance concepts of programming using Python language. Each lab session begins
with a brief theory of the topic. Many details have not been incorporated as the same
is to be covered in Theory classes. The Exercise section follows this section.
The Workbook has been arranged as fourteen labs starting with a practical on the
Introduction to programming environment and fundamentals of programming
language. Next few lab sessions deal with familiarization with different data types and
operation supported by those data types. Single stepping; an efficient debugging and
error detection technique is discussed in Lab session 5. Next lab session covers
decision making in programming and its application. Lab session 7 and 8 introduce
the concepts of loops with different examples to use them in programming.
Lab session 9 introduces a new tool ‗PyCharm‘ for execution of python projects and
scripts. Function declaration and definition concepts and examples are discussed in
lab session 10, 11 and 12. The next two experiments deal with the advance data type
in python names tuples and operations based on files like reading and writing. These
features enable the users to handle not only large amount of data, but also data of
different types (integers, characters etc.) and to do so efficiently.
CONTENTS
13 Implementing tuples 37
39
14 Dealing with Files(Using PyCharm)
Computer Programming Lab Session 01
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 01
OBJECT
THEORY
Computer programming is the act of writing computer programs, which are a sequence of
instructions written using a computer programming language to perform a specified task by the
computer. There exist a large number of high level languages. Some of these include BASIC, C,
C++, FORTRAN, Java, Pascal, Perl, PHP, Python, Ruby, and Visual Basic etc.
Introduction to Python
This lab session introduces the Integrated Development Environment (IDE) of Python 3.6.3 and
shows how to enter, edit, save, retrieve, compile, link, and run a python program in such an
environment.
After installation of Python3.6, follow following steps to develop and execute python program
Create a python script file by replacing the extension of text file (.txt) with (.py).
Do right click on the file (say first.py) and select ―Edit with IDLE‖.
The file will be opened as shown in figure 1.1
Fig. 1.1
1
Computer Programming Lab Session 01
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Do type the program and click on ―run > run module ―or press F5 to execute the program.
The window (on the next page) will appear showing the output of program
Fig. 1.2
After the prompt (>>>), any command typed will be executed as soon as Enter will be
pressed.
After installation of Python3.6, perform following steps to develop and execute python program
Create a python script file by replacing the extension of text file (.txt) with (.py).
Open command prompt by clicking on command prompt from the start> All Programs >
Accessories
Fig. 1.3
Change the path of DOS to the folder containing Frist.py with the of ‗cd‘ command
Fig. 1.4
2
Computer Programming Lab Session 01
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Fig. 1.5
Exploration of Python IDLE Options
Format Menu
1. Indent Region
Shift selected lines right by the indent width (default 4 spaces).
2. De-indent Region
Shift selected lines left by the indent width (default 4 spaces).
3. Comment Out Region
Insert ## in front of selected lines.
4. Uncomment Region
Remove leading # or ## from selected lines.
5. Tabify Region
Turn leading stretches of spaces into tabs. (Note: We recommend using 4 space blocks to
indent Python code.)
6. Untabify Region
Turn all tabs into the correct number of spaces.
7. Toggle Tabs
Open a dialog to switch between indenting with spaces and tabs.
8. New Indent Width
Open a dialog to change indent width. The accepted default by the Python community is 4
spaces.
9. Format Paragraph
Reformat the current blank-line-delimited paragraph in comment block or multiline string
or selected line in a string. All lines in the paragraph will be formatted to less than N
columns, where N defaults to 72.
10. Strip trailing whitespace
3
Computer Programming Lab Session 01
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Remove any space characters after the last non-space character of a line.
RUN Menu
1. Python Shell
Open or wake up the Python Shell window.
2. Check Module
Check the syntax of the module currently open in the Editor window. If the module has
not been saved, IDLE will either prompt the user to save or autosave, as selected in the
General tab of the Idle Settings dialog. If there is a syntax error, the approximate location
is indicated in the Editor window.
3. Run Module
Do Check Module (above). If no error, restart the shell to clean the environment then
execute the module. Output is displayed in the Shell window. Note that output requires
use of print or write. When execution is complete, the Shell retains focus and displays a
prompt. At this point, one may interactively explore the result of execution. This is
similar to executing a file with python –i file at a command line.
Options Menu
1. Configure IDLE
Open a configuration dialog and change preferences for the following:
fonts, indentation, keybindings, text color themes, startup windows and size, additional
help sources, and extensions . To use a new built-in color theme (IDLE Dark) with older
IDLEs, save it as a new custom theme.
Non-default user settings are saved in a .idlerc directory in the user‘s home directory.
Problems caused by bad user configuration files are solved by editing or deleting one or
more of the files in .idlerc.
4
Computer Programming Lab Session 01
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
2. List down the steps to be performed for the execution of python code
5
Computer Programming Lab Session 02
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 02
OBJECT
THEORY
Two of most basic data types in python language are integers and string data types. Mathematical
operations can be directly executed on IDLE while dealing with integers and the same behaviour
can be adopted with string data type object
Routine mathematical operations like subtraction, multiplication and division can be performed
in the similar way as addition operation performed below
>>> 123+456 #Addition
579
>>> 123**2 #Power
15129
>>> 2.0 >= 1 # Greater than or equal: mixed-type 1 converted to
1.0
True
>>> 2.0 == 2.0 # Equal value
True
>>> 2.0 != 2.0 # Not equal value
False
>>> s = 'a\nb\tc'
>>> s
'a\nb\tc'
>>> print(s)
a
b c
>>> S = 'Spam' # Make a 4-character string, and assign it to a
name
>>> len(S) # Length
4
>>> S[0] # The first item in S, indexing by zero-based position
'S'
In Python, we can also index backward, from the end—positive indexes count from the left,
and negative indexes count back from the right:
>>> S[-1] # The last item from the end in S
'm'
6
Computer Programming Lab Session 02
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
SLICING
>>> S[1:3] # Slice of S from offsets 1 through 2 (not 3)
'pa'
>>> S[1:] # Everything past the first (1:len(S))
'pam'
>>> S # S itself hasn't changed
'Spam'
Strings are immutable in Python i.e. they cannot be changed in place after they are created. For
example, a string can‘t be changed by assigning to one of its positions, but new string can always
be assigned to the same string. Because Python cleans up old objects
>>> S
'Spam'
>>> S[0] = 'z' # Immutable objects cannot be changed
...error text omitted...
TypeError: 'str' object does not support item assignment
>>> S = 'z' + S[1:] # But we can run expressions to make new
objects
>>> S
'zpam'
>>> 'abc' + 'def' # Concatenation: a new string
'abcdef'
>>> 'Ni!' * 4 # Repetition: like "Ni!" + "Ni!" + ...
'Ni!Ni!Ni!Ni!'
EXTENDED SLICING
The third parameter in square bracket defines
Difference between the indexes to be printed on output
Direction of access i.e. negative difference define the access direction from right to left
s='Computer'
7
Computer Programming Lab Session 02
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
a=s[::-1]
print(a)
#Output:retupmoC
a=s[1:5:1]
print(a)
# Output:ompu
a=s[1:5:2]
print(a)
# Output:op
a=s[5:1:-1]
print(a)
# Output:tupm
Input Function
Input()
The input function reads a line from provided in parenthesis and converts it to a string (stripping
a trailing newline), and returns that to the output screen.
EXCERCISE
1. Implement quadratic equation to find out both values. Provide at least three set of values for a,
b and c to get the output. A, b and c will be provided by user as input (Hint: use int function)
8
Computer Programming Lab Session 02
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
3. Write down the extended slicing statements to generate following outputs when
string=‘COMPUTERPROGRAMMING‘
4. Develop the script to print the following pattern when string is ‗COMPUTER‘
9
Computer Programming Lab Session 03
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 03
OBJECT
Performing Operations on List Data Type object.
THEORY
In Python, an object of list data type can be a collection of many data types. Python lists have
following basic properties:
Ordered collections of arbitrary objects
From a functional view, lists are just places to collect other objects Lists also maintain a
left-to-right positional ordering among the items contained in them (i.e., they are
sequences).
Accessed by offset
A component object of list can be accessed by its position.
Variable-length, heterogeneous, and arbitrarily nestable
Unlike strings, lists can grow and shrink in place (their lengths can vary), and they can
contain any sort of object, not just one-character strings (they‘re heterogeneous). Because
lists can contain other complex objects, they also support arbitrary nesting.
Of the category “mutable sequence”
Lists are mutable (i.e., can be changed in place) and can respond to all the sequence
operations used with strings, such as indexing, slicing, and concatenation. In fact, sequence
operations work the same on lists as they do on strings; the only difference is that sequence
operations such as concatenation and slicing return new lists instead of new strings when
applied to lists. Because lists are mutable, however, they also support other operations that
strings don‘t, such as deletion and index assignment operations, which change the lists in
place.
10
Computer Programming Lab Session 03
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
EXCERCISE
[1,2,5,6,8,9] Command=
[1,2,6,8,9] Command=
[1,2,6,8,9,10] Command=
11
Computer Programming Lab Session 03
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
[10,9,8,6,2,1] Command=
[8] Command=
2. Write a program to perform operations on the given list to generate following outputs :
l=['this','is','simple','computer','programming','using','python']
Sample Output
['this', 'is', 'computer', 'programming']
['this','is','simple']
['this','is', 'programming','using','python']
['programming','using','python']
12
Computer Programming Lab Session 04
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 04
OBJECT
THEORY
A dictionary is an associative array (also known as hashes). Any key of the dictionary is
associated (or mapped) to a value. The values of a dictionary can be any Python data type.
So dictionaries are unordered key-value-pairs with following properties:
Accessed by key, not offset position
Dictionaries are sometimes called associative arrays or hashes. They associate a set of
values with keys, so an item can be fetched out of a dictionary using the key under which
it is originally stored. The same indexing operation can be utilized to get components in a
dictionary as in a list, but the index takes the form of a key, not a relative offset.
Unordered collections of arbitrary objects
Unlike in a list, items stored in a dictionary aren‘t kept in any particular order. Keys
provide the symbolic (not physical) locations of items in a dictionary.
Variable-length, heterogeneous, and arbitrarily nestable
Like lists, dictionaries can grow and shrink in place (without new copies being made),
they can contain objects of any type, and they support nesting to any depth (they can
contain lists, other dictionaries, and so on). Each key can have just one associated value,
but that value can be a collection of multiple objects if needed, and a given value can be
stored under any number of keys.
Of the category “mutable mapping”
Dictionary allows in place changes by assigning to indexes (they are mutable), but they
don‘t support the sequence operations that work on strings and lists. Because dictionaries
are unordered collections, operations that depend on a fixed positional order (e.g.,
concatenation, slicing) don‘t make sense. Instead, dictionaries are the only built-in, core
type representatives of the mapping category— objects that map keys to values. Other
mappings in Python are created by imported modules.
Tables of object references (hash tables)
If lists are arrays of object references that support access by position, dictionaries are
unordered tables of object references that support access by key. Internally, dictionaries
are implemented as hash tables (data structures that support very fast retrieval), which
start small and grow on demand. Moreover, Python employs optimized hashing
algorithms to find keys, so retrieval is quick. Like lists, dictionaries store object
references (not copies, unless explicitly asked).
13
Computer Programming Lab Session 04
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
By using integer keys, dictionaries can emulate lists that seem to grow on offset assignment:
>>> D = {}
>>> D[99] = 'spam'
>>> D[99]
'spam'
>>> D
{99: 'spam'}
14
Computer Programming Lab Session 04
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
EXCERCISE
3. Write a statement to find out whether the given key (Chinese) is the part of dictionary in Q1.
4. Write a statement to print the value by providing the key (‗CP‘) to the dictionary in Q1.
15
Computer Programming Lab Session 05
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 05
OBJECT
THEORY
There are generally two types of errors namely syntax and logical errors. Syntax errors occur
when a program does not conform to the grammar of a programming language, and the compiler
cannot compile the source file. Logical errors occur when a program does not do what the
programmer expects it to do. Syntax errors are usually easy to fix because the compiler can
detect these errors. The logical errors might only be noticed during runtime. Because logical
errors are often hidden in the source code, they are typically harder to find than syntax errors.
The process of finding out defects (logical errors) in the program and fixing them is known as
debugging. Debugging is an integral part of the programming process.
Fig. 5.1
4. Go to Python Shell and select the Debug option. A window will appear as shown below
Fig. 5.2
16
Computer Programming Lab Session 05
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Fig 5.3
6. Now go to python script and click Run and notice the line highlighted by blue. Note that
the Debug Control window is opened and that the blue line states that the line 1 "S='this
is computer programming'" is ready to be executed
Fig. 5.4
a. Go button will make the program run at normal speed until a breakpoint is
encountered (or input is requested or the program finishes).
b. Step button is used to step through your code, one line at a time.
17
Computer Programming Lab Session 05
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
c. There is a pane "Locals" which shows the value of A and S. This is useful in
several ways. It shows the values of variables as they change, and it shows
the types of variables.
d. Over means that if the statement to be executed has a function call in it, go off
and do the function call without showing any details of the execution or
variables, then return and give the human control again, "step over the function"
e. Out assumes you are in some function's code, finish execution of the function at
normal speed, return from the function and then give the human control again,
"step out of the function"
Fig. 5.5
Summary
Setting breakpoints
Stepping through the source code one line at a time
Inspecting the values of variables as they change
Making corrections to the source as bugs are found
Rerunning the program to make sure, the fixes are correct
18
Computer Programming Lab Session 05
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
EXCERCISE
1. Write a script that performs at least 5 slicing operation at different position on a string (your
Firstname_LastName) saved in a variable. Each slice operation must be saved in a different
variable. Debug the program to show the assignment of values to variables through ‗debug
control‘ window through single stepping.
19
Computer Programming Lab Session 06
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 06
OBJECT
THEORY
Normally, the program flows along line by line in the order in which it appears in source code.
But, it is sometimes required to execute a particular portion of code only if certain condition is
true; or false i.e. you have to make decision in the program.
General Format
if test1: # if test
statements1 # Associated block
elif test2: # Optional elifs
statements2
else: # Optional else
statements3
The indentation (blank whitespace all the way to the left of the two nested statements here) is the
factor that defines which code block lies within the condition statement. Python doesn‘t care how
indents can be inserted (either spaces or tabs may be used), or how much an statement can be
indented (any number of spaces or tabs can be used). In fact, the indentation of one nested block
can be totally different from that of another. The syntax rule is only that for a given single nested
block, all of its statements must be indented the same distance to the right. If this is not the case,
a syntax error will appear, and code will not run until its indentation is repaired to be consistent.
Python almost forces programmers to produce uniform, regular, and readable code
The one new syntax component in Python is the colon character (:). All Python compound
statements that have other statements nested inside them—follow the same general pattern of a
header line terminated in a colon, followed by a nested block of code usually indented
underneath the header line
EXCERCISE
1. Write a program that takes a positive integer as input from user and checks whether the
number is even or odd, and displays an appropriate message on the screen. [Note: For
negative numbers, program does nothing.]
20
Computer Programming Lab Session 06
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
2. Write a script to print the grade (according to given table) when user enters his/her marks.
3. Write a program that displays ―Kaman Akmal‖ on output, if score >30, Shoaib Akhtr, if
20<score <30, and Shahid Afreedi if 10<score <20.
21
Computer Programming Lab Session 07
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 07
OBJECT
Generalization of tasks exploiting the benefit of for loops & their nesting.
THEORY
The Python for loop begins with a header line that specifies an assignment target (or targets),
along with the object you want to step through. The header is followed by a block of (normally
indented) statements that you want to repeat:
General Format
When Python runs a for loop, it assigns the items in the iterable object to the target one by one
and executes the loop body for each. The loop body typically uses the assignment target to refer
to the current item in the sequence as though it were a cursor stepping through the sequence.
EXCERCISE
1. Develop a program that takes two lists (list-1, list-2) from user as input and compares list-1
element by element with list-2 to print the common and un-common items of list-1 with
respect to list-2
22
Computer Programming Lab Session 07
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
3. Develop a program to find out the largest integer in the list given input by user.
23
Computer Programming Lab Session 08
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 08
OBJECT
THEORY
While loop repeatedly executes a block of (normally indented) statements as long as a test at the
top keeps evaluating to a true value. It is called a ―loop‖ because control keeps looping back to
the start of the statement until the test becomes false. When the test becomes false, control passes
to the statement that follows the while block. The net effect is that the loop‘s body is executed
repeatedly while the test at the top is true. If the test is false to begin with, the body never runs
and the while statement is skipped
General Format
EXCERCISE
1. Develop a program to generate the table (till 10) of integer given as input by user.
24
Computer Programming Lab Session 08
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
2. Develop a program that takes an integer (end limit of series) from user and print even
numbers within the limit specified by the user.
3. Develop a program to perform two simple transactions in a bank as long as user enters „y. to
continue.
Sample Output:
Enter your ID: **** Main Menu (after completing the selected
*********** transaction)
1. Deposit Money Do you want to continue?
2. Withdraw Amount [y/Y] _
3. Login as Different User (goes to Main Menu, if y/Y is
Select your choice …. pressed)
25
Computer Programming Lab Session 08
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
26
Computer Programming Lab Session 09
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 09
OBJECT
THEORY
Fig. 9.1
3. Right click on the project (‗ My_first‘) and select the option New > Python File
4. Assign a name to that file (say First_script)
5. Write the code in the file and click on ‗Run‘ to execute.
Program
#print in triangle
x=int(input("enter the number"))
for n in range(0,x):
n +=1
print ("*" *(0+n))
for n in range(-x,0):
n +=1
print ("*" *(0-n+1))
27
Computer Programming Lab Session 09
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Fig. 9.2
EXCERCISE
1. Write a program to print the average of 5 integer values, entered by user using for loop.
Write the program here and attach the printout of output
28
Computer Programming Lab Session 09
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
2. Explore debugging option on PyCharm using the program in Q-1 and describe it in own
wording:
Write the program here and attach the printout of output
29
Computer Programming Lab Session 10
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 10
OBJECT
THEORY
A function is a groups of statements made to execute them more than once in a program. A
function has a name. Functions can compute a result value and can have parameters that serve as
function inputs which may differ each time when function is executed
Functions are used to:
Reduce the size of code as it increases the code reusability
Split a complex problem in to multiple modules (functions) to improve manageability
Scope Example
Let‘s step through a larger example that demonstrates scope ideas. Suppose we wrote the
following code in a module file:
Fig. 10.1
Example-1
# Global scope
30
Computer Programming Lab Session 10
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
# Local scope
Z = X + Y # X is a global
return Z
Example-2
X = 88 # Global X
def func():
global X
X = 99 # Global X: outside def
func()
print(X) # Prints 99
EXCERCISE
31
Computer Programming Lab Session 10
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
2. Debug the program of Q-1 to show the assignment of operands to variables and selection of
operator through ‗debug control‘ window through single stepping, over and out options
separately.
Write down the difference in execution observed in three debugging ways, also attach the
printout here:
32
Computer Programming Lab Session 11
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 11
OBJECT
THEORY
Ability of a function to call itself.
Example:
def mysum(L):
if not L:
return 0
else:
return L[0] + mysum(L[1:]) # Call myself recursively
EXCERCISE
33
Computer Programming Lab Session 11
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
2. Generate the sum of n (user defined) natural number through recursive function.
34
Computer Programming Lab Session 12
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 12
OBJECT
THEORY
Generator functions are coded as normal def statements, but use yield statements to return results
one at a time, suspending and resuming their state between each
Example:
def gensquares(N):
for i in range(N):
yield i ** 2 # Resume here later
EXCERCISE
35
Computer Programming Lab Session 12
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
36
Computer Programming Lab Session 13
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 13
OBJECT
Implementing Tuples.
THEORY
Tuples construct simple groups of objects. They work exactly like lists, except that tuples can‘t
be changed in place (they‘re immutable) and are usually written as a series of items in
parentheses, not square brackets.
EXCERCISE
37
Computer Programming Lab Session 13
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
('p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g') Command=
4. Develop a script that takes a tuple from user and sorts it in reverse order.
38
Computer Programming Lab Session 14
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
Lab Session 14
OBJECT
THEORY
Files are named storage compartments on computer that are managed by operating system.
Here mode can be typically the string 'r' to open for text input (the default), 'w' to create and open
for text output, or 'a' to open for appending text to the end.
Output
this
is first
[' file for python\n']
['this is the second line\n', 'this is the third line of first
python file']
file.close()
39
Computer Programming Lab Session 14
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
EXCERCISE
40
Computer Programming Lab Session 14
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering
41