Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Intro Programming Python (1)

The document provides an introduction to computer programming, covering essential concepts such as computer components, programming languages, and the development cycle of a program. It outlines the phases of program development, including problem definition, analysis, solution design, coding, and debugging, as well as common programming errors like syntax, runtime, and logic errors. Additionally, it highlights the importance of software categories and the role of different programming languages in creating computer programs.

Uploaded by

harrisonlungu406
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Intro Programming Python (1)

The document provides an introduction to computer programming, covering essential concepts such as computer components, programming languages, and the development cycle of a program. It outlines the phases of program development, including problem definition, analysis, solution design, coding, and debugging, as well as common programming errors like syntax, runtime, and logic errors. Additionally, it highlights the importance of software categories and the role of different programming languages in creating computer programs.

Uploaded by

harrisonlungu406
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 72

Contents

1 Introduction to Computer Programming .................................................................................. 6

1.1 Introduction ................................................................................................................................... 6

1.2 Objectives/Learning Outcomes ............................................................................................. 6

1.3 Key Terms ....................................................................................................................................... 6

1.4 Computer Components ............................................................................................................ 6

Central Processing Unit (CPU) ....................................................................................... 7

Main Memory ....................................................................................................................... 7

Input and output devices ................................................................................................ 7

Communication devices ................................................................................................... 7

Storage devices .................................................................................................................... 7

1.5 Software/ Computer Program ............................................................................................... 8

Software categories............................................................................................................ 8

1.6 Activity.............................................................................................................................................. 8

1.7 Activity.............................................................................................................................................. 8

1.8 Programming Languages ......................................................................................................... 9

Machine Language ............................................................................................................. 9

Assembly language ............................................................................................................ 9

High-level languages ......................................................................................................... 9

1.9 Phases in the development of computer program .................................................... 10

Problem Definition ........................................................................................................... 11

Problem Analysis ............................................................................................................... 11

Solution design and representation ......................................................................... 11


Coding and Debugging ................................................................................................. 11

1.10 Errors in Programming ............................................................................................................ 11

Syntax Errors ....................................................................................................................... 11

Runtime Errors.................................................................................................................... 12

Logic Errors .......................................................................................................................... 12

1.11 Summary/Let Us Sum Up ...................................................................................................... 12

1.12 Suggestions for Further Reading/ Reading Assignment .......................................... 12

1.13 Unit Test ........................................................................................................................................ 13

1.14 Answers to Unit Activities ...................................................................................................... 13

2 Getting Started with python ........................................................................................................ 15

2.1 Setting up Environment.......................................................................................................... 15

System or environment variables............................................................................... 16

Setting environment variables in Windows ........................................................... 16

2.2 Your first Python Program..................................................................................................... 22

3 Python Syntax ..................................................................................................................................... 24

3.1 Comments in Python ............................................................................................................... 24

3.2 Triple, double and single quotes........................................................................................ 25

3.3 String inside the quotes ......................................................................................................... 25

3.4 String concatenation ................................................................................................................ 26

3.5 Indentation ................................................................................................................................... 26

4 Variables and operators ................................................................................................................. 28

4.1 Variables ........................................................................................................................................ 28

Single assignment ............................................................................................................. 29

Multiple assignment ........................................................................................................ 29


4.2 Data types in Python ............................................................................................................... 29

Numbers ............................................................................................................................... 29

String ...................................................................................................................................... 32

Boolean.................................................................................................................................. 33

4.3 Operators ...................................................................................................................................... 33

Arithmetic expressions .................................................................................................... 34

Comparison operators .................................................................................................... 35

Variants of assignment operator ................................................................................ 35

Bitwise operators ............................................................................................................... 36

Logical operators............................................................................................................... 36

Membership operators ................................................................................................... 37

5 Control Statement and Loops ..................................................................................................... 38

Introduction ............................................................................................................................................. 38

Objectives/Learning Outcomes ....................................................................................................... 38

5.1 The if and if...else statement ................................................................................................ 39

if-statement ......................................................................................................................... 39

if..else Statement ............................................................................................................... 41

The if...elif...else statement ............................................................................................ 42

5.2 Nested if statements ................................................................................................................ 44

5.3 Loops .............................................................................................................................................. 44

Types of loops .................................................................................................................... 44

for Loop................................................................................................................................. 45

while Loop............................................................................................................................ 48

The break statement........................................................................................................ 50


Nested loops ....................................................................................................................... 50

6 Lists ......................................................................................................................................................... 52

Objectives/Learning Outcomes ....................................................................................................... 52

6.1 Create a list .................................................................................................................................. 52

Creating a list with values ............................................................................................. 52

6.2 Access elements from a list .................................................................................................. 53

List Index ............................................................................................................................... 53

Negative indexing ............................................................................................................. 54

6.3 Adding or updating list .......................................................................................................... 55

6.4 Deleting values in a list .......................................................................................................... 56

6.5 List functions ............................................................................................................................... 58

6.6 Iterating through a List ........................................................................................................... 59

7 Functions .............................................................................................................................................. 60

Objectives/Learning Outcomes ....................................................................................................... 60

7.1 Introduction ................................................................................................................................. 60

7.2 Why use functions? .................................................................................................................. 62

7.3 Categories of functions........................................................................................................... 62

Built-in functions ............................................................................................................... 62

User-defined functions ................................................................................................... 63

Activity ........................................................................................................................................................ 66

Summary/Let Us Sum Up .................................................................................................................. 66

8 Files ......................................................................................................................................................... 68

8.1 File Operations ........................................................................................................................... 68

8.2 Files and Streams ...................................................................................................................... 68


8.3 Creating a File ............................................................................................................................. 69

8.4 Reading from a File .................................................................................................................. 69

The read() method............................................................................................................ 70

The readline() method .................................................................................................... 70

The readlines() method .................................................................................................. 71

Activity ................................................................................................................................... 71

8.5 Writing text to a file ................................................................................................................. 72


1 Introduction to Computer Programming
1.1 Introduction

A computer is a machine or device that performs tasks in accordance to the


instructions provided to it. These tasks include processing and manipulating data in
a variety of ways. Therefore, a computer program can be defined as instructions that
tell the computer what to do and how to do it. This unit will provide a brief overview
of programming, the development cycle of a program and different programming
errors.

1.2 Objectives/Learning Outcomes

On successful completion of the Unit you should be able to:

• Define what a computer program is.


• Distinguish between categories of programming languages.
• Outline the key phases in the development of a computer program
• Explain the differences between syntax errors, runtime errors, and logic
errors

1.3 Key Terms

Ensure that you understand the key terms or phrases used in this unit as listed below.

Computer, Program, Software, Algorithm, Pseudocode, machine language, Assembler,


Assembly Language, High-level language, Low-level Language, Compiler, Interpreter

1.4 Computer Components

A computer comprises of visible physical components referred to as hardware and


non-tangible instructions that control the hardware referred to as software. The major
hardware components of a computer include:

• Central Processing Unit (CPU)


• Main Memory
• Input and output devices (e.g. monitor, keyboard, mouse).
• Storage devices (e.g. Hard disks, CDs e.t.c).
• Communication devices (e.g. network interface cards, modems e.t.c.)

Central Processing Unit (CPU)

This is essentially the brain of the computer. It is made up of a large number of very
small electrical components such as transistors. It is responsible for retrieving
instructions from physical memory and executing those instructions. In order to aid
it in executing instructions, the central processing unit has two key components
namely the control unit and the arithmetic/logic unit (ALU). The control unit
coordinates actions of other components and the ALU is responsible for performing
numerical and logical operations.

Main Memory

Main memory is closely connected to the CPU. It is responsible for storing data and
the instructions or programs that operate on this data. The memory is short term, as
information in main memory ceases to exist once the computer is turned off. It is
also known as Random Access Memory (RAM).

Input and output devices

Input and output devices enable the user to interact and communicate with the
computer. The most common input devices are the mouse and the keyboard. The
most common output devices are the monitor and printer.

Communication devices

Communication devices on a computer are used to network computers together.


Devices such as Network Interface Cards connect a computer to a local area network.

Storage devices

Unlike main memory which is volatile i.e. information is lost when the computer is
switched off, storage devices retain information even after the computer has been
powered off. Data and programs stored in storage devices are moved into main
memory when the computer requires them, reason being that it is much faster for the
computer to access main memory than storage devices. The most common examples
of storage devices are disk drives, USB flash drives and CD/DVD drives.

1.5 Software/ Computer Program

A computer requires software/program in order to function. Software is essentially


instructions for the processor to execute, hence software can also be referred to as
programs.

Software categories

There are several types of software namely:

• System software

These are programs that enable all the software and hardware systems to run
concurrently. The most common example of system software is operating systems
like Windows or Linux. These essentially control and manage the entire computer
system.

• Application software

These are programs that enable users to do various tasks on a computer. The most
common example is word processors such as Microsoft word.

1.6 Activity

Follow the link below. Read and come up with a summary of about 150 words
https://homepage.cs.uri.edu/faculty/wolfe/book/Readings/Reading13.htm

1.7 Activity

In your own words, what is computer program?


1.8 Programming Languages

As previously stated, programs are developed using programming languages.


Programming languages are essentially the notation in which instructions can be
passed onto the computer. Programming languages provide the programmer with
the ability to accurately specify the data that the computer is to operate on within
that program, as well as how it should process the data under a variety of situations.

Machine Language

A computer’s native language, which differs among different types of computers, is its
machine language—a set of built-in primitive instructions. These instructions are in
the form of binary code, so if you want to give a computer an instruction in its native
language, you have to enter the instruction as binary code. For example, to add two
numbers, you might have to write an instruction in binary code, like this:

1101101010011010

However, programming in machine language is tedious and not very intuitive in terms
of readability and modification. Therefore, there are a variety of programming
languages that are more intuitive to develop programs.

Assembly language

Assembly language is categorized as a low level programming language which is much


closer to machine language, with the main difference being that numbers can be
substituted for names thus making it much easier for the programmer to develop
programs. Computers however do not understand assembly language, therefore
another program known as the assembler is used to translate assembly language into
machine code or machine language. However, assembly language is machine
dependent, meaning an assembly program can only be executed on a particular kind
of machine/CPU.

High-level languages

A high-level programming language is much easier to use and learn than assembly
language. High-level languages are considered easier and more user friendly largely
to the fact that they are much closer to natural language like English in terms of
syntax, as well they abstract or hide away most low-level processor operations such
as memory access, which are more prevalent in assembly language. Another key
advantage of high-level programming languages is the fact that they are platform
independent, meaning programs developed using these languages can run on more
than one specific type of machine/CPU. Notable examples of high-level languages
are Java, C, C++, Visual Basic, COBOL, and FORTRAN. Each high-level language is
designed for a specific purpose. For instance, Java is widely used for developing
platform independent network applications, C and C++ are highly popular for
developing system software such Operating systems and Visual Basic is used for
developing GUI based applications.

Compiler
A program written in a high-level language is referred to as a source program or
source code. A computer is not capable of recognising a source program. Therefore,
another computer program known as a compiler is used to translate source code into
machine code or machine language, which is then capable of running on the machine.

1.9 Phases in the development of computer program

When programming, it is usually a bad idea to go straight to a computer and start


writing code. You have to understand the problem you are trying to solve and outline
a step-by-step procedure of how you intend to go about solving it. A well-defined
problem and solution will save you a lot of time spent writing and re-writing code.
Most of the times, the task of creating a computer program is split into the following
main steps:

• Problem Definition
• Problem Analysis
• Solution design and representation
• Coding and debugging
Problem Definition

A problem definition is simply a statement explaining in clear terms what a program


intends to accomplish.

Example: “Create a program that replaces every occurrence of a word in a passage


with another word”

Problem Analysis

This process follows after defining your problem. It involves identifying inputs into the
program and their expected outputs.

Solution design and representation

This stage is about describing the processing that needs to be carried out on the
input in order to come up with the required output. This usually involves expressing
the solution in the form of a sequence of steps. Representing the solution in this way
makes it easier to transform it into source code in a programming language. The
sequence of detailed steps followed when solving a particular problem is called an
algorithm.

Coding and Debugging

Once the design process is complete, the actual computer program is written, i.e. the
instructions are written in a computer language. Coding is generally a very small part
of the entire program development process and also a less time consuming activity
in reality. In this process all the syntax errors i.e. errors related to spelling, missing
commas, undefined labels etc. are eliminated.

1.10 Errors in Programming

Programming errors can be categorized into three types: syntax errors, runtime errors,
and logic errors.

Syntax Errors

Errors that are detected by the compiler are called syntax errors or compile errors.
Syntax errors result from errors in code construction, such as mistyping a keyword,
omitting some necessary punctuation, or using an opening brace without a
corresponding closing brace. These errors are usually easy to detect because the
compiler tells you where they are and what caused them.

Runtime Errors

Runtime errors are errors that cause a program to terminate abnormally. They occur
while a program is running if the environment detects an operation that is impossible
to carry out. Input mistakes typically cause runtime errors. An input error occurs when
the program is fix syntax errors runtime errors waiting for the user to enter a value,
but the user enters a value that the program cannot handle.

For instance, if the program expects to read in a number, but instead the user enters
a string, this causes data-type errors to occur in the program. Another example of
runtime errors is division by zero. This happens when the divisor is zero for integer
divisions.

Logic Errors

Logic errors occur when a program does not perform the way it was intended to.
Errors of this kind occur for many different reasons

1.11 Summary/Let Us Sum Up

In this Unit, we have looked at different components of a computer. We have defined


what a computer program is and explained the processes involved during program
development. Since programs are developed in different languages, we have looked
at the two categories. When developing programs, you will be meeting errors as such,
we have looked at the three types of programming errors and explained how we can
prevent them.

1.12 Suggestions for Further Reading/ Reading Assignment

Ceruzzi, P. E. (2003). A history of modern computing. London: MIT Press.


Ceruzzi, P. E. (2003). A history of modern computing. London: MIT Press. Metropolis,
N, et al. “A History of Computing in the Twentieth Century: A Collection of Essays.” A
History of Computing in the Twentieth Century: a Collection of Essays,
public.eblib.com/choice/publicfullrecord.aspx?p=1888716.

Halmos, P. R. (2016). Algebraic logic. Courier Dover Publications.

Ifrah, G. (2000). The Universal History of Computing: From the Abacus to Quantum
Computing. New York, NY, USA: John Wiley & Sons, Inc.

O’Regan, G. (2012). A brief history of computing. London: Springer.

Patt, Y. N., & Patel, S. J. (2001). Introduction to computing systems. McGraw-Hill.

Randell, B. (2013). The origins of digital computers: selected papers. Springer.

Rojas, R., & Hashagen, U. (2002). The first computers: History and architectures.
Cambridge, Mass: MIT Press.

Tanenbaum, A. S. (2016). Structured computer organization. Pearson Education India.

1.13 Unit Test

1. What is a Computer Program?


2. Why do you need an assembler in Assembly Language?
3. Define an Interpreter and a Compiler?
4. Explain the Program Development Life Cycle
5. Mention the three types of programming errors and give examples

1.14 Answers to Unit Activities

• set of instructions that tell a computer or computerised device what to do


and how to do it.
• to interpret software programs written in assembly language into machine
language, code and instructions that can be executed by a computer
• Interpreter - reads one statement from the source code, translates it to the
machine code or virtual machine code, and then executes it right away.
Compiler - translates entire source code into machine code file - machine
file is then executed
• -
o Problem Definition: Define the problem first before we even try to create
a solution.
o Problem Analysis: Formulate most efficient and effective approach to
solve the problem by breaking up the problem into smaller and simpler
sub-problems.
o Algorithm design and representation (Human Language, Pseudocode or
flowchart).
o Coding and debugging: Writing the solution in a chosen programming
language and fixing errors (also called bugs) that occurs in the program.
• Syntax or Compile-Time Errors: result from errors in code construction
Runtime error: They occur while a program is running if the environment
detects an operation that is impossible to carry out. E.g. dividing by zero
Logic Errors: occur when a program does not perform the way it was
intended to. e.g. erroneous formula giving wrong results.
2 Getting Started with python
The Python language had a humble beginning in the late 1980s when a Dutchman
Guido Von Rossum started working on a fun project, which would be a successor to
ABC language with better exception handling and capability to interface with OS
Amoeba at Centrum Wiskunde and Informatica. It first appeared in 1991. Python 2.0
was released in the year 2000 and Python 3.0 was released in the year 2008. The
language was named Python after the famous British television comedy show Monty
Python's Flying Circus, which was one of Guido's favourite television programmes.

Python is a cross-platform programming language, meaning, it runs on multiple


platforms like Windows, MacOS, Linux and has even been ported to the Java and .NET
virtual machines. It is free and open source. Even though most of today’s Linux and
Mac have Python preinstalled in it, the version might be out-of-date. So, it is always
a good idea to install the most current version.

2.1 Setting up Environment

1. Download the latest version of Python.


2. Run the installer file and follow the steps to install Python
3. During the install process, check Add Python to environment variables. This will
add Python to environment variables and you are able to run Python from any
part of the computer.
4. Once Python is installed, typing python in the command line will invoke the
interpreter in immediate mode. We can directly type in Python code and press
enter to get the output.
5. Try typing in 1 + 1 and press enter. We get 2 as the output. This prompt can
be used as a calculator. To exit this mode type quit() and press enter.
Figure 1: Python sample run

Now you can create a new file and save it with .py extension. For example, hello.py.

To run the application, open your terminal and navigate to where you have saved the
file. Use the command python filename.py. for example, python hello.py.

System or environment variables

If you remember the installation steps explained earlier, you might be still thinking
what are system variables? They are a set of predefined variables, which are available
to all programming units. If it's not set, then each and every time you want to run
your program or execute a Python file, you will have to manually provide path for
each Python executable, but if python.exe is set as a system variable, then the system
automatically recognizes your programming instruction and starts executing.

Setting environment variables in Windows

Here, if python.exe is not provided to the path variable, then the system does not
recognize python as a command, as shown in the following screenshot.
Figure 2: Python not set as an environment variable

Once Python has been updated in the path variables or system variables, the windows
command line recognizes the python command and executes as shown here

Figure 3: Python recognised from cmd

During installation, the installer provides an option to set system variables, which we
have seen in our installation steps. But in case you missed that out, you need not
worry. You can manually set the system variables. Simply follow these steps:

1. Your Python installation will look something like the following screenshot,
where you need to right-click on the address bar and select the Copy address
as text option:
Figure 4: Python installation folder copy address

2. Just right-click on This PC or My Computer and select Properties. Once you


have selected the properties, you will get the following screenshot where you
need to select Advanced system settings:

Figure 5: Advanced System Settings


3. In the windows that opens up, click on “Environment Variables” button. This is
going to open another window.

Figure 6: Environment variable

4. In this window, you will see two boxes containing lists of variables.
User Variables for [username] – Has a list of variables for the user who is
logged in into the computer. These variables cannot be accessed by another
user.
System variables - Has a list of variables that can be accessed by all users
in the system.
In the system variables box, find and click the ‘Path’ variable and click edit.

5. A

Figure 7: Path variable in System variables

new window will pop up listing all the variables that are in the path variable.
Based on the window that pops up, follow one of the below options.
Option 1: Paste the path we copied earlier at the end of the current value
of the path variable, right after appending a semi-colon to the end of the
current path.

Figure 2-8: Editing the path variable


For example, if the path is currently set to C:\Windows\System32, then
after this step it should be C:\Windows\System32;C:\Program
Files\Java\jdk[version]\bin.
Option 2: Click on new then Paste the path we copied earlier at the end of the
current value of the path variable

Figure 2-9: Adding the copied python path to the path variable

6. Click Ok on all the windows that were opened to save your changes.

To see if the process was successful, press Windows key + R. Type cmd in the Run
Box then press enter.
Figure 2-10: Run command

After that, the command prompt window opens up, type the command

“python --version” without the quotes. You should get some information about the
installed version of java, similar to (but might not be exactly like) the following:

Figure 2-11: Output of the "java -version" command

7. If instead you get the error “java is not recognized as an internal or external
command, operable program or batch file” then most likely something went
wrong with the process of setting the environment variable. Please repeat the
process and follow the instructions closely to see where you might have gone
wrong.

2.2 Your first Python Program

Now that we have Python up and running, we can write our first Python program. Let
us create a very simple program called "Hello World!". A "Hello, World!" is a simple
program that outputs Hello, World! on the screen. Since it's a very simple program,
it's often used to introduce a new programming language to a newbie. Type the
following code in any text editor or an IDE and save it as helloWorld.py

print("Hello world")

Then, run the file. You will get the following output.

Hello world!

Congratulations! You just wrote your first program in Python.


3 Python Syntax
Syntaxes can be referred to as simple guidelines that every programming language
requires. Let's try to understand from our daily lives. Let's say you can't eat your food
without having it dressed and placed properly on the platter. You need to have proper
dressing of food before you can consume it. These are sort of syntaxes when we talk
in terms of programming languages.

3.1 Comments in Python

Comments are very important in helping other people understand your code. They
can also help you to quickly remember how your code works if you happen to come
back to it after a long time, hence saving you a lot of time, especially for big
applications

Comments are used to annotate notes or other information without having Python try
to perform an operation on them. One thing to discuss is that comments in Python
are marked with the “#” symbol. For example, “this program prints hello world” is a
comment in the program below

#this program prints hello world

print("Hello world")

In Python, there are two types of comments--one is a single-line comment and the
other is multiline comment. For a single-line comment, # is used, while for a multiline
comment, triple quotes """ are used.

"""this

is a multiline

comment

"""

print("Hello world")
3.2 Triple, double and single quotes

Python does not care if you use single quotes or double quotes to print a single
statement. But, surely, both has some significance while printing complex statements,
which we will see soon.

#this program prints hello world


print("Hello world")
print('Hello world')

Let's try another example. What should be the outcome of the following statement?

print ('What's the matter with you?')

The preceding piece of code gives the following results:

File "helloWorld.py", line 1

print ('What's the matter with you?')

SyntaxError: invalid syntax

Python simply interprets that the statement terminated with a single quote after it.
The solution is to enclose the complete sentence within double quotes as shown:

print ("What's the matter with you?")

Adding double quotes (") gives an error-free output as shown:

What's the matter with you?

3.3 String inside the quotes

For printing a string, either a pair of single (' ') quotes or pair of double quotes (" ")
can be used as shown in the succeeding examples:

print ("Hello 'Mrs' Mangulenje")


print ('a cold weather "but" still good')
This gives the following results:

Hello 'Mrs' Mangulenje

a cold weather "but" still good

3.4 String concatenation

Two strings can be joined using the + operator:

print ("Hello 'Mrs' Mangulenje." + ' a cold weather "but" still good')

The following is the output of the preceding code:

Hello 'Mrs' Mangulenje. a cold weather "but" still good

3.5 Indentation

The most unique characteristic of Python, unlike other programming languages, is


indentation. indentation not only makes Python code readable, but also distinguishes
each block of code from the other. Python forces the user to program in a structured
format. Code blocks are determined by the amount of indentation used. In other
Programming Languages, brackets and semicolons are used to show code grouping
or end-of-line termination. Python doesn’t require those; indentation is used to signify
where each code block starts and ends. Here is an example (line numbers are added
for clarification):

1. x = 1
2. if x : #if x is true
3. y=2
4. if y : #if y is true
5. print ("block 2")
6. print ("block 1")
7. else : print ("block 0")

Each indented line demarcates a new code block. To walk through the above code
snippet, line 1 is the start of the main code block. Line 2 is a new code section; if “x”
has a value not equal to 0, then indented lines below will be evaluated. Hence, lines
3 and 4 are in another code section and will be evaluated if line 2 is true. Line 5 is yet
another code section and is only evaluated if “y” is not equal to 0. Line 6 is part of
the same code block as lines 3 and 4; it will also be evaluated in the same block as
those lines. Line 7 is in the same section as line 1 and is evaluated regardless of what
any indented lines may do; in this case, this line won’t be evaluated because both x
and y are true.

You’ll notice that compound statements, like the if comparisons, are created by having
the header line followed by a colon (“:”). The rest of the statement is indented below
it. The biggest thing to remember is that indentation determines grouping; if your
code doesn’t work for some reason, double-check which statements are indented. A
quick note: the act of saying “x = 1” is assigning a value to a variable. In this case, “x”
is the variable; by definition its value varies. That just means that you can give it any
value you want; in this case the value is “1”. Variables are one of the most common
programming items you will work with because they are what store values and are
used in data manipulation.
4 Variables and operators
4.1 Variables

A variable is a named memory location that is used to store data of a particular type.
For most practical purposes however, it is sufficient to define it as a named data item
that is used to refer to some stored value. When you create a variable, the interpreter
will reserve some space in the memory to store values. Depending on the data type
of the variable, the interpreter allocates memory and makes a decision to store a
particular data type in the reserved memory. Various data types, such as integers,
decimals, or characters, can be stored by assigning different data types to the
variables. Python variables are usually dynamically typed, that is, the type of the
variable is interpreted during runtime and you need not specifically provide a type to
the variable name, unlike what other programming languages require. There are
certain rules or naming conventions for naming variables. The following are the rules:

 Reserved key words such as if, else, and so on cannot be used for naming
variables
 Variable names can begin with _, $, or a letter
 Variable names can be in lower case and uppercase
 Variable names cannot start with a number
 White space characters are not allowed in the naming of a variable

You can assign values to the variable using = or assignment operator.

Syntax:

<variable name>= < expression >

For example:

Age = 26

Name = “Lawrence”
Single assignment

Here, we will illustrate the use of the assignment operator (=) with an example:

city='Blantyre' # A string variable assignment.

money = 100.75 # A floating point number assignment

count=4 #An integer assignment

In this case, we assigned three different values to three variables using the = operator.

Multiple assignment

A single value can be assigned to several variables simultaneously. For example:

a=b=c=1

4.2 Data types in Python

Your programs will have to deal with data. Python (and most programming languages)
provides a way to define every piece of data you work with in your programs. This
defines (and restricts) the kind of operations and computations that can be allowed
on each type of data. These definitions and classifications of data are called data
types.

Data types can be broadly categorized into six different types, listed as follows:

 Numbers
 String
 Boolean
 Tuples
 List
 Dictionary

Numbers

Python supports integers, floating point numbers and complex numbers. They are
defined as int, float and complex class in Python. Integers and floating points are
separated by the presence or absence of a decimal point. 5 is integer whereas 5.0 is
a floating point number. Complex numbers are written in the form, x + yj, where x is
the real part and y is the imaginary part. We can use the type() function to know
which class a variable or a value belongs to and isinstance() function to check if it
belongs to a particular class.

a = 12

# Output: <class 'int'>


print(type(a))

# Output: <class 'float'>


print(type(5.0))

# Output: (8+3j)
c = 5 + 3j
print(c + 3)

# Output: True
print(isinstance(c, complex))

Integer
Integers include zero, all of the positive whole numbers, and all of the negative whole
numbers. The interpreter first checks the expression on the right hand side of the
assignment operator and then binds the value with its variable name; this process is
termed as variable definition or initialization. The int or integer data type ranges from
-231 to (231-1); the leading minus sign shows the negative values. Beyond these ranges,
the interpreter will add L to indicate a long integer.

Floating point numbers


Numbers with certain places after the decimal point are referred to as floating point
numbers in the programming language:

 The floating point number type ranges approximately from -10 to 10^308 and
has 16 digits of precision.
 There are two ways to write a floating point number. It can be written using
ordinary decimal notation or scientific notation. Scientific notation is often
useful for mentioning very large numbers

Complex numbers
Python gives you complex numbers support out of the box. If you don't know what
complex numbers are, you can look them up on the Web. They are numbers that can
be expressed in the form a + ib where a and b are real numbers, and i (or j if
you're an engineer) is the imaginary unit, that is, the square root of -1. a and b are
called respectively the real and imaginary part of the number. It's actually unlikely
you'll be using them, unless you're coding something scientific.

Let's see a small example:

c = 3.14 + 2.73j
print(c.real) # real part
print(c.imag) # imaginary part

Output:

3.14

2.73

Python Mathematics
Python offers modules like math and random to carry out different mathematics like
trigonometry, logarithms, probability and statistics, etc.

import math

# Output: 3.141592653589793
print(math.pi)

# Output: -1.0
print(math.cos(math.pi))

# Output: 22026.465794806718
print(math.exp(10))
# Output: 3.0
print(math.log10(1000))

# Output: 1.1752011936438014
print(math.sinh(1))

# Output: 720
print(math.factorial(6))
String

Strings in programming are simply text, either individual characters, words, phrases,
or complete sentences. They are one of the most common elements to use when
programming, at least when it comes to interacting with the user. Because they are
so common, they are a native data type within Python, meaning they have many
powerful capabilities built-in. Unlike other languages, you don’t have to worry about
creating these capabilities yourself. This is good because the built-in ones have been
tested many times over and have been optimized for performance and stability. Strings
in Python are different than most other languages. First off, there are no char types,
only single character strings (char types are single characters, separate from actual
strings, used for memory conservation). Strings also can’t be changed in-place; a new
string object is created whenever you want to make changes to it, such as
concatenation. This simply means you have to be aware that you are not manipulating
the string in memory; it doesn’t get changed or deleted as you work with it. You are
simply creating a new string each time.

Here’s a list of common string operations:

 s1 = ‘ ’ : empty string
 s2 = “knight’s” : double quotes
 block = “““ - ” ” ” : triple-quoted block
 s1 + s2 : concatenate (combine)
 s2 * 3 : repeat the string a certain number of times
 s2[n] : index (the position of a certain character)
 len(s2) : get the length of a string
 for x in s2 : iteration (sequentially move through the string’s characters)
 ‘m’ in s2 : membership (is there a given character in the string?)

Empty strings are written as two quotes with nothing in between. The quotes used
can be either single or double; my preference is to use double quotes since you don’t
have to escape the single quote to use it in a string.

Triple quoted blocks are for strings that span multiple lines, as shown last chapter.
Python collects the entire text block into a single string with embedded newline
characters. This is good for things like writing short paragraphs of text, e.g.
instructions, or for formatting your source code for clarification.

Boolean

Boolean algebra is that subset of algebra in which the values of the variables are the
truth values: true and false. In Python, True and False are two keywords that are used to
represent truth values. Booleans are a subclass of integers, and behave respectively
like 1 and 0. The equivalent of the int class for Booleans is the bool class, which returns
either True or False. Every built-in Python object has a value in the Boolean context,
which means they basically evaluate to either True or False when fed to the bool function.

Boolean data types can be referred to as an on and off switch, which has only two
values to choose from

Syntax:

<variable name>=<'True' or 'False'>

4.3 Operators

Python supports the following types of operators:

 Arithmetic operators.
 Comparison operators
 Assignment operators
 Bitwise operators
 Logical operators
 Membership operators
 Identity operators

Arithmetic expressions

Arithmetic expressions in any language comprise operands and operators. For


reference, x and y are used as operands having values 10 and 20, respectively. The
following table shows the precedence order:

Operator Description

** Exponent: Performs exponential (power) calculations on operators

* Multiplication: Multiplies values on either side of the operator

/ Division: Divides the left-hand operand by the right-hand


operand

% Modulus: Divides the left-hand operand by the right-hand


operand and returns the remainder

+ Addition: Adds values on either side of the operator

- Subtraction: Subtracts the right-hand operand from the left-hand


operand

In an arithmetic expression, generally, the rule of Bracket, Of, Division, Multiplication,


Addition, and Subtraction (BODMAS) is followed, and operators have their own
precedence order. Exponentiation enjoys a higher precedence order, while addition
and subtraction have a lower precedence order.

The decreasing precedence order is as follows:

 Exponent
 Unary negation
 Multiplication, division, modulus
 Addition, subtraction
If operands are of the same data type, then the resulting value is also of that type.
However, addition of two int data types can produce a long integer.

Comparison operators

Like any other language, Python also supports comparison operators. Comparison
operators return True or False

Operator Description

== Checks the equality

< Returns True if the left-hand side operand is less than the right-
hand side operand

> Returns True if the left-hand side operand is greater than the
right-hand side operand

<= Returns True if the left-hand side operand is less than or equal
to the righthand side operand

>= Returns True if the left-hand side operand is greater than or


equal to the righthand side operand

!= Returns True if the left-hand side operand is not equal to the


right-hand side operand

<> Returns True if the left-hand side operand is not equal to the
right-hand side operand

Variants of assignment operator

Earlier in the chapter, you learned about the assignment operator, =. Now, we will see
some more variants of the assignment operator, often used in combination with
arithmetic operators:
Operator Description

= x=y , y is assigned to x

+= x+=y is equivalent to x=x+y

-= x-=y is equivalent to x=x-y

*= x*=y is equivalent to x=x*y

/= x/=y is equivalent to x=x/y

**= x**=y is equivalent to x=x**y

Bitwise operators

Python supports bitwise operations. You might have come across AND, OR, or
complementary operations:

Operator Description

| Performs binary OR operation

& Performs binary AND operation

~ Performs binary XOR operation

^ Performs binary one's complement operation

<< Left shift operator: The left-hand side operand bit is moved left
by the number specified on the right-hand side

>> Right shift operator: The left-hand side operand bit is moved
right by the number specified on the right-hand side

Logical operators

Python supports logical operators AND, OR, and NOT


Operator Description

and Returns True if both the right-hand and left-hand sides of the
operator are true

or Returns True if any side, either the right-hand side or the left-
hand side, of the operator is true

not If condition in the not operator is True, the not operator makes
it False

Membership operators

Python has two membership operators to test the membership in a sequence, such
as a string, list, tuple, and others

Operator Description

in Returns True if the specified operand is found in the sequence

not in Returns True if the specified operand is not found in the


sequence
5 Control Statement and Loops
Introduction

Statements in a program can be executed in one of three ways: Sequentially:


statements are executed in the order they have been written starting from the top
[default mode of execution]. Selectively: statements are executed depending on a
given condition being true or false. Repetitively: statements are repeated as long as
a given condition is true.

Let's first try to understand what are control statements and why they form an essential
part of any programming language. You might have used the ATM machine to
withdraw money. What do you do when you insert your debit card? The very first
thing you watch on the screen are the options to choose from the menu. Now you
have to perform certain actions, else your card would be turned away after some time,
in case you keep the computer waiting for a long time. When you choose to withdraw,
you have to provide the correct amount, which is required to be withdrawn from the
machine. If you provide the wrong amount, the computer will immediately give the
message "Please enter the correct amount". What happened here? Did you notice?
Here computer is merely following instructions. It has been ordered to accept only
the correct amount and prompt an error message on input of the wrong amount. This
is one such scenario where you can see the use of control statements.

Objectives/Learning Outcomes

On successful completion of the Unit you should be able to:

 Use boolean data type and write boolean expressions using comparison
operators
 Implement selection control using:
o One-way if statement
o if..else statement
o Multiple Alternate if..elif..else Statements
 Nested if statements
 Write programs for executing statements repeatedly using a while loop.
 Write loops using for statements.
 Write nested loops.

5.1 The if and if...else statement

Decision making is required when we want to execute a code only if a certain condition
is satisfied. If can be understood as metaphorical English what if which most people
use in their day to day life. What if this doesn't happen? If I were to become a
billionaire. If this match is drawn, we are out of the champions' league. If this car
doesn't start, use the other one. If you fail this course, you will repeat. We are loaded
with numerous examples from across the globe on usage of if. Same is the case with
programming languages. Majority of the programming languages have control
statements and you will find majority of them use the keyword if in their control
statements. Python is no different and also facilitates the usage of if.

if-statement

This type of if statement executes an action or section of code if and only if a specified
conditional expression results to true. Syntax and examples for one way conditional
statements is stated below.

Syntax:

if test_expression:

#statement(s)

Here, the program evaluates the test_expression and will execute statement(s) only
if the test expression is True. If the test_expression is False , the statement(s) is not
executed.
In Python, the body of the if statement is indicated by the indentation. Body starts
with an indentation and the first unindented line marks the end.

Python interprets non-zero values as True. None and 0 are interpreted as False.

Python if Statement Flowchart

Figure 12:Python if statement flowchart

Example:

# If the number is positive, we print an appropriate message

num = 3
if num > 0:
print(num, "is a positive number.")
print("This is always printed.")

num = -1
if num > 0:
print(num, "is a positive number.")
print("This is also always printed.")

In the above example, num > 0 is the test expression. The body of if is executed only
if this evaluates to True. When variable num is equal to 3, test expression is true and
body inside body of if is executed. If variable num is equal to -1, test expression is
false and body inside body of if is skipped. The print() statement falls outside of the
if block (unindented). Hence, it is executed regardless of the test expression.

if..else Statement

The if..else statement provides a means of executing alternative actions when the
conditional Boolean statement within the parenthesis of the if statement results to
false. Thus the block of code/statements executed differ based on whether the
specified condition is true or false. The syntax and examples for a two-way if
statement are stated below.

if test_expression:

#Body of if

else:

#Body of else

The if..else statement evaluates test_expression and will execute body of if only
when test condition is True . If the condition is False , body of else is executed.
Indentation is used to separate the blocks

if..else Flowchart

Example:
# Program checks if the number is positive or negative
# And displays an appropriate message

num = 3

if num >= 0:
print("Positive or Zero")
else:
print("Negative number")

In the above example, when num is equal to 3, the test expression is true and body
of if is executed and body of else is skipped. If num is equal to -5, the test expression
is false and body of else is executed and body of if is skipped. If num is equal to 0,
the test expression is true and body of if is executed and body of else is skipped.

The if...elif...else statement

If there are a series of actions to be executed, then the if...elif...else block can be
used. Most of the programming languages provide the if...else if...else control
block, while Python has shortened else if to elif but the principle remains the same, that
is, it divides the complete control block into number of blocks for specific action to
be executed. It can be interpreted with day-to-day examples, for example, if this debit
card doesn't work, use this credit card, else pay with a cheque.

Syntax

if test_expression:

#Body of if

elif test_expression:

#Body of elif

else:

#Body of else

Here, in the syntax, we are illustrating a series of branching statements under different
conditions which is also called conditional branching in any language. First, we
encounter an if block and if the condition inside the if block is satisfied or becomes
true, only then will the if block be executed. If while executing the condition inside
the if block is not satisfied, then the control is handed over to the immediate condition
statement, that is, elif block, where the condition would be checked differently, and,
finally, we have the else block, where if all the conditions before the else condition fail,
then the else block will process the code.

Flowchart of if...elif...else

Example:

# we check if the number is positive or


# negative or zero and
# display an appropriate message

num = 3.4

if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")

5.2 Nested if statements

We can have a if...elif...else statement inside


another if...elif...else statement. This is called nesting in computer programming.
Any number of these statements can be nested inside one another. Indentation is the
only way to figure out the level of nesting. This can get confusing, so must be avoided
if we can.

Nested if Example

# In this program, we input a number


# check if the number is positive or
# negative or zero and display
# an appropriate message
# This time we use nested if

num = int(input("Enter a number: "))


if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")

5.3 Loops

There might be a situation where you might require to run a single block of code a
number of times, in that situation, loops come in handy. Loops come handy in
situations such as iterating through data structures in any programming language or
traversing through large sets of data to filter out junk data, followed by certain
keywords followed by alphanumeric characters followed by certain special characters.

Types of loops

There are two types of loops, namely:


1. for loop: In this case, the code of block runs for a defined number of times.
This is useful when the programmer exactly knows in how many counts the task
will be executed or let's assume that he knows the number of elements inside
the data structure. For example, the strength of a classroom.
2. while loop: In this case, the code of block runs until the condition is true. This
is useful where the count is unknown. For example, trying to figure out the
number of times is appears in a literary article.

for Loop

The for loop is used when looping over a sequence, like a list, tuple, or a collection
of objects. Iterating over a sequence is called traversal.

Syntax:

for val in sequence:

#Body of for

Here, val is the variable that takes the value of the item inside the sequence on each
iteration. Loop continues until we reach the last item in the sequence. The body of for
loop is separated from the rest of the code using indentation.
Example:

# Program to find the sum of all numbers stored in a list

# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]

# variable to store the sum


sum = 0

# iterate over the list


for val in numbers:
sum +=val

# Output: The sum is 48


print("The sum is", sum)

The range() function


We can generate a sequence of numbers using range() function. range(10) will
generate numbers from 0 to 9 (10 numbers). We can also define the start, stop and
step size as range(start,stop,step size) . step size defaults to 1 if not provided. This
function does not store all the values in memory, it would be inefficient. So it
remembers the start, stop, step size and generates the next number on the go. To
force this function to output all the items, we can use the function list() .

The following example will clarify this.

# Output: range(0, 10)


print(range(10))

# Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list(range(10)))

# Output: [2, 3, 4, 5, 6, 7]
print(list(range(2, 8)))

# Output: [2, 5, 8, 11, 14, 17]


print(list(range(2, 20, 3)))

We can use the range() function in for loops to iterate through a sequence of
numbers. It can be combined with the len() function to iterate though a sequence
using indexing. Here is an example.

# Program to iterate through a list using indexing

dish = ['nsima', 'chips', 'rice']

# iterate over the list using index


for i in range(len(dish)):
print("I like", dish[i])

for loop with else


A for loop can have an optional else block as well. The else part is executed if the
items in the sequence used in for loop exhausts. break statement can be used to stop
a for loop. In such case, the else part is ignored. Hence, a for loop's else part runs if
no break occurs.

Here is an example to illustrate this.

digits = [0, 1, 5]

for i in digits:
print(i)
else:
print("No items left.")

Here, the for loop prints items of the list until the loop exhausts. When the for loop
exhausts, it executes the block of code in the else and prints

while Loop

In the preceding pages, we saw the for loop in action. It's incredibly useful when you
need to loop over a sequence or a collection. The key point to keep in mind, when
you need to be able to discriminate which looping construct to use, is that the for
loop rocks when you have to iterate over a finite amount of elements. It can be a
huge amount, but still, something that at some point ends. There are other cases
though, when you just need to loop until some condition is satisfied, or even loop
indefinitely until the application is stopped. Cases where we don't really have
something to iterate on, and therefore the for loop would be a poor choice. But fear
not, for these cases Python provides us with the while loop.

The while loop is similar to the for loop, in that they both loop and at each iteration
they execute a body of instructions. What is different between them is that the while
loop doesn't loop over a sequence (it can, but you have to manually write the logic
and it wouldn't make any sense, you would just want to use a for loop), rather, it
loops as long as a certain condition is satisfied. When the condition is no longer
satisfied, the loop ends.

Syntax

while test_expression:

#Body of while

In while loop, test expression is checked first. The body of the loop is entered only if
the test_expression evaluates to True . After one iteration, the test _expression is
checked again. This process continues until the test_expression evaluates to False .
In Python, the body of the while loop is determined through indentation. Body starts
with indentation and the first unindented line marks the end. Python interprets any
non-zero value as True . None and 0 are interpreted as False
Example:

# Program to add natural


# numbers upto
# sum = 1+2+3+...+n

# To take input from the user,


n = int(input("Enter n: "))

# initialize sum and counter


sum = 0
i = 1

while i <= n:
sum = sum + i
i +=1 # update counter

# print the sum


print("The sum is", sum)

In the above program, the test expression will be True as long as our counter
variable i is less than or equal to n (10 in our program). We need to increase the
value of counter variable in the body of the loop. This is very important (and mostly
forgotten). Failing to do so will result in an infinite loop (never ending loop). Finally,
the result is displayed.

while loop with else


Same as that of for loop, we can have an optional else block with while loop as well.
The else part is executed if the condition in the while loop evaluates to False . The
while loop can be terminated with a break statement. In such case, the else part is
ignored. Hence, a while loop's else part runs if no break occurs and the condition is
false.

Example

# Example to illustrate
# the use of else statement
# with the while loop

counter = 0
while counter < 3:
print("Inside loop")
counter = counter + 1
else:
print("Inside else")

Here, we use a counter variable to print the string Inside loop three times. On the
forth iteration, the condition in while becomes False . Hence, the else part is executed

The break statement

The break statements are used to change the flow of any block of statements. There
might be a situation where we might need to break the loop in between; in that
scenario, using the break statement will help us achieve our goal.

Example:

Lodges_in_Zomba = ['Splendor', 'Domino' ,'Peters', 'Mango','Annies','Bluegum']


choice = "Annies"
for lodge in Lodges_in_Zomba:
if(lodge == choice):
break
print (lodge)

Here we have created a list of lodges available in the city of Zomba. We take a variable
choice and assign it a value as "Annies"

We want to print all the places of lodges in Zomba. But there is a twist. We would
like to stop the moment Annies occurs in the list. Hence, for every iteration of the for
loop, the if block will check each and every element inside the list and compare it with
the value we have given to compare, that is, "Annies". So the program will print all
the names appearing before Annies, and the moment Annies occurs, the break
statement terminates the loop. There can be several situations where the break
statement can be handy such as searching for a keyword in a stack of words, searching
a palindrome, and so on.

Nested loops

They are loops inside loops and there could be more than two loops each within
another loop. In most situations, we generally use the break statement to break the
inner loop while the outer loop will continue to execute. Let's try to understand its
working with an example:

cities = ["Blantyre","Lilongwe","Mzuzu","Zomba"]
for city in cities:
str1 = city
for s in str1:
if (s =="o"):
break
print (s)
print ("n")

Here we are interested to print all the city's names and are not interested to print
anything after character o. For this, we create a list of cities and we use the for loop
to iterate through the list. We will use the second for loop to eliminate any characters
appearing after character o. This condition is checked inside the second for loop,
which is nested inside the first for loop with the help of the if statement:
6 Lists
In the real world, we often make lists, such as daily to-do lists, a list of players of a
football team, a shopping list for a marriage proposal, and so on.

A list is a built-in data structure available in Python. It can contain heterogeneous


values such as integers, floats, strings, tuples, lists, and dictionaries. Lists are commonly
used to store collections of homogeneous objects, but there is nothing preventing
you to store heterogeneous collections as well. However, Python lists are mutable; yes,
they can change. The following are the characteristics of a Python list:

 Values are ordered


 Mutable
 A list can hold any number of values
 A list can add, remove, and alter the values

Objectives/Learning Outcomes

On successful completion of the Unit you should be able to:

 Create a list
 Access elements from a list.
 Python list methods

6.1 Create a list

Let's see how we can create an empty list:

<Variable name > = []

E.g.

Courses = []

Creating a list with values

A list contains comma-separated values. For example:


courses = ['DIS112', 'DIS127', 'DIS212', 'DIS111']

friendList = ['Bright', 'Gwamba', 'Eunice', 'Rose', 'Lusungu', 'Laston']

The size of a list can also change during execution, as elements are added or
removed from it. We have seen several examples of lists in Python. Sounds
are lists of sample objects. Pictures are lists containing lists of pixel objects.
When we use a for loop, we iterate over a list of items. We have typically
used lists of pixels, lists of samples, or lists of integers within a certain range in
our for loops.

# empty list
my_list = []

# list of integers
my_list = [1, 2, 3]

# list with mixed datatypes


my_list = [1, "Hello", 3.4]

# nested list
my_list = ["mouse", [8, 4, 6], ['a']]

6.2 Access elements from a list

To access values in lists, use the square brackets for slicing along with the index or
indices to obtain value available at that index. There are various ways in which we can
access the elements of a list.

List Index

We can use the index operator [] to access an item in a list. Index starts from 0. So,
a list having 5 elements will have index from 0 to 5. Trying to access an element other
that this will raise an IndexError . The index must be an integer. We can't use float or
other types; this will result into TypeError . Nested list is accessed using nested
indexing.

my_list = ['c','h','a','n','c','o']
# Output: p
print(my_list[0])
# Output: o
print(my_list[2])

# Output: e
print(my_list[5])

# Error! Only integer can be used for indexing


# my_list[4.0]

# Nested List
n_list = ["Happy", [2,0,1,5]]

# Nested indexing

# Output: a
print(n_list[0][1])

# Output: 5
print(n_list[1][3])
Negative indexing

Python allows negative indexing for its sequences. The index of -1 refers to the last
item, -2 to the second last item and so on.

my_list = ['p','r','o','b','e']

# Output: e
print(my_list[-1])

# Output: p
print(my_list[-5])
6.3 Adding or updating list

List are mutable, meaning, their elements can be changed. We use assignment
operator (=) to change an item or a range of items.

# mistake values
odd = [1, 2, 3, 4]

# change the 1st item


odd[0] = 2

# Output: [2, 2, 3, 4]
print(odd)

# change 2nd to 4th items


odd[1:3] = [3, 5, 7]

# Output: [2, 3, 5, 7, 4]
print(odd)

We can add one item to a list using append() method or add several items using
extend() method.

odd = [1, 3, 5]

odd.append(7)

# Output: [1, 3, 5, 7]
print(odd)
odd.extend([9, 11, 13])

# Output: [1, 3, 5, 7, 9, 11, 13]


print(odd)

We can also use + operator to combine two lists. This is also called concatenation.
The * operator repeats a list for the given number of times.

odd = [1, 3, 5]

# Output: [1, 3, 5, 9, 7, 5]
print(odd + [9, 7, 5])

#Output: ["DIS113", "DIS113", "DIS113"]


print(["DIS113"] * 3)

Furthermore, we can insert one item at a desired location by using the method
insert() or insert multiple items by squeezing it into an empty slice of a list.

odd = [1, 9]
odd.insert(1,3)

# Output: [1, 3, 9]
print(odd)

odd[2:2] = [5, 7]

# Output: [1, 3, 5, 7, 9]
print(odd)

6.4 Deleting values in a list

To remove a list element, you can use either the del statement if you know exactly
which elements you are deleting or the remove method if you do not know.

my_list = ['p','r','o','b','l','e','m']

# delete one item


del my_list[2]

# Output: ['p', 'r', 'b', 'l', 'e', 'm']


print(my_list)
# delete multiple items
del my_list[1:5]

# Output: ['p', 'm']


print(my_list)

# delete entire list


del my_list

# Error: List not defined


print(my_list)

We can use remove() method to remove the given item or pop() method to remove
an item at the given index.

The pop() method removes and returns the last item if index is not provided. This
helps us implement lists as stacks (first in, last out data structure).

We can also use the clear() method to empty a list.

my_list = ['p','r','o','b','l','e','m']
my_list.remove('p')

# Output: ['r', 'o', 'b', 'l', 'e', 'm']


print(my_list)

# Output: 'o'
print(my_list.pop(1))

# Output: ['r', 'b', 'l', 'e', 'm']


print(my_list)

# Output: 'm'
print(my_list.pop())

# Output: ['r', 'b', 'l', 'e']


print(my_list)

my_list.clear()

# Output: []
print(my_list)
6.5 List functions

Method Description Example

friendList = ['Bright', 'Gwamba', 'Eunice']


len(s) Returns the number of
items in the list.
print (len(friendList))

pop() Removes and returns an


element at the given
index

insert() Insert an item at the


defined index

my_list = [3, 8, 1, 6, 0, 8, 4]
sort() Sort items in a list in
ascending order
my_list.sort()

# Output: [0, 1, 3, 4, 6, 8, 8]

print(my_list)

copy() Returns a shallow copy


of the list my_list = [0, 1, 3, 4, 6, 8, 8]

my_list1 = my_list.copy()

# Output: [8, 8, 6, 4, 3, 1, 0]

print(my_list1)
my_list = [0, 1, 3, 4, 6, 8, 8]
reverse() Reverse the order of
items in the list
my_list.reverse()

# Output: [8, 8, 6, 4, 3, 1, 0]

print(my_list)

6.6 Iterating through a List

Using a for loop we can iterate though each item in a list.

friendList = ['Bright', 'Gwamba', 'Eunice', 'Rose', 'Lusungu', 'Laston']

for friend in friendList:


print("Hie ",friend)
7 Functions
A function method is essentially a collection of statements grouped together in a
separate piece code, in order to perform a specific operation. Function therefore
enable the creation of reusable code. The idea behind functions is the breaking down
of a problem or operation into manageable components.

Objectives/Learning Outcomes

On successful completion of the Unit you should be able to:

 Define a function
 Invoke a function both with and without a return value.
 Passing arguments by value.
 Develop modular code using functions.

7.1 Introduction

Write a program that computes the sum of integers from 1 to 10, from 20
to 30, from 35 to 45, respectively

Possible solution from the above activity could be:

sum = 0

i = 1

while i <= 10:

sum += i

i+=1

print("Sum from 1 to 10 is ", sum)

sum = 0

j = 20

while j <= 30:


sum += j

j+=1

print("Sum from 20 to 30 is ", sum)

sum = 0

k = 34

while k <= 45:

sum += k

k+=1

print("Sum from 35 to 45 is ", sum)

Possible problems with our solution:

 There is duplication
o In programming we do not repeat ourselves
o Any repetition increases the programming and maintenance effort
o Repetition increases the size of a program
 We are solving 2 problems in one method
o Computing sum of a range
o Printing the result

Optimised Solution:

#function for calculating sum

def sum(x, y):

sum = 0

while x <= y:

sum += x

x+=1

return sum

#print results

print("Sum from 1 to 10 is ", sum(1, 10))


print("Sum from 20 to 30 is ", sum(20, 30))

print("Sum from 35 to 45 is " ,sum(35, 45))

What is the output from the above code?

7.2 Why use functions?

Functions are among the most important concepts and constructs of any language,

so let me give you a few reasons why we need them:

 They reduce code duplication in a program. By having a specific task taken care
of by a nice block of packaged code that we can import and call whenever we
want, we don't need to duplicate its implementation.
 They help in splitting a complex task or procedure into smaller blocks, each of
which becomes a function.
 They hide the implementation details from their users.
 They improve traceability.
 They improve readability.

7.3 Categories of functions

Functions in any programming language can fall into two broad categories:

 Built-in functions
 User-defined functions

Built-in functions

They are predefined by programming languages and each serves a specific purpose.
While some built-in functions cannot be customized, some can be customized as per
the programming guidelines laid down by a specific programming languages. The
Python language also comes with a set of built-in functions such as len() and insert () .
You can get details about built-in functions from the Python documentation.
The Python documentation can be found at https://docs.python.org

User-defined functions

They are defined by users as per their programming requirement. Functions can be
created or can exist in various forms in any programming language. In this section,
we will learn in depth about various ways in which we can create a function.

Defining a Function in Python


A function in Python is defined by using the def keyword, after which the name of

the function follows, terminated by a pair of braces (which may or may not contain

input parameters) and, finally, a colon (:) signals the end of the function definition

line. Immediately afterwards, indented by four spaces, we find the body of the

function, which is the set of instructions that the function will execute when called

The syntax for function declaration is specified below.

def function_name(arguments):

<statements>

return value

Example

def sum(x, y):

sum = 0

while x <= y:

sum += x

x+=1

return sum

Calling a function
Once a function has been defined in terms of what it is to do, for the function to be
used it has to be invoked or called.

Syntax block of code is:

function_name(arguments)

Example

sum(1, 10)

A function can be called within a programming construct similar to the built-in


function. Use the name of the function followed by a set of parentheses. A function
can be called any number of times within the same programming file, or another, or
can be called within another function. Yes, you got it right: a function can call another
function. Let's learn from an example:

def message():

print ("Programming is Fun!")

message()

Here, we define the message() function and we give a body, which has a print
statement. Finally, we simply call the function by merely typing the name of the
function followed by parentheses. When the program is run, we get the output as
shown.

Function with arguments


So far we saw a function which had no arguments, now we will learn about functions
with arguments. A function can contain any number of arguments depending on the
business requirement.

Example

#message function expecting a parameter

def message(msg):

print (msg)
#message to print

msg = "Programming is Fun!"

#calling message function

message(msg)

In the preceding example, the message function accepts one argument which has a
data type string. We create a variable msg with a certain string statement assigned
and then we call the message function and thereby pass the value of msg.

It is mandatory to pass an argument to the function during function calling after the
function has been defined to accept arguments.

Function with an argument and return type


Sometimes, it may be necessary to return any specific datatype or value from a
function which takes any arbitrary number of arguments.

Example:

#function for calculating the difference

def difference(min, max):

dif = max - min

return dif

#variables

min = 345

max = 2000

#print results

print("The differect between ", max, " and ", min, " is ", difference(min, max)
)

Here, we define the function, which accepts two arguments and the body evaluates
their difference between the numbers with return type as value of the difference, which
is denoted by the return dif statement. We then call the function in the print statement
and pass the value of variable min and variable max.
Activity

1. Fibonacci Sequence

The Fibonacci numbers are the numbers in the following integer sequence:

0, 1, 1, 2, 3, 5, 8,13, 21, 34, 55, 89,144, …

In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the


recurrence relation:

Fn = Fn-1 + Fn-2 with seeds F0 = 0 and F1 = 1.

Write a function Fibonacci (int n) that returns Fn. For example, in n=0, then Fibonacci
(0) should return 0. If n = 1, then it should return 1. For n>1, it should return F n-1+
Fn-1.

For example Fibonacci(9) is 34.

2. Temperature Conversion

Write a program that contains the following functions.

#Converts from Fahrenheit to Celsius

def fahrenheitToCelcius(Fahrenheit)

#converts from Celsius to Fahrenheit

def celciusToFahrenheit(Celsius)

NOTE: the formula for the conversion is:

Fahrenheit = (9.0/5)* Celsius + 32.

Summary/Let Us Sum Up

A function is a collection of statements that perform some specific task and return the
result to the caller. A function can perform some specific task without returning
anything. Functions allow us to reuse the code without retyping the code. In this unit
you have learnt how to create your own functions with or without return values, invoke
a method with or without parameters.
8 Files
Files are a way to save data permanently. Everything you’ve learned so far is resident
only in memory; as soon as you close down Python or turn off your computer, it goes
away. You would have to retype everything over if you wanted to use it again.

The files that Python creates are manipulated by the computer’s file system. Python is
able to use operating system specific functions to import, save, and modify files. It
may be a little bit of work to make certain features work correctly in cross-platform
manner but it means that your program will be able to be used by more people. Of
course, if you are writing your program for a specific operating system, then you only
need to worry about the OS-specific functions.

8.1 File Operations

To keep things consistent, here’s the list of Python file operations:

 output = open(‘/tmp/spam’, ‘w’) Create output file (‘w’ means write)


 input = open(‘data’, ‘r’) Create input file (‘r’ means read)
 S = input.read() Read entire file into a single string
 S = input.read(N) Read N number of bytes (1 or more)
 S = input.readline() Read next line (through end-line marker)
 L = input.readlines() Read entire file into list of line strings
 output.write(S) Write string S onto file
 output.writelines(L) Write all line strings in list L onto file
 output.close() Manual close (or it’s done for you when automatically collected)

8.2 Files and Streams

Python treats files as a data stream, i.e. each file is read and stored as a sequential
flow of bytes. Each file has an end-of-file (EOF) marker denoting when the last byte
of data has been read from it. This is useful because you can write a program that
reads a file in pieces rather than loading the entire file into memory at one time. When
the end-of-file marker is reached, your program knows there is nothing further to read
and can continue with whatever processing it needs to do

8.3 Creating a File

When creating a file in Python you simply create the variable that will represent the
file, open the file, give it a filename, and tell Python that you want to write to it.

Syntax:

file_object = open(file_name ,access_mode)

Where file_object is the name that you will be using whenever to want to use the
file in your program, file_name is the name of your file and access_mode determines
in which mode the file has to be opened, that is, read, write, append, and so on..

Example:

#create a CSV file

myCSVFile = open('Example.csv', 'w')

#create a CSV file

myTextFile = open('Example.txt', 'w')

In both files, we are granting a write access right. If you don’t expressly tell Python
that you want to write to a file, it will be opened in read-only mode. This acts as a
safety feature to prevent you from accidentally overwriting files. In addition to the
standard “w” to indicate writing and “r” for reading, Python supports several other file
access modes

8.4 Reading from a File

Now we will read a file by a program. The access mode for reading is r. In Python, you
can read a file entire file at once, read values at a specified position, read a line and
so on. Let’s take this sample text file (sample.txt) which has the following contents.

sample.txt
You start schooling by rolling into pre-school with your chocolate milk and snack pack. The

next year, you bring your kiddie backpack to kindergarten. If you pass, you'll join the big

boys and girls in elementary school. If you pass Grade 1, the next year you'll enter Grade 2

, and so on, all the way up to Grade 12

The read() method

Let's write a readfile.py program to read the earlier file:

#open file

my_file = open('sample.txt', 'r')

#read file on read() function

all_read = my_file.read()

#print the result

print (all_read)

#close the file

my_file.close()

In the given code, first we created a my_file file object, then we called my_file.read()
to read the file content. After reading, the my_file file object is closed by my_file.close().
To be sure the sample file and the code readfile.py must be in the same directory.
Let's check the output:

The preceding code is running successfully. In order to read character from the file,
you can pass the argument to the read() function, for example, read(43) would read
the first forty three characters of the file.

The readline() method

In order to read the file line by line, use readline().

Let's see the sample code readfile.py:


my_file = open('sample.txt', 'r')

print (my_file.readline())

print (my_file.readline())

print (my_file.readline())

my_file.close()

In code, we have printed three lines. What happens, if you specify count in
readline(count)?

The readlines() method

Consider the situation where you want to make a list of lines of a file; in that case, the

readlines() method allows you to do that.

my_file = open('sample.txt', 'r')

print (my_file.readlines())

my_file.close()

Activity

Write a program to find a particular word from the file. We are making the assumption
that the program should be case insensitive, which means it does not matter whether
the characters are in uppercase or lowercase.

Sample run:
8.5 Writing text to a file

In this section, we will learn how to write a new file using Python. This time we'll use
the write mode 'w' in open(). The 'w' mode creates a new file. If the file already exists,
then the file would be overwritten. We will use the write() function.

Example:

file_input = open("famous_quotes.txt",'w')

file_input.write("Life is what happens when you are busy making other plans")

file_input.write("\nThe way to get started is to quite talking and begin doing")

file_input.write("\nWhoever is happy will make others happy too")

file_input.close()

Output: famous_quotes.txt

Life is what happens when you are busy making other plans

The way to get started is to quite talking and begin doing

Whoever is happy will make others happy too

We wrote lines one by one by adding a new line character \n. You can supply all of
them in one go as shown here:

file_input = open("famous_quotes1.txt",'w')

file_input.write("Life is what happens when you are busy making other plans \nT
he way to get started is to quite talking and begin doing \nWhoever is happy wi
ll make others happy too")

file_input.close()

You might also like