CSC 201- SCIENTIFIC PROGRAMMING IN PYTHON
Part 1: Introduction
Python is a gencral purpose, interpreied, abject
purpose PL. it means. it can be useq write code for any programming task. Being an interpreted
language, it means that its code is transiated and executed by an interpreter, one statement at a
time, Being an OOP language, it means hat datain python are objects that are created from classes,
Versions of Python
There are two versions of python that currently exist together. They are python 2 and python 3,
The program written in python’ wit} pot ran on python2. Python3 is the newer version, but itis
backward-compatible with python2, python3 provide a functionality that automatically convert
code written in python? into the syntay that python} can use
Writing a python program
To write python program, there is need foran EDITOR, An editor that is specifically design for
writing program is called INTERGRATED DEVELOPMENT ENVIRONMENT (IDE). An
IDE Provide the following development:
+ Itprovides a way to run your program straight from the editor.
« Itprovides highlighting and identification that can help as you write your program.
Examples of IDEs for python development include the following;
+ NetBeans
«Eclipse
«© Bric
«IDLE (Interactive development environment)
« Wing IDE 101
To install python in windows O/S, go to this URL #http://python.org
NOTE 1: IDLE is an IDE for python where you can create open, save, edit and run python
programs. Bo
the command-line python interpreter and IDLE are available after python is installed on your
device.
To install wing IDE 101 — HTTP/Avingwave.com
NOTE :: Python programs are case sensitive; therefore, it will be wrong for example, to replace
print in the program with print.
Other contents
> Elementary of python programming.
{2}Mathematical functions
Selections in python.
Loops in python.
Functions in python.
Object and classes in python,
Lists in python. :
Inheritance and polymorphism,
+ Strings an object.
vvvv yy
Part 2: Elementary of Python Programming
The focus of this part is on learning elementary of programming techniques to solve Problem
python. Fundamental programming techniques, such as the use of variables, operators, expressions
and input and output are discussed.
Example: A program to compute the area ofa circle given the radius as 20 can be seen as follows
ComputeArea.py
14 Assign a value to radius
2radius= 20 # radius is assigned 20
3
4# Compute area
5 area = radius * radius * 3.14159
6
7 # Display results
8 print("The area for the circle of radius”, radius, “Is", area)
Note: In other programming languages, such as Java, one has to declare a variable with a data type
to specify what type of values are being stored, such as integers or text characters. Python does not
need such a declaration because it can automatically figure out the data type according to the value
assigned to the variable.
Reading Input from the Console
‘The input function can be used to ask user to input a value. For example, the following statement
prompts the user to enter a value, and then it assigns the value to a variable:
")
variable = input ("Enter 2 valu
The value entered above is a string, the function eval can be used to evaluate and convert it toa
numeric value. For example,
eval("34,5") returns 34.5
eval("345") returns 345
eval("3 + 4") returns 7, and
eval(""51 + (54 * (3 +2))") returns 321.
—{?}ComputeAverage.py
1# Prompt the user to enter th,
2 number] = eval(input("Enter
3 number2 = eval(input("Enter th,
fi umb'
4 number3 = evallinput("Enter the ‘hageumber
5
6 # Compute average
7 average = (number1 + number2 4 number3) /3
8
9 # Display result
10 print("The average of", number, nyumber2, number3,
41 "Is", average) :
Identifiers in Python
Identifiers are the names that identify the elements in a python program such as variables and
functions. For example:
numberl, number2, number3, average, input, eval, and print are the names of things that
appear in the program. In programming terminology, such names are called identifiers.
All identifiers must obey the following rules:
* An identifier is a sequence of characters that consists of letters, digits, and underscores.
* An identifier must start with a letter or an underscore. It cannot start with a digit.
© Anidentifier cannot be a keyword also called reserved words which have special meanings
in Python.
* Anidentifier can be of any length.
Avoid using abbreviations for identifiers. Using complete words is more descriptive. For example,
numberOfStudents is better than numStuds, numOfStuds, or numOfStudents. Use lowercas
letters for variable names, as in radius and area, If a name consists of several words, concatenate
them into one, making the first word lowercase and capitalizing the first letter of each subsequent
word—for example, numberOfStudents.
Variables, Assignment Statements, and Expressions in Python
Variables are used to reference values that may be changed in the program, Every variable has a
scope. The scope of a variable is the part of the program where the variable can be referenced, The
statement for assigning a value to a variable is called an assignment statement. \n Python, the
equal sign (=) is used as the assignment operator. The syntax for assignment statements is as
follows:
variable = expression
An expression represents a computation involving values, variables, and operators that, taken
together, evaluate to a value. For example, consider the following code:
radius =1.0 —# Assign 1.0 to variable radius
{3}x=5*(3/2)+3°2 # Assign the yalye of the exPression to x
xzytl # Assign the addition of y and 1t0*
area = radius *radius* 3.14159 tompute area
Named Constants
A named constant is an idemtifice that represen's @ permanent value. For example, jin the
ComputeArea program, p is a constant which is equal to 3.14159, Python does not have a special
variable to denote a constant, However, to
syntax for naming constants. You can simply create
distinguish a constant from a variable, use all uppercase letters to name a constant. For example,
you can rewrite ComputeArea Program (o use a named constant for p, as follows:
# Assign a radius
radius = 20 # radius is mow 20
# Compute area
p= 3.14159
area = radius * radius * Pl
# Display results
print("The area for the circle of radius", radius, js", area)
Numeric Data Types and Operators
eferred to as data, Python has two numeric
The information stored in a computer is generally r
types—integers and floating-point numbers—for working with the operators +, -y*)/, 44, **, and
%, The operators for numeric data types include the standard arithmetic operators, as shown
below. The operands are the values operated upon by an operator.
Numeric Operators in Python
Name Meaning Example Result
+ Addition 34+1 35
- Subtraction 34.0 - 0.1 33.9
Multiplication 300*30 © 9000
Float Division 1/2 0.5
Hf Integer Division 142 0
** Exponentiation 405 2.0
% Remainder 20 %3 2
When more than one operator is used in an expression, the following operator precedence rule is
used to determine the order of evaluation.
od first.
ion Oo integer division (//) , and remainder operators
ression contains several multiplication, division, and
plied from left to right.
© Exponentiation (**) is applies
* Multiplication (*), float divisi
(%) are applied next. If an exP!
remainder operators, they are aP
* Addition (+) and subtraction (-) operators are applied last. If'an expressioncontains several addi, operators, th ie
7 or ‘on operators, they are applied from left
to right. 1 and subtraction OP
Example: Given two point, X1, Y1 gag x2, Y2 write a Python program that computes and display
the distance between the two poigis, (Hint: Formula for computing distance is given
asif (2 — 41)? + O2 - 1)
ComputeDistance.py
1# Enter the first point with two float yalues
2x1, y1 = eval{input("Enter x1 and yz for Point 1: "))
3
4 # Enter the second point with two float values
§ x2, y2 = evallinput{"Enter x2 and yz for Point 2: "))
6
7 # Compute the distance
B distance = ({x1 - x2) * (x1 - x2) + (y1 - y2) * (y-¥2)) ** os
9
10 print(“The distance between the two points is", distance)
Example: Write a Python program to do the following tasks:
1. Prompts a user to enter two points.
2. Computes the distance between the points.
3. Use Turtle graphics to display the line that connects the two points.
4. Displays the length of the line at the center of the line.
ComputeDistanceGraphics.py
import turtle
2
3 # Prompt the user for inputting two points
4x1, y1 = eval(input("Enter x1 and y1 for point
5 x2, y2= eval(input("Enter x2 and y2 for point 2:
6
7 # Compute the distance
B distance = ((x1 -x2) ** 2+ (yl - v2) ** 2) ** 0.5
9
10 # Display two points and the connecting line
11 turtle.penup()
12 turtle goto(x1, yl) # Move to (x1, ¥2)
13 turtle.pendown()
14 turtle.write("Point 1")
15 turtle.goto(x2, y2) # Draw a line to (x2, y2)
16 turtle.write("Point 2")
v748 # Move to the center
turtlepenupl) OF the tine
pO turtle.gotol {xl +2) /2, (yr 4
21 turtle.write(distance)
22 turtle.done()
2) /2)
Part 3: Mathematical Functions, Strings, and Objects
This part introduces functions, strings, and objects in Python, and also uses them to develop
programs. Part two introduced fimdamental programming techniques and how to write simple
programs to solve basic problems,
Python Functions
A function is a group of statements that performs a specific task. Python, as well as other
programming languages, provides a library of functions. Functions, such as eval, input, print, and
int were used in the preceding parts, These are built-in functions and they are always available
within the Python interpreter. It is not necessary 10 import any modules to use these functions.
Additionally, other built-in functions include abs, max, min, pow, and round and ete.
Also, many programs are created to solve mathematical problems. The Python math module
provides the different mathematical functions. Two mathematical constants, pi and e, are ulso
defined in the math module. They can be accessed using math.pi and math.c. Whenever amodule
is to be used in a program, the module must be imported. For example, the math functions is
defined in the math module.
fabs(x) Returns the absolute value for x as a float. fabs(-2) is 2.0
ceil(x) Rounds x up to its nearest integer. ceil{2.1) is 3, ceil(-2.1) is -2
floor{x) Rounds x down to its nearest integer. floor{2.1) is 2, floor(-2.1) is -3
exp(x)_ Returns the exponential function of x (ex). exp(1) is 2.71828
log(x) Returns the natural logarithm of x. log(2.71828) Is 1.0
log(x, base) Returns the logarithm of x for the specified base. log(100, 10) is 2.0
sqrt{x) Returns the square root of x. sqrt(4.0) is 2
sin{x) Returns the sine of x. x represents an angle in radians. sin(3.14159 / 2) is 1
sin{3.14159) is 0
asin(x) Returns the angle in radians for the inverse of sine. asin{1.0) is 1.57
asin(0.5) is 0.523599
cos{x) Returns the cosine of x. x represents an angle in radians. cos(3.14159 / 2) is 0
¢05(3.14159) is -1
acos(x) Returns the angle in radians for the Inverse of cosine. acos(1.0) is 0
acos(0.5) is 1.0472
tan(x) Returns the tangent of x. x represents an angle in radians. tan(3.14159 / 4) is 1
tan{0.0) is 0
degrees{x) Converts angle x from radians to degrees, degrees(1.57) is 90
a PYfor example: Given the length of ghe yhree sides of 8 triangle, use the formula below to write a
hon program (0 comput
py pute the angles,
cos(fata-b™b-c*c)/(2epe
scab "b-8t3-c%e)/fae nc,
Ceacosl(e*c-b*B-3*3)/(-2* a0 pH))
Here in this example, in ofder to compute the lengths of the sides, we need to know the coordinates
ofthe three comer points and compute the distances between the points. Below is the program that
rompis the user to enter the x- and y.coordinates of the three corner points in a triangle and then
displays the figures angles.
ComputeAngles.py
1 import math
2
3 xt, v1.2, y2,%3, ¥3 = evallinput("Enter three points: "))
4
$ a=math.sart((x2 = x3) * (x2 = x3) + (y2- y3) * (v2 -¥3))
6 b= math.sqrt((xd - x3) * (x1 - x3) + (y2- y3) * (vt -y3))
7x math.sart((ed - x2) * (x2 = 2) + (yd -y2) * (yh -¥2))
8
9 A= math.degrees(math.acos{(a *a-b*b-c* o/(-2*b*c)))
10 B = math.degrees{math.acos{(b*b-a* a-C* o/t2*a*o)))
11c=mathdegrees{mathacos((c* ¢-b*b-a* a)/ (2° 3 “on
cr
13 print("The three angles are", round(A * 100) / 100.0,
14 round{B * 100) /:100.0, round(C * 100) / 100.0)
Strings and Characters
Inaddition to processing numeric values, you can process strings in Python. A string isa sequence
of characters and can ine
quotes "Jor double quotes ("
string represents a character For exam|
Jude text and numbers. String values must be enclosed in matching single
'), Python does not have a data type for characters. A single-character
ple,
letter ='A' # Same as lette
‘a # Same as numchar
Good morning” # Same a5 me!
Sage
Part 4: Introduction to Objects and Methods
TaPyihon,a number 1s an object, a Str js an object, and every datum is an o} Objects of th
same kind have the same type- You can. use the id function and type function to get these pi
et _R{information about an obj, teat .
the class for string is str, for Also in python, an object’s type is defined by a class. For example,
bject-oriented programm integer js int, and for float is float. The term “class” comes from
ng, mnony!
invoked to perform operations a Farther, cases ‘and types are synonymous. Methods can be
e object.
prawing Various Shapes
The Python turtle module contains meihods for moving the pen, setting the pen’s size, lifling, and
putting down the pen. A turtle is agiyally an object that is created when you import the turtle
module. You then invoke the turtle object's methods to perform operations. When a turtle object
iscreated, its position is set at (0,0) (the center of the window) and its direction is set to go straight
io the right, The turtle module uses a pen to draw shapes. By default, the pen is down (like the tip
of an actual pen touching a sheet of paper), When you move the turtle, it draws a line from the
current position to the new position, Below are the lists of methods for controlling the pen's
drawing state and the lists of methods for moving the turtle.
Turtle Pen Drawing State Methods
Method Description
turtle.pendown() Pulls the pen down—drawing when moving.
turtle.penupQ) Pulls the pen up—no drawing when movin:
turtle.pensize(width) Sets the line thickness to the specified width.
Turtle Motion Methods
Method Description
turtle.forward(d) Moves the turtle forward in the direction the turtle is headed.
turtle. backward(d) Moves the turtle backward in the opposite direction the turtle is
headed, The turtle’s direction is not changed.
turtleright(angle) Turns the turtle right by the specified angle.
turtle.Jeft(angle) Turns the turtle left by the specified angle.
turtle.goto(x, y) Moves the turtle to an absolute position.
turtle,setx(x) Moves the turtle’s x-coordinate to the specified position.
turtlesety(y) Moves the turtle’s y-coordinate to the specified position.
Sets the orientation of the turtle to a specified angle. 0-East, 90-
North, 180-West, 270-South,
turtle. home() Moves the turtle to the origin (0, 0) and east direction.
Draws a circle with the specified radius, extent, and step.
Draws a circle with the specified diameter and color.
Undo (repeatedly) the last turtle action(s).
Sets the turtle’s speed to an integer between 1 and 10, with 10
peing the fastest
turtle.setheading(angle)
furtle.circle(r, ext, step)
turtle.dot(diameter, color)
turtle.undoQ)
turtle.speed(s)
e code for drawing a triangle, a square, a pentagon, 2
The following program shows sampl
hexagon, and a circle.simpleShapes.py
import turtle
2
3H Set pen thickness to 3 pivets
4#{Pull the pen up
5
6# Pull the pen down
74 Drawa triangle
8
gturtle.penup()
10 turtle.goto(-100, -50)
11 turtle.pendown()
12 turtle.circle(40, steps = 4) # Draw a square
2B
14 turtle.penup()
15 turtle.goto(0, -50)
16 turtle.pendown()
17 turtle.circle(40, steps = $) # Draw a pentagon
18
19 turtle.penup()
20 turtle.goto(100, -50)
21 turtle.pendown()
22 turtle.circle(40, steps = 6) # Drawa hexagon
23
24 turtle.penup()
25 turtle.goto(200, -50)
26 turtle.pendown()
27 turtle.circle(40) # Drawa circle
28
29 turtle.done()
Line 1 imports the turtle module. Line 3 sets the pen’s thickness to 3 pixels. Line 4 pulls the pen
Up so that you can reposition it to (-200, -50) in line S. Line 6 puts the pen down to draw a triangle
in line 7, In line 7, the turtle object invokes the circle method with a radius of 40 and 3 steps to
draw atriangle, Similarly, the rest ofthe program draws a square (line 12), a pentagon (line 17), a
hexagon (line 22), and a circle (line 27)-
Drawing with Colors and Fonts
A turtle object contains the methods for setting colors and fonts. This section introduces more
Pen control methods and shows you how (© Set colors and fonts and write text. Below are the
lists of pen methods for controlling drawings color, and filling. Example of program that draws a
Wiangle, a square, a pentagon, a hexago" and acircle in different colors, as shown below. The
Program also adds text to the drawing.Turtle Pen Color, Filling, and Drawing Methods
Method
turtle.color(c)
turtle-fillcolor(c)
Description
Sets the pen color.
Sets the pen fill color.
eet Calls this method before filling a shape.
bein fill, Fills the shapes drawn before the last call to
wwrte-ingO Retums the fill state: True if filling, False if not
e.clear() filling. "
turtles Clears the window, The state and the position of the
turtle are not affected.
turtlesreset0) Clears the window and reset the state and position
: to the original default value.
turttesereensize(w, h) Sets the width and height of the canvas.
turlesnidetore Makes the turtle invisible.
arte ee Makes the turtle visible.
rartledsvisibteQ) ari Returns True if the turtle is visible.
turtle.write(s, font=("Arial", 8, "normal”)) Writes the string s on the turtle position. Font is a
triple consisting of fontname, fontsize, and fonttype.
ColorShapes.py
1 import turtle
2
3 turtle.pensize(3) # Set pen thickness to 3 pixels
4turtle.penup() # Pull the pen up
5 turtle.gato(-200, -50)
6turtle.pendown(} # Pull the pen down
7turtle.begin_fill!) # Begin to fill color in a shape
Bturtle.color("red")
9 turtle.circle(40, steps = 3) # Draw triangle
10 turtle.end_fill(}# Fill the shape
u
12 turtle.penup()
23 turtle.goto(-100, -50)
14 turtle.pendown()
15 turtle begin_fill{) # Begin to
16 turtle.color("blue")
T7turtle.circle(4o, steps = 4) # raw 2 §
18 turtle.end_fill{) # Fill the shape
19
20turtle.penup()
Zune goto(0, -50)
turtle.pendown|
3 faicceuncii Begin to fill color ina shape
fill color in a shape
quaregaturtle.color("green")
psturtle.circle(40, steps = 5),
gg turtle.end_fill) # Fill the shape a pentagon
7
ggturtle.penup()
ygturtle.goto(100, -50)
30turtle.pendown()
iturtle.begin_fill) # Begin to fj
32turtle.color("yellow")
33turtle.circle(40, steps = 6) #
jaturtle.end_fill)# Fill the mera hexagon
35
36turtle.penup()
37 turtle.goto(200, -50)
38turtle.pendown()
39turtle.begin_fill() # Begin to fill color ina shape
40turtle.color("purple")
Atturtle.circle(40) # Draw acircle
42turtle.end_fill() # Fill the shape
43 turtle.color("green")
44turtle,penup|)
45 turtle.goto(-100, 50)
46 turtle.pendown()
47turtle.write("Cool Colorful Shapes",
48 font=("Times", 18, "bold"))
49turtle.hideturtle()
50
51turtle.done()
ll color in a shape
Note the following:
count = count + 1 can be written in Python asi
Count = count -1 as: : count -= 2
count = count * 1 as: count *= Lett:
count += 1
Type Conversions and Rounding , ;
Ione afte cede forte ure operators aot vale, the result wil be @ loa vas
This i called pe conversion. S° « 4.5 is the same as 3.0 * 4.5, Sometimes, it is desirable 10
called spe conversion. 50+
obiain the integer part of a fractl
integer part of a float value. For ¢
onal number. You can use the int(value) function to return the
xample:poo value = 5.6
>>? int(value)
5
2?
Note that the fractional Partofy
function {0 round a numbers 2 Mmber is rncated, not rounded up. You ean also use the round
the nearest whole value. For Example:
>> value = 5.6
>»> round(value)
6
>>
Part 5: Selection Statements in Python
A program can decide which statements ip exeome based on a condition, Like all high-level
programming languages, Python provides sefection statements that let you choose actions with
two or more alternative courses, Python provides six comparison operators (also known as
relational operators), shown below, which can be used to compare two values.
Operator — Maths Symbol Name Example Output
IfR=5
< < less than R
greater than R>0 True
>= > greater than or equal to R>=0 True
= = equal to R=0 False
& % not equal to Ri=0 True
if Statements
Aone-way if statement executes the statements if the condition is true. If the condition is not true
the computer will skip to the statements after the if statement.
Python if Statement (also called a one-way if'statement) .
‘The if statement contains a logical expression (test) which data is compared and a decision is
made based on the result of the comparison.
if (condition)
(statement(s))
{expression and will execute statement(s) only if the text
Here, t es the tes
the program evaluates U te E 1
ee sion is False, the statement(s) is not executed.
“xpression is True. If the text expre
tt 2example below is a programs th |
of 5. the program display: 'at Prompts the user to enter an integ
ay ger. Ifthe number is a multiple
HiEven. © result Hipive. Ifthe number és divisil
ible by 2, the program displays
simplelfDemo.py
number = evallinput("Enter an ing
‘eae
2
3 ifnumber % 5 =
4 print("HiFive")
5
gifnumber % 2
Tprint("HIEven
The ET TE the user to enter an integer (line 1) and displays HiFive ifitis divisible
by 5 (lines 3-4) and HiEven if it is divisible by 2 (lines 6-7).
Python if-else statement
Aone-way if statement takes an action if the specified condition is True. If the condition is False,
nothing is done. Assuming, there is need to take one or more alternative actions when the
condition is False. A two-way if-else statement can be utilized, The actions that a two-way if-else
statement specifies differ based on whether the condition is True or False.The syntax for a two-
way if-else statement is shown below:
if (condition):
statement(s)-for-the-true-case
else:
statement(s)-for-the-false-case
Ifthe condition evaluates to True, the statement(s) for the true case are executed; otherwise, the
slatement(s) for the false case are executed, For example, consider the following code:
radiusCirele.py
Wradius 5
area = radius * radius * math.pi
print(“The area for the circle of radius
else:
Print(“Negative Input")
", radius, “is", area)
Ifradius >= 0 is true, area Is computed and displayed; If It is false, the message
Negative input is displayed.
Here is another example: Write 4 python program using If,,.Else statement to find the factorial of
number provided by the uscr-
et 8 HRThe factorial of a numbe,
of 6 (denoted as 61) j
NE Brodct of gl the integers from 1 to that number, For example, the factorial
of zero is one, 0!
5°6 = 799 Factorial is not defined for negative numbers and the factorial
4 Python program to find
gchange the value for a qj
num=7
auncomment to take input from
gnum = int(input("Enter a numbers na
factorial = 1 "
a check if the number is negative
tou 205 Positive or zero
print("Sorry, factorial does not exist for negative numbers”)
elif num == 0:
print("The factorial of O is 1")
else:
fori in range(1,num + 1):
factorial = factorial*i
print{"The factorial of",
the factor, Ib
er
itera of a num
‘Mt result
num, "is" factorial)
Nested if and Multi-Way if-elif-else Statements
One if statement can be placed inside another if statement to form a nested if statement. The
statement in an if or if-else statement can be any legal Python statement, including another if or if-
else statement. The inner if statement is said to be nested inside the outer if statement, The inner
ifstatement can contain another if statement; in fact, there is no Timit to the depth of the nesting.
For example, the following is a nested if statement:
ifi>k:
ifj>k:
print("
else:
Print("i is less than or equal to k")
and jare greater than k")
The it j> k statement is nested inside the if 1> k statement, The nested if statement can be used
to implement multiple alternatives. For example, the statement below assigns a letter value to the
Variable grade according to the score.
8ifscore >= 90.0;
grade ‘AY If score >= 90.0;
else: grade ='A'
i'score >= 80,0: elif score >= 80.0:
grade =
elif scor
grade =
elif score
grade ='D'
else:
grade =
better format
multiple
alternatives is
shown in the
second figure
using a multi-
if-elif-else statement.
Example: Body mass index (BMI) is a measure of health based on weight. It can be calculated
by king your weight in kilograms and dividing it by the square of your height in meters. The
interpretation of BMI for people 16 years and older is as follows:
BMI Interpretation
Below 18.5 | Underweight
18.5-24.9 __| Normal
25.0-29.9 Overweight
Above 30.0 Obese
Using nested if statement, write a program thal prompts the user to enter a weight in pounds and
height in inches and then displays the BMI. Note that one pound is 0.45359237 kilograms and one
inch is 0.0254 meters.
body\Weight.py
4 Prompt the user to enter weight in pounds
weight = eval{input( "Enter weight in pounds: "))
# Prompt the user to enter height in inches
height = eval{input{"Enter height in inches: "))
KILOGRAMS_PER_POUND = 0.45359237
METERS_PER_INCH = 0.0254
4 Compute BMI
Weightinkilograms = weight * ravoaRAMe.Pen POUND
heightinMeters = height * MeTERS_PER. T * heightinMeters)
bmi = weightinkilograms / (heightinMete ers)
etg pisplay result
rint("BM1 is", for .
i 18s em "amy
print("Underweight")
lif bmi < 25:
print(’Normal")
elifbmi < 30:
print("Overweight")
else:
print("Obese")
Python Loops
Aloop is 4 construct that controls the repeated execution of a block of statements. Python provides
two types of loop statements: while loops and for loops.
The while Loop
Awhile loop executes statements Tepeatedly as long as a condition remains true. The syntax for
the while loop is:
while cexpression>:
# Loop body
Statement(s)
When a while loop is encountered, the expression is evaluated. If it is true, the loop body is
executed. Then is checked again, and if still tue, the body is executed again, This
continues until becomes false, at which point program execution proceeds to the first
statement after the loop body.
Suppose we are to display a string (¢.8. Programming is fun!) 100 times. It would be tedious to
ype the statement 100 times:
Print("Programming is fun!")
Print("Programming is fun!")
Print("Programming is fun!")
(rol how many times in succession an operation (or a
Pyth construct to contr y ‘ mt
am uses the powerful erformed. By using loop statements, [tis no longer necessary to write
s aa ie of operations) ne dd times; the code below can be used to display the string in a specified
Statement a hun Hi written as VS!
numberof times, The loop statement cat P& follows:
count =o.
While count < 100:
_ ee("Program
print ming Is fun
count = count +1 fun")
gsample: The problem ig
program thal randomly gen’, 8458 what number a computer has in mind. You are to white &
sompts the user to enter ny “rates an integer between O and 100, inclusive. The program should
foreach user input, the fem TS continuously until it matches the randomly generated number.
the user can choose the next inp tould reports whether the number is too low or too high, so that
intelligently.
guessNumber.py
jImport random
2
3# Generate a random numbe
number = random.randint(o, to be guessed
100)
5
6 print("Guess a magic number between 0 and 100")
7
pguess=-2
g while guess != number.
10 # Prompt the user to guess the number
31 guess = eval(input("Enter your guess; "))
12
13if guess == number:
14print("Yes, the number is", number)
15 elif guess > number:
16 print("Your guess is too high")
else:
18 print("Your guess is too low")
The program generates the magic number in line 4 and prompts the user to enter a guess
continuously in a loop (lines 9-18). For each guess, the program determines whether the user's.
h, or too low (lines 13-18). When the guess is correct, the program ©:
umber is correct, 100 hig i mt guess isc
the loop (line 9), Note that guess is initialized to-1. Ths sto avoid iitlizing it toa value between
Oand 100, because that could be the number to be guessed.
Nested While Loop
i=.
print" * 50
while i< 11:
nel
while n <= 10:
print “%4d" % (i * n),
n
pring
ise
print ".The Python for Loop
Python for loop itera
a tes thy
S esthe 01
james the loop body needs ig he L8H each value in a sequence Ofien you know exactly how many
‘ble can be used to count the executions.
Aloop of this type is called gg X°euted, so a control varia .
“ al, the syntax of for loop is:
. Ounter-controlled loop. In gener:
for var in sequence:
# Loop body
sequence holds multiple items of data, +
fored one after the other.
example: A Python progr: | |
given by a user. Bram that uses for Joop to display the multiplication table any number
souree Code
Mullt1.py
1gPython program to find the #multiptication table (from 1 to 10)
num = 12
3# To take input from the user
4# num = int(input("Display multiplication table of? “))
5 # use for loop to iterate 10 times
6fori in range(1, 11):
7print(num, *x’, i, '=num*i)
for xin range(1, 10):
print (" {)",format(x), end="")
print()
foryin range(1, 10);
print("(:<}", format(y))
for 2 in range(1, 10, Ui
ans=y*Z
print(” {}”, format(ans), end="")
Corererere rrp th
Pere Panay 6 SO aca Cae
FUE
print("{:<}" -format(y)) .
Peseta
PLP aa
eet aoeNested For..loops
Joop can be nested ing,
ins
sanet loops. Each time thes emther loop, Nested loops
he PFOBFAM Below uses nosye COP is repeated, the inne
4 for jagps to display & multiplication able.
onsist of an outer loop: ‘and one or more
‘loops are reentered and started anew.
utiplicationTable,p
for x an range(a, Be:
print” (2".Format(x)
int) ender)
fon
for 2 in range(1, 10, ye)
aszy*?
print(” — {}"-format(ans), eng sy
Python Break and Continue statements
‘The ae statement is used to skip the rest of the code inside @ Joop for the current iteration
oi - not terminate but continues on with the next iteration while the break statement
teminates the loop containing it, Contr ofthe program flows to the staternent immediately after
the body of the loop.
Example: Write a Python program using the break statement to search for the number °88” in the
given list of numbers, 11, 9, 88, 10, 90, 3, 19. The program is to display all the numbers till the
umber '88" is found and when itis found, the loop should be terminated and rest of the numbers
should not be displayed.
searchNum.py
1# program to display all the element:
2for num in [11, 9, 88, 10, 90, 3, 19]:
3 print(num)
4 if{num==88):
S print("The number 88 is found")
6 print{"Terminating the loop")
Tbreak
s before number 88
Example: The program that uses the continue statement to skip letter ¢ in the word string and
x : The
then print the output.
letterNum.py
14 Program to show the Use
2for val in "string":
3 If val
eee
of continue statement Inside loops
{ ee _———_4 continue
5 print(val)
gprint("The end")
part 6: Input ana °O
Aquming You Rave
ie is ee tro
keyboard Mis Possible to stope® WO enter, Tt woud be tedious (0 type all the entries trom
ty using the following command” data in a text file (input.txt, for example) and run the program
python SentinelVatuespy « inn
y Ut txt
This command is called jp,
jeyboard at runtime, the pr PUC Fedircetion, Instead of having the user type the data from the
° :
BAM lakes the input from the file input.txt.
similarly, output redirecti
The command for output redirect the output to a file instead of displaying it on the sereen.
Nis:
python Script.py > output.txt
ut and output redirecti i
tpt a out u redirection can be used in the same command. For example, the following
oo Sets input from input.txt and sends output to output.txt:
python SentinelValue.py output.txt
Part 7: Function in Python
pe
A Function in Python are used to utilize the code in more than one place in a program, sometimes
also called method or procedures. Python provides you many inbuilt functions like print().A.
function is a block of organized, reusable code that is used to perform a single, related action.
Functions provide better modularity for your application and a high degree of code reusing.
Python gives you many built-in functions like print(), etc. but it also gives you freedom to create
your own functions which are called user-defined functions
Ex P «og you are to find the sum of integers from 1 to 10, 20 to 37, and 35 to 49. To
eestor ire these three sets of numbers, the code might look like this:
sum =0
for iin range(1, 11):
sum +=
print("Sum fram 1 to 10/5", sum)
sum=0
for iin range(20, 38):
sum += j
et }Rpit("SUM from 20%9 59,
so
range(35, 50);
gmszi
"sum from 3
printl S to 49 jg
sum)
snstead of repeating the co
’ my i Pan 1 z,
commonly used code oneg ean to add these numbers as shown above, it is possible to write
cnables US 10 create reusatje Wen reuse it. This can be done by defining a function, which
functions, as follows: Code. For example, the preceding code can be simplified by using
def sum(it, 1
zresult = 0
3for iin range(it, 12 + 1):
gresult += 7
5
greturn result
7
8def main():
gprint("Sum from 4 to 10s", sum(1,20))
10print("Sum from 20 to 37 is", sum(20, 37))
11 print("Sum from 35 to 49 is", sum(35, 49))
2
13 main() # Call the main function
Lines 1-6 define the function named sum with the wo parameters il and i2. Lines 8-11 define
the main function that invokes sum(1, 10) to compute the sum from 1 to 10, sum(20, 37) to
compute the sum from 20 to 37, and sum(35, 49) to compute the sum from 35 to 49.
How to Define a Function in Python
‘A function definition consists of the function's name, parameters, and body.
The syntax for defining a function is #s follows:
def functionName(list of parameters)
numbers is bigger. We can create a function, named max that has
Example: To find which of 80 OM seger of which is returned by the function.
two parameters, mum} and num
def max(numt, eum?) .
ifnumt > num2! smati'y}
enumt
result =num a
else: vs pram
result = num?
return result
a
etAfunction contains h
fynction’s nam der
om 2 parame Pa tens beds The header beens with the def keyword, fllosed by he
tssed 10 the param Paramect” ends witha colon. The variables in the function header are
optional; that i eter. This yay, 8 like a placeholder: When a function is invoked, a value is
art oP ae ma tS funetion mee i Feferred to as an actual parameter or argument, Parameters
function pes Ho) Parameters '8Y not have any parameters. For example, the random.random()
operations without retumnin. ™ fimations return a value, while other functions perform desired
jnction. The function body's. ue. If a function returns a value, itis ealled a value
For example, the fiction bods acollection of statements that define what the function does.
number is larger and return the v0! the max function uses an if statement to determine which
igrequired for a Value-retutnin Value of that number, A return statement using the keyword return
ck Ng Func :
satement is executed. 8 function to return a result. The function terminates when a return
How to Call a Function in Pyth
ion
function must be called or pe wins the code in the function. To use any Function defined, the
ornot itretns a value fy ked. There are tivo ways to call a function, depending on whether
swale Forename function returns a value, a call to that function is usually treated as
larger = max(3, 4)
alls max(3, 4) and assigns the result of the function to the variable larger.
Another example of 2 call that is treated as a value is
print(max(3, 4) which
prints the return value of the function call max(3, 4).
fa function does not return a value, the call to the function must be a statement. For exemple,
the print function does not return a value, The following call is a statement:
rint("Programming Is fun!")
Example: A complete programto find which of two numbers is bigger.
TestMax.py
14 Return the max of two numbers
2 def max(numi, num2):
if num > num2:
4 result = numt
5 else:
Sresult = num2
LEH 22 }#qT
greturn result
‘i def main():
y ie5
y iF
3 k= maxli, j) # can y
y4 print("The larger mee maK ‘unction
rs FOP |, and”, j, "is", k)
sgmain() # Call the main function
The Scope of Variables ;
The scope of a variable is the . tn Python
iseusses the scope of variab| i Of the program where the variable can be referenced. This section
fered to as a local variable ae the Context of functions. A variable created inside a function is
sfalocal variable starts from ite cal variables can only be accessed within a function. The scope
variable. In Python, you ean a} Creation and continues to the end of the function that contains the
‘accessible to all tunes: also Use global variables. They are created outside alll functions and
ae ‘unctions in their scope. Consider the following examples.
iglobalVar = 1
2def f1():
3 localVar = 2
4 print(globalVar)
5 print(localVar)
6
7A)
8 print(globalVar)
Sprint(localVar) # Out of scope, $0 this gives an error
. afi It is accessed within the function in line 4 and outside the
saci eated in line 1. eee 3 a ea ae
A dlobat variable is ee | variable is created in line 3. It is accessed within the function in line 5.
Pee line 8. A ca ie from outside of the function causes an error in line 9.
lempting to access the
Example 2
lesa
2def F211);
3 x=2
7 print(x) # Displays 2
Shay)
7 print(x) # Displays 2pere a global Variat Ie ys
in ine ren this Por is g ated
function, the global Variat OF, the pfitine 1 and a local variable with the same name (x) is ereatted
Able x ig Global variable x is not accessible in the function, Outside the
“ill accessible. So, it prints 1 in line 7.
st can STORET
Ore TCoTD
values. Suppose, ive nt
A
of
way
; He to reaq any SUE. PROGFANTS COMMONS Teed To MOTE a TEE TUMEGT
amany OF the numbers gpa’! read : 7
A re 00 numbers, comput verage, i ’
ii erage, then go? Shove numbers, compute their average, and then find out how
i AES eagy © erage. the program first reads the numbers and computes
swage. In order to ac lige’ ber With the average to determine whether itis above the
ve will create 100 yar, this tsk, the numbers must all be stored in variables, To do thie,
progam this Way is imprae |, qcheatedly write almost identical code 100 times, Writing a
type called alist which stopega't 8 efficien, organized approach is needed, Python provides ¢
the 100 numbers in a list ang °@¥*Mtal collection of elements. In this example, we ean store all
example Will 1OOk like this: “°®CSS them through a single list variable. The solution to this
DataAnalysis.py
1NUMBER_OF_ELEMENTS -
2 Create an empty Ten TS" 5 For simplicity use 5 instead of 100
3sum=0
4
Sfor jim range(NUMBER_OF.
4 ELEMENTS):
Svalue = evallinput("Enter anew number: "))
7
8sum += value
3
10 average = sum / NUMBER_OF_ELEMENTS
u
12 count = 0 # The number of elements above average
13 foriin range(NUMBER_OF_ELEMENTS);
14 If numbers[i] > average:
IS count +=1
16
17 print("Average is", average) bh
‘Number of elements above the average Is", count)
List as a Sequence TYE pes in Fybon. A string is a sequence of characters, while a st
jeune and lis bee cients ine common operations for sequences are summarized below,
sequence of any clements.
Common Operations for Sequence
a iption
Operation DeserPement x Is in sequence s,
xins Tevet
if elernent is not in sequence s,
Xnotins
— #Rcq
neattlenates two sequences st and s2
gil ith a of sequence s concatenated.
jen) Slice sa" in sequences,
yin(s) ‘sequence s from index itoj- 1.
masts) $inuth of sequences, i. the numberof elements ins.
© (8) ullest clement in sequence s.
orioop g TBEH element in sequence s.
Tray ot all sumbers in sequence s.
Faverses elements {tom left to right in a for loop.
Mpares two sequences.
GP
Functions for Lists
some Python built-in funct
: n function; ‘
qumber of elements in the lst yeu be used with lists. The len function can be used to return the
grctest and lowest values jn ima Max/min functions can be used to retum the elements with the
jist. The shuffle functio, 7
Fin lst and the sum function to return the sum of all elements in the
u
thelist. Here are some cxampeetttom module can be used to shuffle the elements randomly in
19> list = [2, 3, 4, 1, 32]
2>22 lenllista)
35
4 >>> max(list)
532
6 >>> min(list2}
71
B>>> sumflist1)
942
10>>> import random
11>>> random.shuffle(list1) # Shuffle the elements in list
12 >> list
134, 1,2, 32,3)
Id>>>
List Slicing (start : end]
‘The index operator allows us to select an element at the specified index. The sticing operator
revue a slice of the list using the syn'ax list[start : end). The slice is a sublist from index start
to index end ~ 1. Here are some examples:
slicing operator
>>> list) = [2, 3, 5,7, 9, 1]
Qove list12: 4]
3{5,71
4>27
selection Sorting in Listgyppose We Want
ssupP° ‘sonar
ppelistand swaps iy with 4 list in
with the first cleme, ie
following figure sho
" ist Ascending order. A selection sort finds the smallest element
Tt in the pa, Ist{j):
40 currentMin = Ist{j]
itcurrentMinindex = j
12
138 Swap Ist[i] with Ist(currentmi
14if currentMinindex
15 Ist[currentMinindex] = Ist{i]
16 |Ist[i] = currentMin
inindex] if necessary
The selectionSort(Ist) function sons any list of elements. The function is implemented with a
ested for loop. The outer loop (with the loop control variable i) (line 3) is iterated in order to find
the smallest element in the list, which ranges from Ist[i] to Ist[len(Ist)-I[, and exchanges it with
ti. The variable i is initially 0. After each iteration of the outer loop, Ist[i] is in the right place.
Eventually, all the elements are put in the right place: therefore, the whole list is sorted.
Part 9; Multidimensional Lists
. wo-dimensional list. A two-dimensional list is a list
. an be stored in at onal
Datain a table or a matrix OM ys, The preceding section introduced how to use alist to store
i contains other kiss a Jist can be used to store two-dimensional data, such as a matrix
linear collections of elements:
ora table.
‘ jists
mensional us accessed through a row and column index.
Pr i -Dit
‘ocessing Two-Di a liste
Avvalue in a two-dimensi
ues
ut Ae ‘vith user input values:
a
hitializing Lists with
The following loop initia
sty lst
Matrix = [] # Create an e™PYYper0'ROWS = EVAILINBUL"ENter the number of rows! ")
a mns =
tt gOICOIUMNS = evallinputrm
ber PUL("Eny =
ha cangetnumberOtmon eer the number of columns: ")
(0 f
xappendi(]) # Add an empty new ew
vaune in range(numberOfColumng)
zevallinput("Enter an element».
oon Pen dlvatue) nt and press Enter: "))
este)
peiatizing Lists with Random Values
jiefollowing loop initializes alist that stores random values between O and 99:
inport random
exis [] # Create an empty list
pumberOfRows = evallinput{"Enter the number of rows: ")
numberofColumns = eval(input("Enter the number of columt
fprrow in range(numberOfRows):
ratrixappend([}) # Add an empty new row
feecolumn in range(numberOfColumns):
ratri(row].append(random.randint(0, 99))
print{matrix)
Printing Lists
Toprint a two-dimensional list, print cach clement in the list by using a loop like the following:
matric= ([1, 2, 3], [4, 5, 6), (7, 8, 9] # Assume a list is given
fortow in matrix:
forvalue in row:
rrint(value, end =")
Hint) # Print a new line
o
‘atic [[1, 2, 3], [4, 5, 6), (7, 8, $I] # Assume a list is given
"row in range(len(matrix)):
‘orcolumn in range(len(matrix[row]}):
Fntimatrix{row)[column], end
Fin) 4 Print a new line
Sumi
ming Ele Column ;
Fe each alia ioe able named total to store its sum. Add each element in the column to
‘Vsing a loop like this:
"ies [2 2,3) 4, 5, 6), [7, 8, 9] Assume a lists given
Es | 27 ajumn in range
tr i Bt emtmatiaony,
wefow In range(len(ma
Hal+= matrix[rowlf co
('sum for column
trix):
umn]
+ Column, mign
finding pew With the Larg
‘o find the Tow With the larpec est Sum
Psck the largest sum anfan ‘Sum, you may use the variables maxRow and indexOfMaxRow
pasRow arid IndexOPMaxpyy w°% Of the row. For each row, compute its sum and update
Y if the new sum is greater.
oe
pei
total)
trix = [[, 2, 3], (4, 5, 6),
ronROW = summatrvi ree Assimme a list is given
indexO[MaxRow = 0 Of the first row in maxRow
for row in range(1, len(matrix)):
ifsum(matrix{row]) > maxRow:
maxRow = sum(matrix{row])
indexOfMaxRow = row
print("Row", indexOfMaxRow, "has the maximum sum of", maxRow)
Example: Assuming there are eight numbers of students and ten different questions, and the
answers (0 the questions are stored in a two dimensional list. Each row records a student's answers
to the questions, as shown in the following illustration. Write a Python program to grade the test
based on the key to questions and then display the result.
0123456789
‘Student 0 ABACCDEEAD
Student 1 DBABCAEEAD
Student2 EDDACBEEAD
Student 3 CBAEDCEEAD
Student 4 ABDCCDEEAD
Student 5 BBECCDEEAD
Student 6 BBACCDEEAD
Student? EBECCDEEA
Key to the Questions:
0123456789
DBDCCDAEAD
GradeExam.py
' def main():
24 Students’ answers to the aU
Sonswers =
estions
ao[CB *A', "EY 1p,
5 [EY "D', "Di, "A" 4 'C'"E, 8141, ‘D',
9 ‘A, Cc, ‘Be Ee tee ae
0 EDS TBA BSC) rar pee AS Dh
PAS "BY TANI, CDS pe ‘BY "AY, 'D'),
i EAC DT,
2
13 # Key to the questions
weys=['D' "BY 'D','C'C Da 1B, 4,04]
5
16# Grade all answers
17 fori in range(len(answers) ):
18 # Grade one student
19 correctCount = 0
x) for j in range(len(answers[i)) ):
al if answers|i][j] == keysfi]:
2 correctCount += I
3B
4 print("'Student", i, "'s correct count is", correctCount)
35
26 main() # Call the main functionsignment:
s¢ YOU ATE to dey,
sid randomly generate? * Progra, . .
iber2 and asks the ES Ug sin 'M for a pry one pupil to practice subtraction. The program
samoram should diene! a quegte igi integers, number! and number2, with numbert >=
wee splays a te 'Stion such as "What is 9-2?" After the pupil enters the answer,
'SSage indicating whether the answer is correct.
g
thot:
yep 1: Generate two sin,
; edit
gp 2: number