Chapter 2-Program Elements
Chapter 2-Program Elements
1 Introduction
As we mentioned in Chapter 1, python program is made up of several elements. We mentioned some of
these elements in Chapter 1 like variables and literals.
R
1.1 Statements
Definition 1. A python statement is any line of code that can be executed by the interpreter.
Python requires that every line of code contain a single statement as shown in code below
U
1 radius = 9
2 area = 3.142 ∗ radius ∗ radius
3 print( ’Radius =’, radius, ’Area =’, area)
UL
1. Initialize the variable radius with the value 9
Note 1. We can have several statements on the same line as long as these statements are separated with
G
semicolons as shown in the code below and non of these statements starts a new block of code.
1 radius = 9; area = 3.142 ∗ radius ∗ radius ; print( ’Radius =’, radius, ’Area =’, area)
1 n = 10
2 if n >= 0:print(”Something”);if n <= 20:print(’This is an error as second if starts a new block’)
Statements in Python typically end with a new line. Python does, however, allow the use of the line
continuation character (\) to denote that the line should continue. For example
1 item 1 = 10
2 item 2 = 3
3 item 3 = 12
.
4 total = item 1 + \
5 item 2 + \
DR
6 item 3
7 print( ’Total =’, total )
note that, line 4, 5 and 6 contain a single statement that spans multiple lines.
1.2 Comments
Definition 2. A comment is a line of code that is ignored by the Python interpreter during program
execution. It is a line of code that is not executed by Python interpreter.
Note 2. It is wrong to define a comment as A program statement that is ignored by the interpreter during
program execution. Remember definition of statement and see the contradiction in this definition
contents of line 1 is what we refer to as a single line comment. You can put a single line comment
anywhere in a program, that is, you can put it on its own line as in the code above or you can still
put a comment in front of a statement.
2. Multi-line comment - It starts with triple quotation marks (double or single), spans multiple lines, and
ends with triple quotation marks. See the code below for example
R
1 ’’’ This program reads radius of a circle from
2 the keyboard as an integer, calculates and
3 print area of the circle ’’’
4
5 rad = int(input(”Enter Radius: ”))
U
6 area = 3.142 ∗ rad ∗ rad #We can still read pi from the math module
7 print( ’Radius =’, rad, ”Area =”, area)
You can notice that, line 1-3 constitute multi-line comment, I left line 4 blank just to make the code
easy to read.
UL
Python ignores blank lines and white-spaces, just as it ignores comments, during program execution.
I have inserted a single line comment after statement on line 6, just to show you how we can put
comments after a statement. I used single quotation, but you can use double quotation marks.
1. Integers (int) - Consist of whole numbers (numbers that do not have fractional parts). This type can
be used to define discrete data like number of students in a class, number of cars in a yard, number of
cups in a cupboard. You will notice that we cannot have 23456.76 people watching Pirates vs Chiefs
at Moses Mabhida stadium, this number must be a whole number because we cannot have 0.76 of a
person. We can perform arithmetic operations like addition, subtraction, multiplication, exponential
etc on ints
2. Floating point numbers (float) - Data type that is used to denote data with fractional parts. This is
data that may contain a continuous value like age, amount of fuel from a pump per unit time, radius
.
of a circle etc. Example 2.45, 0.001, 895.895, 0.0245 etc. We can perform arithmetic operations like
DR
3. Strings (str) - This type can be used to denote data that contain several characters. Strings are
enclosed either in single or double quotation marks. We can not perform arithmetic operations like
addition, subtraction, multiplication, exponential etc on strings.
Python provides a function type() that returns the data type of the value or value in the variable passed
to it. This code
1 #Function type() returns the data type of its arguement (the value/or value its passed to)
2 age = 75
3 name = ”Raf”
4 print(type(age))
5 print(type(name))
6 print(type(3.142))
1. int() - Will convert a a value from float or string to integer. For the float, the fractional part will be
truncated (cut and discarded). To convert from string to int, the string must be a valid integer value
(without alphabets nor special characters). For example, see the code below (read comments to notice
valid and invalid conversions)
R
1 #Converting from float or string to int
2
3 a = int(”734”) #Valid, this is same as a = 734
4 b = int(157.25) #Valid, this is same as b = 157
5 c = int(”672.75”) #Invalid, because of the dot, raise an error
6 d = int(”B45”) #Invalid, because of the B character, raise an error
U
2. float() - Will convert a a value from integer or string to float. For an integer, a fractional part of .0
is appended to the number. To convert from string to float, the string must be a valid floating point
1
2
3
4
a = float(”734.45”)
b = float(157)
UL
value (without alphabets nor special characters). For example, see the code below (read comments to
notice valid and invalid conversions)
#Converting from int or string to float
3. str() - Convert floating point values or integers to strings. See code below for example
AN
Note 3. Python has other data types like List, Tuple and Dictionary. We will look at some of these later
on, when you have grasped these basics, OK?
Note 4. It is important to note that, as much as we expect age to be a numerical value, the input() function
reads it in as a string. Whenever we expect numerical input from the keyboard, we must cast (convert) the
input read by the input() function to respective numerical value we expect (float or integer).
To convert input to numerical values, we use int() or float() type conversion functions. See the code below
R
that reads age and convert it to a integer, reads weight and convert it to a floating point value
1 #Read age and convert it to an integer, weight and convert to float
2
3 age = int(input(”Enter age: ”)) # If you enter 17, the statement becomes age = int(”17”) which is same as age = 17
4 weight = float(input(”Enter weight: ”)) #If you enter 45.6, statement becomes weight = float(”45.6”) which is same as
U
weight = 45.6
Look at the same code below with where we display the type of each variable after reading it and after
converting it to numerical
1
2
3
4
5
6
age = input(”Enter age: ”) #read age
print(age, ”is of type”, type(age))
age = int(age) #convert to int
print(age, ”is NOW of type”, type(age))
UL
#Read age and convert it to an integer, weight and convert to float
7
8 weight = input(”Enter weight: ”) #read weight
G
9 print(weight, ”is of type”, type(weight))
10 weight = float(weight) #convert to float
11 print(weight, ”is NOW of type”, type(weight))
12
AN
Note 5. If you enter an invalid integer (string with a dot, alphabet or special character) or an invalid float
(string with alphabet or special character), the conversion to respective type will fail and Python will raise
DR
an error.
There is another function called eval() that evaluates valid expressions entered from the keyboard. This
function can also convert user input into numerical values (int or float). See the code below for details, read
comments
1 #Read age and convert it to an integer, weight and convert to float using eval () .
2 #Read a valid expression and evaluate it too
3 age = input(”Enter age: ”) #read age
4 print(age, ”is of type”, type(age))
5 age = eval(age) #convert to int
6 print(age, ”is NOW of type”, type(age))
7
8 weight = input(”Enter weight: ”) #read weight
R
23 Enter a Valid expression: 75 − 8 ∗ 7.34 / 2 − 5
24 Value of expression is 40.64
25 ’’’
U
Python provides a function print() that displays strings, literals, variable values and values of expression on
the screen. We have seen how print is used to display information on the screen in previous example. The
line of code below displays a string Welcome to UKZN on the screen
1 print(”Welcome to UKZN”)
UL
Notice that, the quotation marks around the screen are not displayed. For this case, we just passed a single
string literal to the function.
We can pass more than one arguments to this function by separating them with commas as in the
example below
G
1 name = ”Raph”
2 age = 86
3 print(”Your name is”, name, ”and Age is”, age)
4
’’’ OUTPUT
AN
5
6 Your name is Raph and Age is 86
7 ’’’
Notice that, there is a single white space between is and Raph, between Raph and and and between is and
86.
Python will insert a space between each of the arguments of the print function. There is an optional
argument called sep, short for separator, that you can use to change that space to something else. For
example, using sep=’:’ would separate the arguments by a colon and sep=’##’ would separate the arguments
by two pound signs.
.
The print() has an optional argument sep (for separator) which substitutes every comma with a single
DR
white space character. You can change the separator from single white space character by definition the
separator as
1 name = ”Raph”
2 age = 86
3 print(”Your name is”, name, ”and Age is”, age, sep = ’−’) #default definition of sep is sep = ’ ’
4
5 ’’’ OUTPUT
6 Your name is−Raph−and Age is−86
7 ’’’
There is an optional argument called end that you can use to keep the print function from advancing to
the next line. Here is an example:
1 print( ’Line one’, end = ’ ’ ) #default definition of end is end = ’\n’
2 print( ’Line two’)
3
R
4 ’’’ OUTPUT
5 Line one Line two
6 ’’’
We can also pass variables and expressions to print() as shown below (We can also pass function calls
to print() as print(type(2)), and as we will see more examples in this module). See sample code below
U
to see how we can pass variable and expressions to this function
1 n = 10
2 print( ’n =’, n, ’n squared =’, n ∗ n) #n is a variable and n ∗ n is an expression.
3 #They can be any other valid expression like 4 ∗ 5 − 9 // 2 etc
1.6 Operators UL
An operator is a symbol that signify some kind of operation (processing) to be performed on data. We have
arithmetic operators, relational operators, assignment operator and logical operators
G
1.6.1 Arithmetic operators
They specify some kind of arithmetic operation to be performed on data. Table 1 show a list of arithmetic
operators, there meaning and a sample operation on data.
AN
% Modulus 5%2 = 1
DR
∗∗ Exponential 52 = 25
R
2 n = 10
The assignment operator can be combined with arithmetic operators as shown in Table 3. Assume the
variable n initially has the value 3 See code below for sample output of the operations listed in Table 3
U
Operator Symbol Meaning Sample Operation In Full is
+= Add and assign n += n→ n = 6 n=n+n
-= Subtract and assign n -= n→ n = 0 n=n-n
*=
/=
//=
%=
**=
UL
Multiply and assign
Divide and assign
Divide and assign
Modulus and assign
Exponent and assign
n *= n→ n = 9
n /= n→ n = 1.0
n //= n→ n = 1
n %= n→ n = 0
n **= n→ n = 27
n=n*n
n=n/n
n = n // n
n=n%n
n = n ** n
G
1 #Read as n takes the value 10. OR 10 is assigned to variable n
2 n=3
3 n += n
4 print( ’n += n is ’,n)
AN
5 n = 3 #remember n now has value 6, am re−assigning before doing next operation for purposes of undesranding
6 n −= n
7 print( ’n −= n is ’,n)
8 n=3
9 n ∗= n
10 print( ’n ∗= n is ’ ,n)
11 n=3
12 n /= n
13 print( ’n /= n is ’ ,n)
14 n=3
.
15 n //= n
16 print( ’n //= n is ’ ,n)
DR
17 n=3
18 n %= n
19 print( ’n %= n is ’,n)
20 n=3
21 n ∗∗= n
22 print( ’n ∗∗= n is ’ ,n)
23
24 ’’’ −−−−−−−OUTPUT−−−−−−
25 n += n is 6
26 n −= n is 0
27 n ∗= n is 9
28 n /= n is 1.0
29 n //= n is 1
30 n %= n is 0
31 n ∗∗= n is 27
1. and – Checks two logical conditions and return True if both conditions are true, otherwise returns
False
Table 4: Logical and operations
R
Condition 1 Condition 2 Output
True True True
True False False
False True False
False False False
U
2. or – Checks two logical conditions and return True if both any of the conditions is true, otherwise
returns False
Condition 1
True
Condition 2
True
Output
True
True False True
False True True
G
False False False
3. not – Checks a logical condition and return True if the condition is False and return False if the
AN
condition is True
Table 6: Logical not operations
Condition Output
True False
False True
.
We will see how to use logical and relation operators in the selection topic.
DR
1. in - Evaluates to True if it finds a variable in the specified sequence and False otherwise.
2. not in - Evaluates to True if it does not finds a variable in the specified sequence and False otherwise.
1. is - Evaluates to True if the variables on either side of the operator point to the same object and False
otherwise.
2. is not - Evaluates to False if the variables on either side of the operator point to the same object and
True otherwise.
R
executed before others. This is almost similar to the BODMAS rule we did in grade 5, I hope you remember
it. In programming, we refer to such order of operation as precedence rules of operators.
Operators with highest precedence will be executed first, followed by operators with lower precedence.
Table 7 show precedence of operators starting with operators with highest precedence to ones with lowest
precedence. Operators with the same precedence are evaluated from left to right. See the code below, try
U
Table 7: Logical not operations
4 print( ’p =’, n)
5 n = 9 − 2 + 2 ∗ 6 // 5 − (3 % 2) ∗∗ 3 #see effect of putting these parantheses
6 print( ’z =’, n)
7
8 ’’’ −−−−−−−−−OUTPUT−−−−−−−−−−−−−−−
9 n=6
10 n=2
11 n=8
12 −−−−−−−−−−END−−−−−−−−−−−−−−−−’’’
.
1. Syntax error - This occurs when you fail to observe rules of a particular programming language. For
example putting an expression on the left of an assignment operator like in the code below
1 radius = int(input(”Enter radius: ”))
2 3.142 ∗ radius ∗ radius = area
3 print( ’Radius =’, radius, ’Area =’, area)
4
5 ’’’ −−−−−−−−−−OUTPUT−−−−−−−−−−−−−
6 Enter radius: 6
7 Traceback (most recent call last ) :
8 File syntax.py”, line 2, in <module>
9 3.142 ∗ radius ∗ radius = area
2. Runtime error - Occur occur when an invalid or illegal statement is encountered during program
execution. For example using a variable that is not initialized as in the code below
1 n = 10
2 z =n/d
3 print(”n =”, n, ”d =”, d, ”z =”, z)
4
5 ’’’ −−−−−−−−−−−−−−−−OUTPUT−−−−−−−−−−−−−−−−−−
6 Traceback (most recent call last ) :
R
7 File runtime.py”, line 2, in <module>
8 z =n/d
9 builtins .NameError: name ’d’ is not defined
10 ’’’
U
3. Logical error - This error occur when you use a wrong algorithm (procedure) to solve a problem.
For example calculating area of a circle using the formula area = π + radius + radius instead of
area = π ∗ radius ∗ radius as in the code below
1
2
3
4
5
UL
radius = int(input(”Enter radius: ”))
area = 3.142 + radius + radius #wrong algorithm used here. Correct formula is area = 3.142 ∗ radius ∗ radius
print( ’Radius =’, radius, ’Area =’, area) #with radius 7, correct area is 153.958 NOT 17.142
’’’ −−−−−−−−−−OUTPUT−−−−−−−−−−−−−
6 Enter radius: 7
7 Radius = 7 Area = 17.142
G
8 ’’’
This error does not stops your program from executing, but you will get wrong results.
AN
Tutorial questions
1. Define the following terms as used in Python programming [13 Marks]
(f) Statement
(g) Variable
(h) Expression
(i) Block of code
(j) Comment
(k) Compiler, interpreter, debugger
3. Write a Python program that reads radius of a circle from the user as an integer, calculate and display
area and circumference of the circle. [3 Marks ]
(a) n = 12 - 2 + 4 * 7 // 9 - 5 % 4 ** 2
(b) n = 7 - (4 - 2) * 9 / 2 - 7 % 2 ** 3
(c) n = 69 + 2 - 5 * 6 // 5 - (8 % 3) ** 3
R
6. With examples, explain three types of errors commonly committed by Python programmers[6 Marks]
7. What is the type of data contained in the variable n after execution of each line in the code below [3
Marks]
1 n = ’472.125’
U
2 type(n)
3 float (n)
4 int (n)
UL
8. State four rules that variable names must adhere to in Python [4 Marks]
G
. AN
DR