Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Download as pdf or txt
Download as pdf or txt
You are on page 1of 44

Practical Workbook

Computer Programming

Name _____________________________
Year _____________________________
Batch _____________________________
Roll No _____________________________
Department: __________________________________

5th Edition Fall 2017-2018

Dept. of Computer & Information Systems Engineering


NED University of Engineering & Technology,
Karachi – 75270, Pakistan
Introduction

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

Lab Session No. Object Page No.

Fundamentals of Computer Programming and Familiarization with


1 Programming Environment using Python 3.6.3 (IDE) 1
.
2 Performing Operations on Integers and String Data Types. 6

3 Performing Operations on List Data Type object 10

4 Performing Operations on DICTIONARY Data Type object 13

5 Debugging of Programs through IDLE. 16

6 Decision making in programming (if –else & conditional operator) 20

Generalization of tasks exploiting the benefit of for loops & their


7 22
nesting

8 Generalization of tasks exploiting the benefit of while loop 24

9 Exploring PyCharm for the execution of python scripts and projects 27

10 Implementing functions (Using PyCharm) 30

11 Implementing recursive functions(Using PyCharm) 33

12 Implementing generator functions(Using PyCharm) 35

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

Fundamentals of Computer Programming and Familiarization with Programming


Environment using Python 3.6.3 (IDE).

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

Python is an interpreted, object-oriented, high-level programming language with dynamic


semantics. Its high-level built in data structures, combined with dynamic typing and dynamic
binding, make it very attractive for Rapid Application Development, as well as for use as a
scripting or glue language to connect existing components together. Python's simple, easy to
learn syntax emphasizes readability and therefore reduces the cost of program maintenance.
Python supports modules and packages, which encourages program modularity and code reuse.
The Python interpreter and the extensive standard library are available in source or binary form
without charge for all major platforms, and can be freely distributed.

Program Development with Python IDE

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.

Hello-World Program (Approach-1)

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.

Hello-World Program (Approach-2)

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

 Run the script by using command ‗python First.py‘

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.

2. Code Context (toggle)(Editor Window only)


Open a pane at the top of the edit window which shows the block context of the code
which has scrolled above the top of the window.
EXCERCISE

1. Mention the steps when ―Run Module‖ is clicked or F5 is pressed.

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

3. List down the options available in Configuration of IDLE

5
Computer Programming Lab Session 02
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Lab Session 02
OBJECT

Performing Operations on Integers and String Data Types.

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

Executing Mathematical Operators on IDLE

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

Executing String Operators on IDLE

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

>>> S[-2] # The second-to-last item from the end


>>> S # A 4-character string
'Spam'

DATA TYPE CONVERSION


>>> "42" + 1
TypeError: Can't convert 'int' object to str implicitly
>>> int("42"), str(42) # Convert from/to string
(42, '42')
>>> S = "42"
>>> I = 1
>>> S + I
TypeError: Can't convert 'int' object to str implicitly
>>> int(S) + I # Force addition
43
>>> S + str(I) # Force concatenation
'421'

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)

Write the program here:

a= , b= ,c= X1= X2=

a= , b= ,c= X1= X2=

a= , b= ,c= X1= X2=

8
Computer Programming Lab Session 02
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

2. Write down the slicing statements to generate following outputs when


string=‘COMPUTERPROGRAMMING‘:

Output: PUTER Statement:

Output: GRAMM Statement:

Output: PROGRAM Statement:

Output: COMPUTER Statement:

3. Write down the extended slicing statements to generate following outputs when
string=‘COMPUTERPROGRAMMING‘

Output: RETUP Statement:

Output: MMARG Statement:

Output: MARGORP Statement:

Output: RETUPMOC Statement:

4. Develop the script to print the following pattern when string is ‗COMPUTER‘

COMPUTERS Write the program here:


OMPUTERS
MPUTERS
PUTERS
UTERS
TERS
ERS
RS
S

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.

>>> L = ['spam', 'Spam', 'SPAM!']


>>> L[2] # Offsets start at zero
'SPAM!'
>>> L[−2] # Negative: count from the right
'Spam'
>>> L[1:] # Slicing fetches sections
['Spam', 'SPAM!']
>>> L = [1, 2, 3]
>>> L[1:2] = [4, 5] # Replacement/insertion
>>> L
[1, 4, 5, 3]
>>> L[1:1] = [6, 7] # Insertion (replace nothing)
>>> L
[1, 6, 7, 4, 5, 3]
>>> L[1:2] = [] # Deletion (insert nothing)
>>> L
[1, 7, 4, 5, 3]
>>> L = [1]

10
Computer Programming Lab Session 03
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

>>> L[:0] = [2, 3, 4] # Insert all at :0, an empty slice at


front
>>> L
[2, 3, 4, 1]
>>> L[len(L):] = [5, 6, 7] # Insert all at len(L):, an empty
slice at end
>>> L
[2, 3, 4, 1, 5, 6, 7]
>>> L.extend([8, 9, 10]) # Insert all at end, named method
>>> L
[2, 3, 4, 1, 5, 6, 7, 8, 9, 10]

LIST METHOD CALLS


>>> L = ['THIS', 'IS', 'COMPUTER']
>>> L.append('PROGRAMMING') # Append method call: add item at
end
>>> L
['THIS', 'IS', 'COMPUTER', 'PROGRAMMING']
>>> L.sort()
>>> L
['COMPUTER', 'IS', 'PROGRAMMING', 'THIS']
>>> L = [1, 2]
>>> L.extend([3, 4, 5]) # Add many items at end (like in-place
+)
>>> L
[1, 2, 3, 4, 5]
>>> L.pop() # Delete and return last item (by default: −1)
5
>>> L
[1, 2, 3, 4]
>>> L.reverse() # In-place reversal method
>>> L
[4, 3, 2, 1]
>>> list(reversed(L)) # Reversal built-in with a result
(iterator)
[1, 2, 3, 4]

EXCERCISE

1. Write commands to perform operations on list L[5,6,8,9,2,1] to convert it into :

[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']

['is', 'this', 'computer', 'programming']

12
Computer Programming Lab Session 04
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Lab Session 04
OBJECT

Performing Operations on DICTIONARY Data Type 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).

Basic Dictionary Operations


>>> D = {'this': 2, 'is': 1, 'CP': 3} # Make a dictionary
>>> D['this'] # Fetch a value by key
2
>>> D # Order is "scrambled"
{'this': 2, 'is': 1, 'CP': 3}
>>> len(D) # Number of entries in dictionary
3

13
Computer Programming Lab Session 04
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

>>> 'this' in D # Key membership test alternative


True
>>> list(D.keys()) # Create a new list of D's keys
['this', 'is', 'CP']

Changing Dictionaries in Place


>>> D
{'this': 2, 'is': 1, 'CP': 3}
>>> del D['this'] # Delete entry
>>> D
{'is': 1, 'CP': 3}
>>> D['Course'] = '4' # Add new entry
>>> D
{'is': 1, 'CP': 3, 'Course': '4'}
>>> D = {'this': 2, 'is': 1, 'CP': 3}
>>> D.values()
dict_values([1, 3, '4'])
>>> D.get('this') # A key that is there
2
>>> print(D.get('game')) # A key that is missing
None
>>> D.get('good', 88)
88
# pop a dictionary by key
>>> D
{'this': 2, 'is': 1, 'CP': 3}
>>> D.pop('CP')
3
>>> D
{'is': 1}

Dictionaries as flexible lists:


When a list is used, it is illegal to assign to an offset that
is off the end of the list:
>>> L = []
>>> L[99] = 'spam'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
IndexError: list assignment index out of range

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

1. Write an script to develop the given dictionary:


D={'CP':'COMPUTER PROGRAMMING',
'FCE':'FUNDAMENTALS OF COMPUTER ENGINEERING',
'PST':'PAKISTAN STUDIES',
'BEE':'BASICS OF ELECTRICAL ENGINEERING',}

Write the program here:

2. Write a statement to add 'F.ENG': 'FUNCTIONAL ENGLISH' in the dictionary of Q1.

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

Debugging of Programs through IDLE.

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.

Program Debugging With IDLE


1. Open Python shell
2. Go to file>New and open a python script file
3. Write a program on that file

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

5. Set break point by right clicking on the particular line.

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"

f. Quit stops the execution of the entire program

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.

Attach printout here:

19
Computer Programming Lab Session 06
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Lab Session 06
OBJECT

Decision making in programming (if –else & conditional operator).

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.

Write the program here:

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.

Write the program here:

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

for target in object: # Assign object items to target


statements # Repeated loop body: use target
else: # Optional else part
statements # If we didn't hit a 'break'

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

Write the program here and attach the printout of output

22
Computer Programming Lab Session 07
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

2. Write a program to develop a pattern mentioned below:


Note: user input will define the number of lines to be generated with maximum number of *
*
** Write the program here:
***
****
*****
******
*******
********
*********
*********
********
*******
******
*****
****
***
**
*

3. Develop a program to find out the largest integer in the list given input by user.

Write the program here and attach the printout of output

23
Computer Programming Lab Session 08
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Lab Session 08
OBJECT

Generalization of tasks exploiting the benefit of while loop.

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

while test: # Loop test


statements # Loop body
else: # Optional else
statements # Run if didn't exit loop with break

EXCERCISE

1. Develop a program to generate the table (till 10) of integer given as input by user.

Write the program here and attach the printout of output

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.

Write the program here and attach the printout of output

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

Write the program here and attach the printout of output

26
Computer Programming Lab Session 09
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Lab Session 09
OBJECT

Exploring PyCharm for the execution of python scripts and projects.

THEORY

Pycharm is an IDE(Integrated Development Environment) developed for the execution of python


scripts and projects:
Steps:
1. Go to File > New Project
2. Assign the name to new project (say ‗ My_first‘)

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

Implementing functions. (Using PyCharm)

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

X = 99 # X and func assigned in module: global

def func(Y): # Y and Z assigned in function: locals

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

func(1) # func in module: result=100

Example-2

X = 88 # Global X
def func():
global X
X = 99 # Global X: outside def
func()
print(X) # Prints 99

EXCERCISE

1. Develop a simple calculator (using functions) that defines addition, subtraction,


multiplication and division operation. User selects the operation and provides the operands
then output will be generated.

Write the program here and attach the printout of output

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

Implementing recursive functions. (Using PyCharm)

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

1. Develop the Fibonacci series till user defined limit.

Write the program here and attach the printout of output

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.

Write the program and output here

34
Computer Programming Lab Session 12
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Lab Session 12
OBJECT

Implementing generator functions. (Using PyCharm)

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

1. Differentiate between recursive and generator functions.

2. Develop a generator function to produce Fibonacci series till n (defined by user)

Write your program here

35
Computer Programming Lab Session 12
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

3. Develop a generator function to produce prime number till n (defined by user)

Write the program and output here

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.

>>> t=() #An empty Tuple


>>> (1, 2) + (3, 4) # Concatenation
(1, 2, 3, 4)
>>> (1, 2) * 4 # Repetition
(1, 2, 1, 2, 1, 2, 1, 2)
>>> T = (1, 2, 3, 4) # Indexing, slicing
>>> T[0], T[1:3]
(1, (2, 3))
>>> T = ('cc', 'aa', 'dd', 'bb')
>>> tmp = list(T) #Converting tuple into list
>>> tmp
['cc', 'aa', 'dd', 'bb']
>>> tmp.sort() #Sorting list
>>> tmp
['aa', 'bb', 'cc', 'dd']
>>> T = tuple(tmp) #Converting list into tuple
>>> T
('aa', 'bb', 'cc', 'dd')
>>> sorted(T) #Sorting Tuple
['aa', 'bb', 'cc', 'dd']

EXCERCISE

1. Develop a program to replace last element of all tuples in a list

37
Computer Programming Lab Session 13
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

3. Write commands to perform operations on my_tuple = ('p','r','o','g','r','a','m','m','i','n','g')to


convert it into :

('r', 'o', 'g') Command=

('p', 'r', 'o') Command=

('m', 'i', 'n', 'g') Command=

('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.

Write the program and output here

38
Computer Programming Lab Session 14
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

Lab Session 14
OBJECT

Dealing with Files. (Using PyCharm)

THEORY

Files are named storage compartments on computer that are managed by operating system.

afile = open(filename, mode) #open a file


afile.method()

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.

Program (to read a file)


f = open("test.txt",'r') # open file in current directory
print (f.read(5))
print('\n')
print (f.read(8))
print (f.readlines(1))
print (f.readlines())

Output
this

is first
[' file for python\n']
['this is the second line\n', 'this is the third line of first
python file']

Program (to write a file)


file = open('test.txt', 'w')

file.write('This is a first script')


file.write('To add more lines in a file.')

file.close()

39
Computer Programming Lab Session 14
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

EXCERCISE

1. Develop a program to read a file in a remote directory with ‗for loop‘


Write your program here

2. Develop a script that prints the words of file separated by commas.

Write your program here

40
Computer Programming Lab Session 14
NED University of Engineering & Technology – Department of Computer & Information Systems Engineering

3. Develop a script to find the longest word in the file.

Write your program here

41

You might also like