Intro Programming Python (1)
Intro Programming Python (1)
Software categories............................................................................................................ 8
1.6 Activity.............................................................................................................................................. 8
1.7 Activity.............................................................................................................................................. 8
Runtime Errors.................................................................................................................... 12
Numbers ............................................................................................................................... 29
String ...................................................................................................................................... 32
Boolean.................................................................................................................................. 33
Logical operators............................................................................................................... 36
Introduction ............................................................................................................................................. 38
if-statement ......................................................................................................................... 39
for Loop................................................................................................................................. 45
while Loop............................................................................................................................ 48
6 Lists ......................................................................................................................................................... 52
7 Functions .............................................................................................................................................. 60
Activity ........................................................................................................................................................ 66
8 Files ......................................................................................................................................................... 68
Activity ................................................................................................................................... 71
Ensure that you understand the key terms or phrases used in this unit as listed below.
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 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
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.
Software categories
• 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
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
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.
• Problem Definition
• Problem Analysis
• Solution design and representation
• Coding and debugging
Problem Definition
Problem Analysis
This process follows after defining your problem. It involves identifying inputs into the
program and their expected outputs.
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.
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.
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
Ifrah, G. (2000). The Universal History of Computing: From the Abacus to Quantum
Computing. New York, NY, USA: John Wiley & Sons, Inc.
Rojas, R., & Hashagen, U. (2002). The first computers: History and architectures.
Cambridge, Mass: MIT Press.
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.
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.
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
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
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
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-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:
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.
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!
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
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.
Let's try another example. What should be the outcome of the following statement?
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:
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." + ' a cold weather "but" still good')
3.5 Indentation
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
Syntax:
For example:
Age = 26
Name = “Lawrence”
Single assignment
Here, we will illustrate the use of the assignment operator (=) with an example:
In this case, we assigned three different values to three variables using the = operator.
Multiple assignment
a=b=c=1
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: (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.
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.
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.
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:
4.3 Operators
Arithmetic operators.
Comparison operators
Assignment operators
Bitwise operators
Logical operators
Membership operators
Identity operators
Arithmetic expressions
Operator Description
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
< 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 not equal to the
right-hand side operand
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
Bitwise operators
Python supports bitwise operations. You might have come across AND, OR, or
complementary operations:
Operator Description
<< 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
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
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
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.
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.
Example:
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.
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:
num = 3.4
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
Nested if Example
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
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:
#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:
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
# 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)))
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.
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:
while i <= n:
sum = sum + i
i +=1 # update counter
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.
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 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:
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.
Objectives/Learning Outcomes
Create a list
Access elements from a list.
Python list methods
E.g.
Courses = []
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]
# nested list
my_list = ["mouse", [8, 4, 6], ['a']]
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])
# 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]
# Output: [2, 2, 3, 4]
print(odd)
# 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])
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])
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)
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']
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).
my_list = ['p','r','o','b','l','e','m']
my_list.remove('p')
# Output: 'o'
print(my_list.pop(1))
# Output: 'm'
print(my_list.pop())
my_list.clear()
# Output: []
print(my_list)
6.5 List functions
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)
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)
Objectives/Learning Outcomes
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
sum = 0
i = 1
sum += i
i+=1
sum = 0
j = 20
j+=1
sum = 0
k = 34
sum += k
k+=1
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:
sum = 0
while x <= y:
sum += x
x+=1
return sum
#print results
Functions are among the most important concepts and constructs of any language,
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.
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.
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
def function_name(arguments):
<statements>
return value
Example
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.
function_name(arguments)
Example
sum(1, 10)
def message():
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.
Example
def message(msg):
print (msg)
#message to print
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.
Example:
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:
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.
2. Temperature Conversion
def fahrenheitToCelcius(Fahrenheit)
def celciusToFahrenheit(Celsius)
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.
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
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:
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:
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
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
#open file
all_read = my_file.read()
print (all_read)
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.
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)?
Consider the situation where you want to make a list of lines of a file; in that case, the
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.close()
Output: famous_quotes.txt
Life is what happens when you are busy making other plans
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()