Lectures

Download as pdf or txt
Download as pdf or txt
You are on page 1of 44

[Pick the

INTRODUCTION TO COMPUTER PROGRAMMING


date]

Module 1. Introduction to Computer Programming


Intended Learning Outcome

1. Able to use the print function to print an output

What is Computer Programming?


Programming or Computer programming is a way of giving an instruction to a computer to
perform a specific task. In programming world, it often refer to as coding.

A sequence of instruction that a computer is executing is called computer program. A set of


computer programs can create a software.

Computer in this course will not just be desktop and laptop, but all devices capable of running
computer programs.

The Language of Computer


A computer system is made of electronic devices which operates from 0v to 5v. In computer
design these voltages are divided into two states, which is the High and Low. High corresponds to ranges
close to 5v while the Low corresponds to the voltages near 0v or ground. These states are converted into
a number system called binary. Thus the computer/machine language are a series of binary digits (Bits) of
1 and 0.

Since, it would be hard for human to give instruction to computer system using the machine
language. The computer programming was developed which is base in human natural language.

Programming Languages
A quest to provide a common language that a computer and human will understand leads to the
development of programming languages. There are a lot of programming language that have been
develop but all of these are divided into two types; Low-level Language and High-Level Language.

Low-Level Languages - It has no abstraction and the programming rely closely to the computer
architecture. To create a program using a low level language, the programmer must understand the
[Pick the
INTRODUCTION TO COMPUTER PROGRAMMING
date]

architecture of the computer system such as the number of registers, the size of memory, register and
cache, how the device are connected to each other, how many instruction the machine is capable and what
are these instructions.

Low level program codes are divided into two parts. the opcode and the operand.

High- Level Languages - It has a high-level of abstraction and focus mainly on the programming logic
rather than the underlying hardware architecture. It is more user friendly and generally independent from
the computer hardware.

Translators
Because programming language is similar to a natural language, the machine needs a translator
for it to understand.

The translator’s task is to translate the source code into computer codes which is basically a set of
binary numbers.

Translator can be any of the following:

Interpreters - Some programming language doesn't need to complete the program before you execute it.

An interpreter is a computer program that executes instructions written in a programming or


scripting language directly, without previously needing them to be translated into a machine language
program. An interpreter usually employs one of the following program execution strategies:

1. Parse source code and explicitly execute.

2. Translate the source code to some effective intermediate representation and execute it
immediately;

3. Execute the stored pre-compiled code created by a compiler that is part of the interpreter program.

Some of the most common programming language who still use interpreter are the following:
 Perl
 Python
 Matlab
 Ruby

Compilers - The compiler is a computer program that converts machine code written in one
programming language (source language) into another language (target language). The term
[Pick the
INTRODUCTION TO COMPUTER PROGRAMMING
date]

"compiler" is generally used by applications that convert source code from a high-level programming
language to a lower-level language (e.g. assembly language, object code, or computer code) to
construct an executable application.

The most common language we used usually uses compilers are:

C++

Java

Visual Basic

There are programming language that uses a hybrid of Interpreters and Compilers

Assembler - Assembly language (or assembler language), also abbreviated asm, is any low-level
programming language in which the instructions in the language and the computer code instructions
of the machine correlates quite strongly.
[Pick the
INTRODUCTION TO COMPUTER PROGRAMMING
date]

Module 2
Intended Learning Outcome
1. Able to use the print function to print an output

The print() function


The word print () used here is a name for a function. In python programming the syntax is based on the
meaning of the word. In this can the print here is used to print or display a specific values you specify.

Though this section introduce a function. there are more discussion on the function on the later sections of
this course.

A function may:

An cause an effect or evaluate a value. A function always have a component which is called as
argument. An argument is just like an argument in a mathematical functions. e.g., tan(x). these function
takes one argument (x) which is a measure of an angle.

The good thing is, Python functions are more versatile as it can accept any number of arguments as
needed to perform a task. Some Python functions don't need any argument to perform its task.

To deliver a multiple argument in a print function, you need to place them inside the parentheses and
separated by a comma.

In the example;

print ("Hello, World")

There is only one argument delivered to the print() function and it is delimited with quotes. In python or
any programming language, a text coincide in a quotes is identified as string . All text inside a quotation
will not be considered as part of a code thus will not be executed as instruction.

The print function and the arguments in our example forms a function invocation. There is a more
elaborated discussion on function invocation on the later part of this course .

Try the following codes and analyze the output.


print("The itsy bitsy spider\n climbed up the waterspout.")
print()
print("Down came the rain\n and washed the spider out.")

print("The itsy bitsy spider" , "climbed up" , "the waterspout.")


print("My name is", "Python.", end=" ")
print("Monty Python.")
[Pick the
INTRODUCTION TO COMPUTER PROGRAMMING
date]

Module 3
Intended Learning Outcome
1 Understands and apply the concept of variables in programming

Variables
In mathematics, if we want to solve a problem with missing values, we created a placeholder for that
values and we called it a variables. Programming also allows us to used variables, these will serve a
container for any values you want to assign or inputs from the users.

Usually the variables contains a name and a value;

Assigning variables has its own issues. To reduce errors in assigning variables, the following reminders
must be bear in mind.

The name of the variable must have:


 The name of the variable must not be any reserved words/syntax of the programming language
you are using.
 the name can be upper case or lower case and digits.
 the digits must be combined to a letter for it to be usable.
 The variable name must start with a letter
 the only acceptable character is underscore ( _ ) and these character is considered as letter
 the variable name is case sensitive thus, same name with different case is a different variables.

Note:
Variable assignments may differ based on the programming language you are using. In our example, a
variable comes into existence as a result of assigning a value to it.

If you assign any value to a nonexistent variable, the variable will be automatically created. You don't
need to do anything else.

to create a variable in Python language, you just need to think of a name and assigned a value to it.

Lets try another one:


var = 1
account_number = 2232-2355952
client_name = 'Juan De la Cruz'
print(var, account_number, client_name)
print(Var)

Note:

In writing a code, you can always combine text and variable in printing the result using ( + ) symbol.
[Pick the
INTRODUCTION TO COMPUTER PROGRAMMING
date]

var = 33
print ("My age is " + var)

Sections Exercises.

Implement the following codes and explain what happens in the output.
var = 3
print(var)
var = var + 1
print(var)

a = 3.0
b = 4.0
c = (a ** 2 + b ** 2) ** 0.5
print("c =", c)
[Pick the
INTRODUCTION TO COMPUTER PROGRAMMING
date]

Module 4
Intended Learning Outcomes
1. Understand and apply different data types to solve programming problems

Data Types
In programming we will find a different types of data in our source codes. It can be a numbers , characters
or a just true false. In this section, we will discuss different data types
In programming we will find a different types of data in our source codes. It can be a numbers ,
characters or a just true false. In this section, we will discuss different data types

Integers
These are numbers which are devoid of the fractional part. integers is mainly composed of signed and
unsigned non-fractional numbers.

here are some example of data type assignment in different programming language.

C++ and Java


int a = 1;
int myVar;

In typical C and Java programming, we perform a variable declaration and assign a datatype which
corresponds the variable

Python
a=5
b = "Juan"

In Python programming, the data type will be automatically determined base on the form of the literals i

Floats
The float type are the numbers that have a non-empty decimal fraction. It can be signed or unsigned
number which has a fractional part after the decimal point.

Variable and data type declaration in C and Java;


float c;
float d = 3.44;

Variable declaration using python;


myVar = 2.5
C = -0.4
[Pick the
INTRODUCTION TO COMPUTER PROGRAMMING
date]

whenever we assign a number in a variable with decimal place whether it is between two numbers or
between a zero and a number, it is considered as floating-point numbers:
2.5
-0.4

Int vs float
The two numbers below has different data types:
4
4.0

The number 4 is an integer and 4.0 is a float.

1.2.2 Text
Strings
Strings and numbers are two different data type. Strings are basically for processing text and not a
number. Strings usually comes with quotes upon encoding.

This is a very typical string: "I love programming."

However, there is a catch. The catch is how to encode a quote inside a string which is already delimited
by quotes.

Let's assume that we want to print a very simple message saying:


I love "Engineering"

How do we do it without generating an error?

There are two possible solutions.


print("I love \"Engineering\"")

or
print('I love "Engineering"')

1.2.3 Boolean
Boolean Values
Boolean data types are use to represent very abstract values such as truthfulness. It is used when you want
to create a variable that will store a truthfulness of a statement.

Boolean data type comes from Boolean Algebra which is introduced by George Bool (1815-1864) in his
book entitled "The Laws of Thought.
[Pick the
INTRODUCTION TO COMPUTER PROGRAMMING
date]

The usual statement is that, the program ask question and upon execution of the program, it will provide
an answer which is composed of only two types: Yes/True and No/False

C++ and java


boolean isHappy = true;
boolean isSad = false;

Python
print(10 > 9)
print(10 == 9)
print(10 < 9)

In Python, any statement that will return a true or false answer will automatically assigned as boolean.

Programming Exercises 1

Estimated time
5 minutes

Objectives
 Familiarize with print function
 Able to use variables;
 Able to declare different data types

Scenario
Write a three-line piece of code, that declares a variable and its data type and print the output to match
the expected output

Expected output
The first number ( 5.0) is a float
The second number (20) is a integer
The third is a string:
" I am a string "
[Pick the
INTRODUCTION TO COMPUTER PROGRAMMING
date]

Module 5
Intended Learning Outcomes
1. The student are able to use different operators in solving mathematical and computer problem

Operators
In computer programming, codes that perform arithmetic and logical operations are inevitable. These can
be done using various operators.

Operators can generally be classified as follows:

Assignment Operators
Assignment operators are used to put values in a variable. It must be confused with equal-to
operators which is mainly used for comparison.

Arithmetic Operators

Comprises operators for carrying out arithmetic tasks such as addition, and subtraction. Some
languages provide some arithmetic operators which others may not have. For example the
modulus operator (%) returns the remainder value in division operations.

Relational Operators

are used for comparing values. They include greater than, less than, equal-to, not-equal-to. Their
representation varies as well depending on what programming language you are learning. The
symbols is usually != or !==.

Logical Operators

are used to compute logical operations. The commonly used logical operators are and , or , not.
Some languages represent these operators with symbols such as && for and , || for or , and ! for
not. Logical Operation values usually evaluate to Boolean values true or false.
[Pick the
INTRODUCTION TO COMPUTER PROGRAMMING
date]

2.1 Arithmetic Operators


Addition ( + )
a=1
b=2
c= a + b
print ( c )

Subtraction ( - )
a = 15
b = 27
c= b - a
print ( c )

Multiplication ( * )
a=6
b=3
c=b*a
print ( c )

Division ( / )
a=3
b=9
c=b/a
print ( c )

Integer Division ( // )

A // (double slash) sign is an integer divisional operator. It differs from the standard / operator in two
details:
 its result lacks the fractional part - it's absent (for integers), or is always equal to zero (for floats);
this means that the results are always rounded;
 it conforms to the integer vs. float rule.
print(6 // 3)
print(6 // 3.)
print(6. // 3)
print(6. // 3.)

Modulo (%)

The result of the operator is a remainder left after the integer division.
a=6
b=3
c=a%b
print ( c )
[Pick the
INTRODUCTION TO COMPUTER PROGRAMMING
date]

2.2 Relational Operators


a=7

b = 10

a != b (a is not equal to b)

b > a (b is greater than a)

Note:

= is not the same as ==


= is an assignment operator while == is an relational operators

2.3 Logical Operators


Lets have an example of logical operators on the later part of this course

Programming Exercise 2
Objectives
 Familiarize with the concept of numbers, operators, and arithmetic operations;
 Able to perform basic calculations.

Scenario
Take a look at the code in the editor: it reads a float value, puts it into a variable named x, and prints the
value of a variable named y. Your task is to complete the code in order to evaluate the following
expression:

3x - 2x + 3x - 1
3 2

The result should be assigned to y.

Remember that classical algebraic notation likes to omit the multiplication operator - you need to use it
explicitly. Note how we change data type to make sure that x is of type float.

Keep your code clean and readable, and test it using the data we've provided, each time assigning it to the
x variable (by hardcoding it). Don't be discouraged by any initial failures. Be persistent and inquisitive.
[Pick the
INTRODUCTION TO COMPUTER PROGRAMMING
date]

Test Data
Sample input
x=0
x=1
x = -1

Expected Output
y = -1.0
y = 3.0
y = -9.0
[Pick the
INTRODUCTION TO COMPUTER PROGRAMMING
date]

Module 6
Intended Learning Outcomes
1. The students are able to understand the concept of Looping
2. The student can apply loops in solving programming problems

BASIC INPUT/OUTPUT OPERATION


What is Input/Output

Input and Output (I/0) is the transmission between a data information system, like a computer, and a
user which can be a human or some other data information system. Inputs are the signals or data to be
received by the system; while outputs are the signals or data sent from it.

Built-in functions such as input() and print() are readily available at the Python prompt. These functions
are extensively used for standard input and output operations.

Input

The Programs are made to be stationary by defining the value of variables or hard coding into the source
code

On occasion, it would take the input from the user to provide flexibility.

To allow flexibility, we might want to take the input from the user. In Python, we have the input()
function to allow this. The syntax for input() is:

input([prompt])

Where prompt is the string we wish to display on the screen. It is optional.

>>> num = input('Enter a number: ')

Enter a number: 10

>>> num

'10'

Here, we can see that the entered value 10 is a string, not a number. To convert this into a number we
can use int() or float() functions.
[Pick the
INTRODUCTION TO COMPUTER PROGRAMMING
date]

>>> int('10')

10

>>> float('10')

10.0

This same operation can be performed using the eval() function. But eval takes it further. It can evaluate
even expressions, provided the input is a string

>>> int('2+3')

Traceback (most recent call last):

File "<string>", line 301, in runcode

File "<interactive input>", line 1, in <module>

ValueError: invalid literal for int() with base 10: '2+3'

Python Output Using print() function

We use the print() function to output data to the standard output device (screen). We can also output
data to a file, but this will be discussed later.

Example:

print (I study in Batangas State University)

Output

I study in Batangas State University

Another Example

b = 100
print (‘The number of students is ‘ , b)

Output
The number of students is 100
[Pick the
INTRODUCTION TO COMPUTER PROGRAMMING
date]

In the second print() statement, we can notice that space was added between the string and the value
of variable b. This is by default, but we can change it.

The actual syntax of the print() function is:

Print(*object, sep= ‘ ‘, end=’\n’, file=sys.stdout, flush =False)

Here, objects is the value(s) to be printed.

The sep separator is used between the values. It defaults into a space character.

After all values are printed, end is printed. It defaults into a new line.

The file is the object where the values are printed and its default value is sys.stdout (screen). Here is an
example to illustrate this.

print(1, 2, 3, 4)

print(1, 2. 3, 4, sep =’*’)

print(1, 2. 3, 4, sep =’#’, end=’&’)

Output

1234

1*2*3*4

1#2#3#4&

Output formatting

Sometimes we would like to format our output to make it look attractive. This can be done by using the
str.format() method. This method is visible to any string object
[Pick the
INTRODUCTION TO COMPUTER PROGRAMMING
date]

>>> x = 5; y = 10

>>> print('The value of x is {} and y is {}'.format(x,y))

The value of x is 5 and y is 10

Here, the curly braces {} are used as placeholders. We can specify the order in which they are printed by
using numbers (tuple index).

print('I love {0} and {1}'.format('bread','butter'))

print('I love {1} and {0}'.format('bread','butter'))

Output

I love bread and butter

I love butter and bread

We can even use keyword arguments to format the string.

>>> print('Hello {name}, {greeting}'.format(greeting = 'Goodmorning', name = 'John'))

Hello John, Goodmorning

We can also format strings like the old sprintf() style used in C programming language. We use the %
operator to accomplish this.

>>> x = 12.3456789

>>> print('The value of x is %3.2f' %x)

The value of x is 12.35

>>> print('The value of x is %3.4f' %x)

The value of x is 12.3457

Activity
[Pick the
INTRODUCTION TO COMPUTER PROGRAMMING
date]

Write a Python program that converts feet to meter: The conversion formula is: 1 foot = 0.3048 meters

Your program’s output should look like this: Enter feet: 34 34 feet is equal to 10.3632 meters

You will need to use: Variables Arithmetic operator input() and print()

Boolean

A data type that can have either a True or False value. Then control structures allow the flow of control
to change such that statements can be executed based on some condition, instead of sequentially.

Boolean expression

evaluates to either True or False and can be used as the condition in a control structure. To form a
Boolean expression, we can use relational operators (also called comparison operators) such as '=='
(equality), '!=' (not equal), '<' (less than), '>=' (greater or equal), and so forth. For example, we can have
a Boolean expression such as: x == y

This expression is read as 'x is equal to y' and depending on the values of variables x and y, it evaluates
to either True or False. So if x and y both have value 10, the expression evaluates to 'True' and if they
have different values it evaluates to 'False'.

Now we are ready to look at control structures that use Boolean expression. There are two basic types:
selection and loops

Selection

These types of control structures allow different blocks of code to be executed based on the Boolean
expression. There are three basic types in Python that can be used.

 if

 if-else

 if-elif-else
[Pick the
INTRODUCTION TO COMPUTER PROGRAMMING
date]

The if statement allows to only execute one or more statements when some condition is met. The
addition of the else statement allows an alternative action and the addition of elif, which stands for
'else if', allows for different conditions and having different actions for each of them.

Example:

if (score < 70):

print('Failing score')

elif (score <80)

print('C score')

elif (score <90)

print('B score')

else:

print('A score')

In this code, for any score less than 70 we print 'Failing score'. Then we check additional different ranges
to print 'C score' for a score greater than 70 but less than 80, 'B score' for a score 80 to 89 and lastly, for
any score 90 or greater we print 'A score'.

Boolean Operators

In addition to relational operators, we can also use Boolean operators (also called logical operators) to
form more complex Boolean expressions. There are three basic types: 'and', 'or', and 'not'.

The not operator negates the expression. For example: 'not(x==5)' will evaluate to True if x is not equal
to 5 and True if it is. The way this works is that Python will first evaluate (x==5) to either True or False
and then reverse it. So if (x==5) is True, 'not' will make it False.

When we want the whole expression to be evaluated to True for multiple conditions, we can use the
'and' operator. For example: x==5 and y==6

This Boolean expression evaluates to True when both x is 5 and y is 6, unlike when we use the 'or'
condition where only one expression needs to be True. For example: x==5 or y==6

This expression evaluates to True if either x is 5 or y is 6.


[Pick the
INTRODUCTION TO COMPUTER PROGRAMMING
date]

Note that Boolean expressions are evaluated from left to right; Boolean operators have order of
precedence not, and, or; and expressions in parenthesis have precedence.

Boolean Truth Tables

Truth tables express all possible values and outcomes of an expression. For example, if we consider a
has the value of (x==5) and b has the value of (y == 6) then we can have the following truth tables:

Notice that both a and b expressions have to evaluate to True for the whole 'and' expression to evaluate
to True while only either a or b have to be True for the whole 'or' expression to be True.
[Pick the
INTRODUCTION TO COMPUTER PROGRAMMING
date]

Module 6
Intended Learning Outcomes
1. The student can identify the difference of function and procedures
2. The student are able to use functions and procedures in their programming practices

Loops
Imagine buying new shoes, wearing them once, then putting them in your closet and never touching
them again. Instead of wearing them again, you buy another pair. What happens if you do this every
day?

Very soon, your closet will be full of shoes, and you will waste a LOT of money!

When we write code, we don’t want to spend extra time writing the same things over and over again. If
we already have code in our program that prints “Hi”, we should avoid writing another line that also
prints “Hi.”

Loops are one way to reuse pieces of code. Let’s learn about for loops.

These control structures allow a block of code to be executed more than once based on a Boolean
expression.

Looping means repeating something over and over until a particular condition is satisfied.

There are two basic types in Python that can be used:

 While

 For

While loop
Most loops contain a counter or more generally, variables, which change their values in the course of
calculation. These variables have to be initialized before the loop is started. The counter or other
variables, which can be altered in the body of the loop, are contained in the condition. Before the body of
the loop is executed, the condition is evaluated. If it evaluates to False, the while loop is finished. In other
words, the program flow will continue with the first statement after the while statement, i.e. on the same
indentation level as the while loop. If the condition is evaluated to True, the body, - the indented block
below the line with "while" - gets executed. After the body is finished, the condition will be evaluated
again. The body of the loop will be executed as long as the condition yields True.
[Pick the
INTRODUCTION TO COMPUTER PROGRAMMING
date]

A Simple Example with a While Loop

n = 100

total_sum = 0

counter = 1

while counter <= n:

total_sum += counter

counter += 1

print("Sum of 1 until " + str(n) + " results in " + str(total_sum))

Sum of 1 until 100 results in 5050

Excercise

Write a program, which asks for the initial balance K0 and for the interest rate. The program shall
calculate the new capital K1 after one year including the interest.

Extend the program with a while-loop, so that the capital Kn after a period of n years can be calculated.

K = float(input("Starting capital? "))

p = float(input("Interest rate? "))

n = int(input("Number of years? "))

i=0

while i < n:

K += K * p / 100.0

# or K *= 1 + p / 100.0

i += 1

print(i, K)

print("Capital after " + str(n) + " ys: " + str(K))


[Pick the
INTRODUCTION TO COMPUTER PROGRAMMING
date]

1 100.6

2 101.2036

3 101.8108216

4 102.4216865296

5 103.0362166487776

6 103.65443394867026

7 104.27636055236228

8 104.90201871567645

9 105.53143082797051

10 106.16461941293834

Capital after 10 ys: 106.16461941293834

The else Part

Similar to the if statement, the while loop of Python has also an optional else part. This is an unfamiliar
construct for many programmers of traditional programming languages. The statements in the else part
are executed, when the condition is not fulfilled anymore. Some might ask themselves now, where the
possible benefit of this extra branch is. If the statements of the additional else part were placed right
after the while loop without an else, they would have been executed anyway, wouldn't they? We need
to understand a new language construction, i.e. the break statement, to obtain a benefit from the
additional else branch of the while loop. The general syntax of a while loop looks like this:

while condition:

statement_1

...

statement_n

else:

statement_1

...

statement_n
[Pick the
INTRODUCTION TO COMPUTER PROGRAMMING
date]

while potatoes:

peel

cut

else:

pot pot on oven

cook for 40 minutes

wash salad

and so on

For Loop

A for loop in Python is a control flow statement that is used to repeatedly execute a group of
statements as long as the condition is satisfied. Such a type of statement is also known as an iterative
statement. Thus, a for loop is an iterative statement.
[Pick the
INTRODUCTION TO COMPUTER PROGRAMMING
date]

The statements in any Python program are always executed from top to bottom. However, you can
control the flow of execution by employing control flow statements such as a for loop. Usually, the for
loop is used when we know in advance how many times a code block needs to be executed

Example 1 of For Loops in Python

Let's use the above example of the cake slices and write some code. The following will iterate from 1 to
5 using a for loop:

Output of Example 1

I put a cake slice on plate number 1

I put a cake slice on plate number 2

I put a cake slice on plate number 3

I put a cake slice on plate number 4

I put a cake slice on plate number 5

All 5 plates are ready to be served!

In this example, we have created a Python list of plates from 1 to 5. For each plate number in the list of
plates, we have printed something to the console. So, how did the for loop work? The program iterated
the contents of the for loop until the condition was met. In the first iteration, the number 1 (the first
number in the list named 'plates') was assigned to the variable 'x'. The first (and only) statement in the
loop was then executed and printed the output 'I put a cake slice on plate number 1' to the console.
Since the list still contained more items, the for loop was still in control, so on the second iteration, the
number 2 (the second number in the list) was assigned to the variable 'x' and the print statement was
executed again. The process was repeated until the end of the list was reached, when the loop yielded
control back to the main program flow.
[Pick the
INTRODUCTION TO COMPUTER PROGRAMMING
date]

Syntax in For Loops in Python

Look carefully at code Example 1 and the visual 'For loop syntax'. Do you notice the letter 'x' in the for
statement followed by the keyword 'in'? In the example, 'x' stands for each item retrieved from a Python
list. Thus, the letter 'x' denotes each element in a sequence. A sequence is a general term which refers
to data represented by any of the following Python data types - string, list, tuple, set, or dictionary.
Therefore, when you use the for loop, you are actually telling Python to perform some action for each
element in a sequence of items.

Also, notice that we indent the statements within a conditional block, which is a very important rule of
Python.

List

A list is a data structure in Python that is a mutable, or changeable, ordered sequence of elements. Each
element or value that is inside of a list is called an item. Just as strings are defined as characters
between quotes, lists are defined by having values between square brackets [ ] .

Example

Create a List:

thislist = ["apple", "banana", "cherry"]

print(thislist)

Access Items: You access the list items by referring to the index number:

Example
[Pick the
INTRODUCTION TO COMPUTER PROGRAMMING
date]

Print the second item of the list:

thislist = ["apple", "banana", "cherry"]

print(thislist[1])

Negative Indexing

Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second last
item etc.

Example

Print the last item of the list:

thislist = ["apple", "banana", "cherry"]

print(thislist[-1])

Range of Indexes

You can specify a range of indexes by specifying where to start and where to end the range.

When specifying a range, the return value will be a new list with the specified items.

Example

Return the third, fourth, and fifth item:

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]

print(thislist[2:5])

Note: The search will start at index 2 (included) and end at index 5 (not included).

Remember that the first item has index 0.

By leaving out the start value, the range will start at the first item:
[Pick the
INTRODUCTION TO COMPUTER PROGRAMMING
date]

Example

This example returns the items from the beginning to "orange":

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]

print(thislist[:4])

By leaving out the end value, the range will go on to the end of the list:

Example

This example returns the items from "cherry" and to the end:

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]

print(thislist[2:])

Range of Negative Indexes

Specify negative indexes if you want to start the search from the end of the list:

Example

This example returns the items from index -4 (included) to index -1 (excluded)

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]

print(thislist[-4:-1])

Change Item Value

To change the value of a specific item, refer to the index number:

Example

Change the second item:

thislist = ["apple", "banana", "cherry"]

thislist[1] = "blackcurrant"
[Pick the
INTRODUCTION TO COMPUTER PROGRAMMING
date]

print(thislist)

Loop Through a List

You can loop through the list items by using a for loop:

Example

Print all items in the list, one by one:

thislist = ["apple", "banana", "cherry"]

for x in thislist:

print(x)

Check if Item Exists

To determine if a specified item is present in a list use the in keyword:

Example

Check if "apple" is present in the list:

thislist = ["apple", "banana", "cherry"]

if "apple" in thislist:

print("Yes, 'apple' is in the fruits list")

List Length

To determine how many items a list has, use the len() function:

Example

Print the number of items in the list:

thislist = ["apple", "banana", "cherry"]

print(len(thislist))
[Pick the
INTRODUCTION TO COMPUTER PROGRAMMING
date]

Add Items

To add an item to the end of the list, use the append() method:

Example

Using the append() method to append an item:

thislist = ["apple", "banana", "cherry"]

thislist.append("orange")

print(thislist

To add an item at the specified index, use the insert() method:

Example

Insert an item as the second position:

thislist = ["apple", "banana", "cherry"]

thislist.insert(1, "orange")

print(thislist)

Remove Item

There are several methods to remove items from a list:

Example

The remove() method removes the specified item:

thislist = ["apple", "banana", "cherry"]

thislist.remove("banana")

print(thislist
[Pick the
INTRODUCTION TO COMPUTER PROGRAMMING
date]

Example

The pop() method removes the specified index, (or the last item if index is not specified):

thislist = ["apple", "banana", "cherry"]

thislist.pop()

print(thislist)

Example

The del keyword removes the specified index:

thislist = ["apple", "banana", "cherry"]

del thislist[0]

print(thislist)

Example

The del keyword can also delete the list completely:

thislist = ["apple", "banana", "cherry"]

del thislist

Example

The clear() method empties the list:

thislist = ["apple", "banana", "cherry"]

thislist.clear()

print(thislist)

Copy a List
[Pick the
INTRODUCTION TO COMPUTER PROGRAMMING
date]

You cannot copy a list simply by typing list2 = list1, because: list2 will only be a reference to list1, and
changes made in list1 will automatically also be made in list2

There are ways to make a copy, one way is to use the built-in List method copy().

Example

Make a copy of a list with the copy() method:

thislist = ["apple", "banana", "cherry"]

mylist = thislist.copy()

print(mylist)

Another way to make a copy is to use the built-in method list().

Example

Make a copy of a list with the list() method:

thislist = ["apple", "banana", "cherry"]

mylist = list(thislist)

print(mylist)

Join Two Lists

There are several ways to join, or concatenate, two or more lists in Python.

One of the easiest ways are by using the + operator.

Example

Join two list:

list1 = ["a", "b" , "c"]

list2 = [1, 2, 3]

list3 = list1 + list2


[Pick the
INTRODUCTION TO COMPUTER PROGRAMMING
date]

print(list3)

Another way to join two lists are by appending all the items from list2 into list1, one by one:

Example

Append list2 into list1:

list1 = ["a", "b" , "c"]

list2 = [1, 2, 3]

for x in list2:

list1.append(x)

print(list1)

Or you can use the extend() method, which purpose is to add elements from one list to another list:

Example

Use the extend() method to add list2 at the end of list1:

list1 = ["a", "b" , "c"]

list2 = [1, 2, 3]

list1.extend(list2)

print(list1)

The list() Constructor

It is also possible to use the list() constructor to make a new list.

Example

Using the list() constructor to make a List:

thislist = list(("apple", "banana", "cherry")) # note the double round-brackets


[Pick the
INTRODUCTION TO COMPUTER PROGRAMMING
date]

print(thislist)

Example

Return the third, fourth, and fifth item:

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]

print(thislist[2:5])

Note: The search will start at index 2 (included) and end at index 5 (not included).

Remember that the first item has index 0.

By leaving out the start value, the range will start at the first item:

Example

This example returns the items from the beginning to "orange":

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]

print(thislist[:4])

By leaving out the end value, the range will go on to the end of the list:

Example

This example returns the items from "cherry" and to the end:

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]

print(thislist[2:])

Range of Negative Indexes

Specify negative indexes if you want to start the search from the end of the list:

Example
[Pick the
INTRODUCTION TO COMPUTER PROGRAMMING
date]

This example returns the items from index -4 (included) to index -1 (excluded)

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]

print(thislist[-4:-1])

Change Item Value

To change the value of a specific item, refer to the index number:

Example

Change the second item:

thislist = ["apple", "banana", "cherry"]

thislist[1] = "blackcurrant"

print(thislist)

Loop Through a List

You can loop through the list items by using a for loop:

Example

Print all items in the list, one by one:

thislist = ["apple", "banana", "cherry"]

for x in thislist:

print(x)

Check if Item Exists

To determine if a specified item is present in a list use the in keyword:

Example

Check if "apple" is present in the list:


[Pick the
INTRODUCTION TO COMPUTER PROGRAMMING
date]

thislist = ["apple", "banana", "cherry"]

if "apple" in thislist:

print("Yes, 'apple' is in the fruits list")

List Length

To determine how many items a list has, use the len() function:

Example

Print the number of items in the list:

thislist = ["apple", "banana", "cherry"]

print(len(thislist))

Add Items

To add an item to the end of the list, use the append() method:

Example

Using the append() method to append an item:

thislist = ["apple", "banana", "cherry"]

thislist.append("orange")

print(thislist

To add an item at the specified index, use the insert() method:

Example

Insert an item as the second position:

thislist = ["apple", "banana", "cherry"]

thislist.insert(1, "orange")
[Pick the
INTRODUCTION TO COMPUTER PROGRAMMING
date]

print(thislist)

Remove Item

There are several methods to remove items from a list:

Example

The remove() method removes the specified item:

thislist = ["apple", "banana", "cherry"]

thislist.remove("banana")

print(thislist

Example

The pop() method removes the specified index, (or the last item if index is not specified):

thislist = ["apple", "banana", "cherry"]

thislist.pop()

print(thislist)

Example

The del keyword removes the specified index:

thislist = ["apple", "banana", "cherry"]

del thislist[0]

print(thislist)

Example

The del keyword can also delete the list completely:


[Pick the
INTRODUCTION TO COMPUTER PROGRAMMING
date]

thislist = ["apple", "banana", "cherry"]

del thislist

Example

The clear() method empties the list:

thislist = ["apple", "banana", "cherry"]

thislist.clear()

print(thislist)

Copy a List

You cannot copy a list simply by typing list2 = list1, because: list2 will only be a reference to list1, and
changes made in list1 will automatically also be made in list2.

There are ways to make a copy, one way is to use the built-in List method copy().

Example

Make a copy of a list with the copy() method:

thislist = ["apple", "banana", "cherry"]

mylist = thislist.copy()

print(mylist)

Another way to make a copy is to use the built-in method list().

Example

Make a copy of a list with the list() method:

thislist = ["apple", "banana", "cherry"]

mylist = list(thislist)
[Pick the
INTRODUCTION TO COMPUTER PROGRAMMING
date]

print(mylist)

Join Two Lists

There are several ways to join, or concatenate, two or more lists in Python.

One of the easiest ways are by using the + operator.

Example

Join two list:

list1 = ["a", "b" , "c"]

list2 = [1, 2, 3]

list3 = list1 + list2

print(list3)

Another way to join two lists are by appending all the items from list2 into list1, one by one:

Example

Append list2 into list1:

list1 = ["a", "b" , "c"]

list2 = [1, 2, 3]

for x in list2:

list1.append(x)

print(list1)
[Pick the
INTRODUCTION TO COMPUTER PROGRAMMING
date]

Or you can use the extend() method, which purpose is to add elements from one list to another list:

Example

Use the extend() method to add list2 at the end of list1:

list1 = ["a", "b" , "c"]

list2 = [1, 2, 3]

list1.extend(list2)

print(list1)

The list() Constructor

It is also possible to use the list() constructor to make a new list.

Example

Using the list() constructor to make a List:

thislist = list(("apple", "banana", "cherry")) # note the double round-brackets

print(thislist)

List Methods

Python has a set of built-in methods that you can use on lists.

Method Description

append() Adds an element at the end of the list


[Pick the
INTRODUCTION TO COMPUTER PROGRAMMING
date]

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

extend() Add the elements of a list (or any iterable), to the end of the current list

index() Returns the index of the first element with the specified value

insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list

Functions and Procedures


Function is a group of statement that perform a specific task. It help break the program into smaller and
modular chunks. Functions make it more organized and manageable to avoid repetition and makes the
code reusable.

Function Syntax
1. Functions introduce two new keywords: def and return
2. Functions accept arguments
3. Functions contain code and (usually) documentation

Difference between FUNCTION and


PROCEDURE.
[Pick the
INTRODUCTION TO COMPUTER PROGRAMMING
date]

Function returns a value and used to calculate a value based on input while procedure executes commands
in order.

Example 1: Adding two numbers: procedures vs function.

Challenge 1: Write a program to find sum of two


numbers using functions and calculate their
average?

Function Call, Indentation, Arguments & Return


Values
Python provides you many inbuilt functions like print(), but it also gives freedom to create your own
functions.
[Pick the
INTRODUCTION TO COMPUTER PROGRAMMING
date]

Example 2: A function using "def function_hello ( ): " and call the function. The function print
function_hello() calls our def function_hello(): and print the command " This is Python Function."

References:
https://edube.org/learn/programming-essentials-in-python/your-first-program-
3 https://hourofpython.trinket.io/a-visual-introduction-to-python#/turtles/meet-
tina https://www.freecodecamp.org/news/a-gentler-introduction-to-programming-1f57383a1b2c/

Boolean Control Structures in Python: Definition & Examples. (2018, December 29). Retrieved from
https://study.com/academy/lesson/boolean-control-structures-in-python-definition-examples.html.
For Loops in Python: Definition & Examples. (2018, July 22). Retrieved from
https://study.com/academy/lesson/for-loops-in-python-definition-examples.html.
Python Course. https://www.python-course.eu/python3_loops.php.
Python For Loops: Tutorials, Examples & Notes: Beginners. Teach Computer Science. (2019, September
25). https://teachcomputerscience.com/gcse-python/loops/.
Python Lists. https://www.w3schools.com/python/python_lists.asp.

Reference:
Busbee, K. L. (2018, December 15). Input and Output. Programming Fundamentals.
https://press.rebus.community/programmingfundamentals/chapter/input-and-output/.
Python Input, Output and Import. https://www.programiz.com/python-programming/input-output-
[Pick the
INTRODUCTION TO COMPUTER PROGRAMMING
date]

import.
University of Auckland. (2020, August). Python – Input, output and variables. Lecture 23 –
COMPSCI111/111G SS 2018. University of Auckland.

You might also like