0% found this document useful (0 votes)
27 views

Chapter 2-Program Elements

Uploaded by

Aningu Wayne
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Chapter 2-Program Elements

Uploaded by

Aningu Wayne
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

School of Computing and Informatics

BCS 360 Interactive Programming


Program Elements in Python

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)

this code contains three statements

UL
1. Initialize the variable radius with the value 9

2. Calculate area of a circle and initialize the variable area

3. Displays the radius and area to the screen

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)

For instance, the code below will generate an error


AN

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

There are two types of comments in Python

Dr. Raphael Angulu, BCS 360 SCI, MMUST, 2020: Basics 1


1. Single line comment - It starts with a # character and spans a single line as shown in code below
1 #Program to calculate area of a rectangle
2 l = 10
3 w=5
4 area = l ∗ w
5 print(”Length=”, l, ”Width=”, 5, ”Area =”, area)

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.3 Data types


G
Definition 3. Data type (typing) is classification of data based on its possible values, possible operations
and memory requirements. Python has got three basic data types
AN

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

addition, subtraction, multiplication, exponential etc on floats

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

Dr. Raphael Angulu, BCS 360 SCI, MMUST, 2020: Basics 2


will display < class 0 int0 >, < class 0 str0 > and < class 0 f loat0 >. This denotes that, age is type int,
name is type str and 3.142 is type float.

1.3.1 Type casting


Type casting is converting from one data type to another. We can convert from any data type to another
using respective functions

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

#Valid, this is same as a = 734.45


#Valid, this is same as b = 157.0
5 c = float(”B45”) #Invalid, because of the B character, raise an error
G
6 print(”a =”, a)
7 print(”b =”, b)

3. str() - Convert floating point values or integers to strings. See code below for example
AN

1 #Converting from int or string to float


2
3 a = str(734.45) #Valid, this is same as a = ”734.45”
4 b = str(157) #Valid, this is same as b = ”157”
5 print(”a =”, a, ”Type =”, type(a)) #Have used type() function to display the datatype of a and b
6 print(”b =”, b, ”Type =”, type(b)) #Notice that the data type is now str
7
8 ’’’ This is what will be displayed by this code
9 a = 734.45 Type = <class ’str’>
10 b = 157 Type = <class ’str’>
.

11 Notice datatype for a and b has changed to str ’’’


DR

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?

1.4 Reading input from keyboard


Python provides a function input() that reads input as a string from the keyboard. This function display
a string passed to it as prompt to the user. This makes our program interactive, neh!. See the code below
that reads an input from the keyboard and store it in a variable named name and another one in variable
age
1 #Read name from the keyboard
2 name = input(”Enter name: ”)
3 age = input(”Enter age: ”)

Dr. Raphael Angulu, BCS 360 SCI, MMUST, 2020: Basics 3


When this program is executed, it displays the string Enter name: After entering some input from the
keyboard and pressing enter, it displays the second prompt to the user Enter age: If you enter Raph and
75 respectively, the two input statements decompose to
1 #Read name from the keyboard
2 name = ”Raph”
3 age = ”75”

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

13 ’’’ If we enter age as 12 and weight as 45,


14 OUTPUT Will be
15 Enter age: 12
16 12 is of type <class ’ str’>
17 12 is NOW of type <class ’int’>
18 Enter weight: 45
19 45 is of type <class ’ str’>
20 45.0 is NOW of type <class ’float’>
21 ’’’
.

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

Dr. Raphael Angulu, BCS 360 SCI, MMUST, 2020: Basics 4


9 print(weight, ”is of type”, type(weight))
10 weight = eval(weight) #convert to float
11 print(weight, ”is NOW of type”, type(weight))
12
13 v = eval(input(”Enter a Valid expression: ”)) #read an expression and evaluate it
14 print(”Value of expression is ”, v)
15 ’’’ If we enter age as 12 and weight as 45.8, and expression as 75 − 8 ∗ 7.34 / 2 − 5
16 OUTPUT Will be
17 Enter age: 12
18 12 is of type <class ’ str’>
19 12 is NOW of type <class ’int’>
20 Enter weight: 45.8
21 45.8 is of type <class ’ str’>
22 45.8 is NOW of type <class ’float’>

R
23 Enter a Valid expression: 75 − 8 ∗ 7.34 / 2 − 5
24 Value of expression is 40.64
25 ’’’

1.5 Writing output on the screen

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

You can see the separator has been defined as an hyphen.


The print function will automatically advance to the next line. For instance, the following will print on
two lines:

Dr. Raphael Angulu, BCS 360 SCI, MMUST, 2020: Basics 5


1 print( ’Line one’)
2 print( ’Line two’)
3
4 ’’’ OUTPUT
5 Line one
6 Line two
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

Table 1: Arithmetic operators in Python

Operator Symbol Meaning Sample Operation


+ Addition 5+2=2
− Subtraction 5−2=3
∗ Multiplication 5 ∗ 2 = 10
/ Floating point division 5/2 = 2.5
// Integer division 5//2 = 2
.

% Modulus 5%2 = 1
DR

∗∗ Exponential 52 = 25

1.6.2 Relational operators


They are used for comparison. They compare two values and return True or False Table 2 show relational
operators, there meaning and sample operation.

1.6.3 Assignment Operator


The symbol for assignment operator is =. This operator is used to assign/give values to variables. See the
line of code below, read the comment to understand what this line of code does

Dr. Raphael Angulu, BCS 360 SCI, MMUST, 2020: Basics 6


Table 2: Relational operators in Python

Operator Symbol Meaning Sample Operation


== Equality 5 == 2 → False
> Greater than 5 > 2 → True
>= Greater than or equal to 5 >= 2 → True
< Less than 5 < 2 → False
<= Less than or equal to 5 <= 2 → False
!= Not equal to 5 != 2 → True

1 #Read as n takes the value 10. OR 10 is assigned to variable n

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

Table 3: Combined assignment operator

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

Dr. Raphael Angulu, BCS 360 SCI, MMUST, 2020: Basics 7


32 ’’’

1.6.4 Logical operators


Logical operators combine two or more conditions and return True or False. Python provides three logical
operators.

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

ULTable 5: Logical or operations

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.6.5 Membership operators


Python provides two membership operators

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.

We will see how to use these operators in our subsequent topics.

Dr. Raphael Angulu, BCS 360 SCI, MMUST, 2020: Basics 8


1.6.6 Identity operators
Python provides two identity operators used to compare the memory locations of two objects.

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.

1.6.7 Precedence rules of operators


If all operators appear in an equation, Python provides some precedence that allows some operators to be

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

Precedence Operator Name Evaluated from


1
2
3
4
5
UL ()
**
*, /, //, %
+, -
=
Parentheses
Exponential
Multiplicative
Additive
Assignment
Right-to-left
Left-to-Right
Left-to-right
Right-to-Left
G
to solve these expressions by hand and see if you get the same results.
1 n = 9 − 2 + 2 ∗ 6 // 5 − 3 % 2 ∗∗ 3
2 print( ’n =’, n)
3 n = 9 − (2+ 2) ∗ 6 // 5 − 3 % 2 ∗∗ 3 #see effect of putting these parantheses
AN

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.7 Types of errors in Python


DR

There are three types of errors that can occur in Python

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

Dr. Raphael Angulu, BCS 360 SCI, MMUST, 2020: Basics 9


10 Syntax Error: can’t assign to operator: <string>, line 2, pos 0
11 ’’’

This error stops your program from executing.

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

This error stops your program from executing.

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]

(a) Source code


(b) Object code
(c) High level language
(d) Low level language
.

(e) Machine language


DR

(f) Statement
(g) Variable
(h) Expression
(i) Block of code
(j) Comment
(k) Compiler, interpreter, debugger

2. With illustration, briefly explain two types of comments in python [4 Marks]

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 ]

Dr. Raphael Angulu, BCS 360 SCI, MMUST, 2020: Basics 10


4. State and explain the output of the following lines of code. [3 Marks]
1 length = int(input(”Enter Length: ”))
2 width = int(input(’Enter Length: ”))
3 area = length ∗ width
4 print(”Length =”, length, ”Width =”, width ”Area =”, area)

5. Evaluate the following expressions [6 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

Dr. Raphael Angulu, BCS 360 SCI, MMUST, 2020: Basics 11

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy