CSC201 Python 092740
CSC201 Python 092740
LECTURE NOTE
(First Part)
2024
INTODUCTUCTION TO COMPUTER PROGRAMMING
Programming languages are languages through which we can instruct the computer to carry out
some processes or tasks. They are also designed to communicate ideas about algorithms between
human beings and computers. Programming languages can be used to execute a wide range of
algorithms, that is, an instruction could be executed through more than a procedure of execution.
A program is a set of codes that instructs the computer to carry out some processes.
Programs and programming languages have been in existence since the invention of computers,
Machine Language
Machine language is a set binary coded instruction, which consists of zeros (0) and ones (1).
Machine language is peculiar to each type of computer. The first generation of computers was
coded in machine language that was specific to each model of computer. Some of the shortcomings
Machine language was not user-friendly. That is the user had to remember a long list of
codes, numbers or operation codes and know where instructions were stored in computer
memory.
Debugging any set of codes is a very difficult task since it requires going through the
The advantage of machine language is that it requires no translation since it is already in machine
This is a level of programming language which is different from the machine language. That is, the
instructions are not entirely in binary coded form. It also consists of some symbolic codes, which
are easier to remember than machine codes. In assembly language, memory addresses are
referenced by symbols rather than addresses in machine language. Low level programming
language is also called assembly language, because it makes use of an assembler to translate codes
1
The major advantage of the assembly language is that programs written in it are easier to read and
more user friendly than those written in machine language, especially when comments are inserted
in the codes.
the computer because the programmer only needs to pay attention to the steps or procedures
involved in solving the problem for which the program is to be used to execute the problem. High-
level language is usually broken into one or more states such as: Main programs, sub-programs,
classes, blocks, functions, procedures, etc. The name given to each component differs from one
It saves much time and effort when used compared to any other programming level
language.
There are some conventional features which a programming language must possess, these features
are:
It must have a language structure, which consists of keywords, expressions and statements.
Programming languages are written and processed by the computer for the purpose of
CHARACTERISTICS OF PROGRAM
Clarity: Refer to the overall readability of the program, with emphasis on its underlying
logic.
Simplicity: The clarity and accuracy of the program are usually enhanced by keeping the
Efficiency: It is concerned with the execution speed and efficient memory utilization.
modules.
2
Generality: Program must be as general as possible.
operating system.
An algorithm is more abstract – it does not deal with machine specific details – think of it as
What is good algorithm? Efficient algorithms are good, we generally measure efficiency of
DESIGNING A PROGRAM
A program is a set of instructions that are grouped together to accomplish a task or tasks. The
instructions consist of task like reading and writing memory, arithmetic operations, and
We can design a program by going through the following first four major steps:
2. Design a solution/Program
Analyze the program: When we analyze a problem, we think about the requirements of the
Design a solution/Program: This is the stage where we decide how our program will work
to meet the decision made during analysis. Program design does not require the use of a
computer. We can design program using pencil and paper. This is the stage where algorithm
are designed.
Code/Enter the Program: Here we enter the program into the machine by making use of
Test the Program: This part deals with testing of programs for various inputs and making
necessary changes if required. Testing cannot show that a program produces the correct
output for all possible inputs, because there are typically an infinite number of possible
inputs. But testing can reveal syntax errors, run-time problems and logical mistakes.
3
Evaluate the solution: Thus, finally program can be implementing to obtain desired results.
Use of procedures.
Documentation of program
Debugging program
Testing
procedures could be written to carry out different task and then can be combined
and linked with the main procedure. This will help in making the algorithm and
wish to store age of two different people we can define variable age1, age2 to store
their ages. The main advantage of choosing correct variable is that the program
becomes self-explanatory
can be used easily by the other people unfamiliar with the working and input
Debugging the Program: It is expected that one should carry out number of tests
correctly according to its specifications. The program may have some logical
To detect such type of errors we may print computed values at various steps
Program Testing: The program should be tested against many possible inputs.
Some of the things we might check are whether the program solves the smallest
that handle all input conditions, all the time. Whenever possible, programs should
4
TRANSLATORS
A translator is a program that translates another program written in any programming language
other than the machine language to an understandable set of codes for the computer and in so
doing produces a program that may be executed on the computer. The need for a translator arises
because only a program that is directly executable on a computer is the machine language.
Interpreters and Compilers: These consist of programs that convert programs in high level
programming language into machine language. The major difference between interpreters
and compilers is that a compiler converts the entire source program into object code before
the entire program is executed while the interpreter translates the source instructions line
by line. In the former, the computer immediately executes one instruction before translating
FEATURES OF TRANSLATORS
There exist different translators for different levels and types of programming languages
INTRODUCTION TO PYTHON
Python is one of the most widely used user-friendly programming languages. It is an open-
programming language.
Python is not intended to work on special area such as web programming. That is why it
is known as multipurpose because it can be used with web, enterprise, 3D CAD etc.
We don’t need to use data types to declare variable because it is dynamically typed so
Python makes the development and debugging fast because there is no compilation step
HISTORY
Python was first introduced by Guido Van Rossum in 1991 at the National Research
Though the language was introduced in 1991, the development began in the 1980s.
Previously van Rossum worked on the ABC language at Centrum Wiskunde & Informatica
5
The ABC language was capable of exception handling and interfacing with the Amoeba
operating system. Inspired by the language, Van Rossum first tried out making his own
version of it.
used for software development at companies and organizations such as Google, Yahoo,
Python developer, Rossum always wanted the name of his new language to be short,
Inspired by Monty Python’s Flying Circus, a BBC comedy series, he named it Python.
Python programming language is being updated regularly with new features and supports. There
are lots of update in Python versions, started from 1994 to current release, the current version today
FEATURES
1. Easy to Code:
Python is a very developer-friendly language which means that anyone and everyone can
As compared to other object-oriented programming languages like Java, C, C++, and C#,
Python is an open-source programming language which means that anyone can create and
Python has an online forum where thousands of coders gather daily to improve this
language further. Along with this Python is free to download and use in any operating
GUI or Graphical User Interface is one of the key aspects of any programming language
because it has the ability to add flair to code and make the results more visual.
Python has support for a wide array of GUIs which can easily be imported to the interpreter,
thus making this one of the most favorite languages for developers.
4. Object-Oriented Approach:
One of the key aspects of Python is its object-oriented approach. This basically means
that Python recognizes the concept of class and object encapsulation thus allowing
Suppose you are running Python on Windows and you need to shift the same to either a
Mac or a Linux system, then you can easily achieve the same in Python without having
This is not possible in other programming languages, thus making Python one of the most
6. Highly Dynamic
Python is one of the most dynamic languages available in the industry today. What this
basically means is that the type of a variable is decided at the run time and not in advance.
Due to the presence of this feature, we do not need to specify the type of the variable
Out of the box, Python comes in built with a large number of libraries that can be
The presence of libraries also makes sure that you don’t need to write all the code
yourself and can import the same from those that already exist in the libraries.
APPLICATION OF PYTHON
Data Science
Desktop Applications
Mobile Applications
Software Development
Enterprise Applications
3D CAD Applications
Machine Learning
Gaming
INSTALLING PYTHON
To install Python, firstly download the Python distribution from official website of python
(www.python.org/ download).
Another useful method of executing the Python code. Use the Python IDLE GUI Shell to
integrated development environment (IDE) that comes bundled with the Python
7
programming language. IDLE provides a graphical user interface (GUI) for writing,
IDLE offers several features that facilitate the development process for Python
programmers, including:
Interactive Shell: IDLE includes an interactive Python shell, which allows you to
Code Editor: It provides a text editor where you can write and edit Python scripts.
The editor supports features like syntax highlighting, auto-indentation, and code
completion.
Open the Python IDLE shell by pressing the window button of the keyboard. Type “Python”
and click the “IDLE (Python 3.7 32-bit)” to open the Python shell.
Create a Python file with .py extension and open it with the Python shell. The file looks
It contains the simple Python code which prints the text “Hello World!”. In order to execute
the Python code, you have to open the ‘run’ menu and press the ‘Run Module’ option.
8
A new shell window will open which contains the output of the Python code. Create your
own file and execute the Python code using this simple method by using Python IDLE.
DEBUGGING
Debugging means the complete control over the program execution. Developers use
Debugging is a healthier process for the program and keeps the diseases bugs far away.
Syntax Errors:
Errors are the mistakes or faults performed by the user which results in abnormal working
of the program.
A syntax error occurs when we do not use properly defined syntax in any programming
language. For example: incorrect arguments, indentation, use of undefined variables etc.
Example
9
def my_function():
print("Indentation is missing") # Missing indentation for the function body
age=16
if age>18:
print ("you can vote”) # syntax error because of not using indentation
else
print ("you cannot vote”) #syntax error because of not using indentation
Runtime Errors:
The second type of error is a runtime error, so called because the error does not appear
These errors are also called exceptions because they usually indicate that something
division by zero
accessing a list element, dictionary value or object attribute which doesn’t exist
Example
radius = 5
area = 3.14 * r * r # Incorrect variable name 'r' instead of 'radius'
print ("Area:", area)
Semantic Errors:
The problem is that the program you wrote is not the program you wanted to write. The
Example
x =3
y=4
x + y = z # In appropriate assigning of variable
print(z)
10
Logical Errors:
Logical errors occur when the code runs without any error, but the output is not as expected due
Unlike other errors logical errors are not displayed while interpreting because interpreter
Example
To find the area of the circle the formula to be used is area = 3.14 * r * r
But if we written area = 3.14 * 2 * r, then the required output is not obtained even though the
PYTHON COMMENTS
Creating a Comment
Example
#This is a comment
print("Hello, World!")
Comments can be placed at the end of a line, and Python will ignore the rest of the line:
Example
print("Hello, World!") #This is a comment
Multiline Comments
You can add a multiline string (triple quotes) in your code, and place your comment inside it:
Example
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
PYTHON VARIABLES
Variables are names given to data that we need to store and manipulate in our programs. For
instance, suppose your program needs to store the age of a user. To do that, we can name this
data userAge and define the variable userAge using the following statement.
userAge = 24
11
Creating Variables
Python has no command for declaring a variable.
x=5
y = "John"
Variables do not need to be declared with any particular type, and can even change type after
they have been set.
Example
x=4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Casting
If you want to specify the data type of a variable, this can be done with casting.
Example
x = str(3) # x will be '3'
z = float(3) # z will be 3.0
Example
x = "John"
# is the same as
x = 'John'
Case-Sensitive
Example
a=4
A = "Sally"
#A will not overwrite a
Variable Names
A variable can have a short name (like x and y) or a more descriptive name (age, carname,
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and
_)
12
Variable names are case-sensitive (age, Age and AGE are three different variables)
Example
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
Example
2myvar = "John"
my-var = "John"
my var = "John"
There are several techniques you can use to make them more readable:
Camel Case
myVariableName = "John"
Pascal Case
MyVariableName = "John"
Snake Case
my_variable_name = "John"
Example
x, y, z = "Orange", "Banana", "Cherry"
And you can assign the same value to multiple variables in one line:
Example
x = y = z = "Orange"
13
Output Variables
Example
x = "Python"
y = "is"
z = "awesome"
print(x, y, z)
Example
x = "Python "
y = "is "
z = "awesome"
print(x + y + z)
Example
x=5
y = 10
print(x + y)
Global Variables
Variables that are created outside of a function (as in all of the examples above) are known as global
variables. Global variables can be used by everyone, both inside of functions and outside.
Example
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
If you create a variable with the same name inside a function, this variable will be local, and can
only be used inside the function. The global variable with the same name will remain as it was,
Example
Create a variable inside a function, with the same name as the global variable
14
x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc()
print("Python is " + x)
If you use the global keyword, the variable belongs to the global scope:
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
To change the value of a global variable inside a function, refer to the variable by using
the global keyword:
x = "awesome"
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
In programming, data type is an important concept. Variables can store data of different types, and
different types can do different things. Python has the following data types built-in by default, in
these categories:
You can get the data type of any object by using the type () function:
Example
x=5
y = "John"
print(type(x)) # <class ‘int’>
print(type(y)) # <class ‘str’>
In Python, the data type is set when you assign a value to a variable:
15
Example Data Type
x = 20 int
x = 20.5 float
x = range(6) range
range (6) will generate the list [0, 1, 2, 3, 4, 5]
x = {"name" : "John", "age" : 36} dict
x = True bool
x = None NoneType
PYTHON NUMBERS
int
float
Variables of numeric types are created when you assign a value to them:
Example
x = 1 # int
y = 2.8 # float
Int
Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.
Example:
userAge = 20, mobileNumber = 07055556666
x=1
y = 35656222554887711
z = -3255522
Float
Float, or "floating point number" is a number, positive or negative, containing one or more
decimals.
Example:
userHeight = 1.82, userWeight = 67.2
x = 1.10
y = 1.0
z = -35.59
16
Type Conversion
You can convert from one type to another with the int() and float() methods
Example
Convert from one type to another:
x=1 # int
y = 2.8 # float
a = float(x)
b = int(y)
print(a) # 1.0
print(b) # 2
To change a string to an integer, we can type int (“4”) and we’ll get 4. However, we cannot type
The float() function takes in an integer or an appropriate string and changes it to a float. For
instance, if we type float(2) or float(“2”), we’ll get 2.0. If we type float(“2.09109”), we’ll get
2.09109 which is a float and not a string since the quotation marks are removed.
The str() function on the other hand converts an integer or a float to astring. For instance, if we
Strings
Strings in python are surrounded by either single quotation marks, or double quotation marks.
To declare a string, you can either use variableName = ‘initial value’ (single quotes) or
Example:
Example
print("Hello")
print('Hello')
representing unicode characters. However, Python does not have a character data type, a single
17
Square brackets can be used to access elements of the string.
Example
Get the character at position 1 (remember that the first character has the position 0):
a = "Hello, World!"
print(a[1])
Since strings are arrays, we can loop through the characters in a string, with a for loop.
Example
for x in "banana":
print(x)
String Length
Example
a = "Hello, World!"
print(len(a)) #13
Check String
To check if a certain phrase or character is present in a string, we can use the keyword in.
Use it in an if statement:
Example
txt = "The best things in life are free!"
if "free" in txt:
print("Yes, 'free' is present.")
Check if NOT
To check if a certain phrase or character is NOT present in a string, we can use the keyword not in.
Use it in an if statement:
Example
Slicing
Specify the start index and the end index, separated by a colon, to return a part of the string.
18
Example
b = "Hello, World!"
print(b[2:5]) #llo
By leaving out the start index, the range will start at the first character:
Example
b = "Hello, World!"
print(b[:5])
By leaving out the end index, the range will go to the end:
Example
Get the characters from position 2, and all the way to the end:
b = "Hello, World!"
print(b[2:])
Modify Strings
Upper Case
Example
a = "Hello, World!"
print(a.upper())
Lower Case
Example
a = "Hello, World!"
print(a.lower())
Replace String
Example
a = "Hello, World!"
print(a.replace("H", "J"))
19
String Concatenation
To concatenate, or combine, two strings you can use the + operator. We can combine multiple
substrings by using the concatenate sign (+). For instance, “Peter” + “Lee” is equivalent to the
string “PeterLee”.
Example
a = "Hello"
b = "World"
c=a+b
print(c)
Example
a = "Hello"
b = "World"
c=a+""+b
print(c)
The find() method finds the first occurrence of the specified value. The find() method returns -1 if
the value is not found.
Example
Where in the text is the first occurrence of the letter "e" when you only search between position 5
and 10?
20
String format() Method
Example
age = 36
txt = "My name is John, I am " + age
print(txt) #This will generate error
But we can combine strings and numbers by using the format() method! The format() method takes
unlimited number of arguments, and are placed into the respective placeholders. The placeholders
can be identified using named indexes {price}, numbered indexes {0}, or even empty
placeholders {}. The format() method allows you to format selected parts of a string. Sometimes
there are parts of a text that you do not control, maybe they come from a database, or user input?
To control such values, add placeholders (curly brackets {}) in the text, and run the values through
Example
age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))
age = 36
txt = "My name is Ali, and I am {}".format(age)
print(txt)
Example
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
Example
print(txt.format(price))
Index Numbers
You can use index numbers (a number inside the curly brackets {0}) to be sure the values are placed
Example
You can use index numbers {0} to be sure the arguments are placed in the correct placeholders:
quantity = 3
itemno = 567
21
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))
myorder = "I want {0} pieces of item number {1} for {2:.2f} dollars."
print(myorder.format(quantity, itemno, price))
Example
quantity = 3
itemno = 567
price = 49
myorder = "I want {0:d} pieces of item number {1:d} for {2:.2f} dollars."
print(myorder.format(quantity, itemno, price))
Also, if you want to refer to the same value more than once, use the index number:
Example
age = 36
name = "John"
txt = "His name is {1}. {1} is {0} years old."
print(txt.format(age, name))
Named Indexes
You can also use named indexes by entering a name inside the curly brackets {carname}, but then
you must use names when you pass the parameter values txt.format(carname = "Ford"):
Example
myorder = "I have a {carname}, it is a {model}."
print(myorder.format(carname = "Ford", model = "Mustang"))
Escape Character
Sometimes we may need to print some special “unprintable” characters such as a tab or a
newline. In this case, you need to use the \ (backslash) character to escape characters that
For instance to print a tab, we type the backslash character before the letter t, like this: \t.
Without the \ character, the letter t will be printed. With it, a tab is printed. Hence, if you type
Example
You will get an error if you use double quotes inside a string that is surrounded by double quotes:
Example
The escape character allows you to use double quotes when you normally would not be allowed:
22
Escape Characters
Python Booleans
Boolean Values
In programming you often need to know if an expression is True or False. You can evaluate any
expression in Python, and get one of two answers, True or False. When you compare two values,
print(10 > 9)
print(10 == 9)
print(10 < 9)
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
PYTHON OPERATORS
Operators are used to perform operations on variables and values. In the example below, we use
Example
print(10 + 5)
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
23
Membership operators
Arithmetic operators are used with numeric values to perform common mathematical operations:
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
== Equal x == y
!= Not equal x != y
24
Python Logical Operators
statements is true
not Reverse the result, returns not(x < 5 and x < 10)
the object
x = ["apple", "banana"]
print("banana" in x) //True
in the object
x = ["apple", "banana"]
Operator Precedence
Example
Parentheses has the highest precedence, meaning that expressions inside parentheses must be
evaluated first:
print((6 + 3) - (6 + 3)) #0
Example
Multiplication * has higher precedence than addition +, and therefor multiplications are
evaluated before additions:
print(100 + 5 * 3) #115
25
Example
Addition + and subtraction - has the same precedence, and therefore we evaluate the expression
print(5 + 4 - 7 + 3) #5
PYTHON LISTS
List refers to a collection of data which are normally related. Instead of storing these data as
separate variables, we can store them as a list. For instance, suppose our program needs to store
the age of 5 users. Instead of storing them as user1Age, user2Age, user3Age, user4Age and
To declare a list, you write listName = [initial values]. Note that we use square brackets [ ]
Example:
userAge = [21, 22, 23, 24, 25]
List Items
List items are indexed, the first item has index [0], the second item has index [1] etc.
Ordered
When we say that lists are ordered, it means that the items have a defined order, and that order
If you add new items to a list, the new items will be placed at the end of the list.
Changeable
The list is changeable, meaning that we can change, add, and remove items in a list after it has been
created.
Allow Duplicates
Since lists are indexed, lists can have items with the same value:
Example
Lists allow duplicate values:
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)) #3
26
List Items - Data Types
Example
Example
Access Items
List items are indexed and you can access them by referring to the index number:
Example
Negative Indexing
Negative indexing means start from the end
-1 refers to the last item, -2 refers to the second last item etc.
Example
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
Note: The search will start at index 2 (included) and end at index 5 (not included).
27
By leaving out the start value, the range will start at the first item:
Example
This example returns the items from the beginning to, but NOT including, "kiwi":
By leaving out the end value, the range will go on to the end of the list:
Example
print(thislist[2:])
Specify negative indexes if you want to start the search from the end of the list:
Example
This example returns the items from "orange" (-4) to, but NOT including "mango" (-1):
Example
Example
To change the value of items within a specific range, define a list with the new values, and refer
to the range of index numbers where you want to insert the new values:
Example
Change the values "banana" and "cherry" with the values "blackcurrant" and "watermelon":
print(thislist)
28
Insert Items
To insert a new list item, without replacing any of the existing values, we can use
Example
Note: As a result of the example above, the list will now contain 4 items.
Append Items
To add an item to the end of the list, use the append() method:
Example
thislist.append("orange")
print(thislist)
Extend List
To append elements from another list to the current list, use the extend() method.
Example
You can assign a list, or part of it, to a variable. If you write userAge2 = userAge, the variable
If you write userAge3 = userAge[2:4], you are assigning items withindex 2 to index 4-1 from
the list userAge to the list userAge3. In other words, userAge3= [23, 24].
Example
Remove "banana":
If there are more than one item with the specified value, the remove() method removes the first
occurance:
29
Example
Example
If you do not specify the index, the pop() method removes the last item.
Example
del
myList = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’, ‘i’,‘j’, ‘k’, ‘l’]
30
Example
reverse()
myList = [1, 2, 3, 4]
myList.reverse()
print (myList)
#[4, 3, 2, 1]
sort()
Addition Operator: +
Concatenate List[Example]
Multiplication Operator: *
Note: The + and * symbols do not modify the list. The list stays as [‘a’, ‘b’,‘c’, ‘d’] in both cases.
You can loop through the list items by using a for loop:
Example
31
PYTHON TUPLE
Tuples are used to store multiple items in a single variable. Tuples are just like lists, but you cannot
modify their values. The initial values are the values that will stay for the rest of the program.
An example where tuples are useful is when your program needs to store the names of the
To declare a tuple, you write tupleName = (initial values). Notice that we use round brackets
Example:
monthsOfYear = (“Jan”, “Feb”, “Mar”, “Apr”, “May”,
“Jun”, “Jul”, “Aug”, “Sep”, “Oct”, “Nov”, “Dec”)
Tuple Items
Tuple items are indexed, the first item has index [0], the second item has index [1] etc.
Ordered
When we say that tuples are ordered, it means that the items have a defined order, and that order
Unchangeable
Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple
Allow Duplicates
Since tuples are indexed, they can have items with the same value:
Example
Tuple Length
To determine how many items a tuple has, use the len() function:
Example
32
Example
Example
You can access tuple items by referring to the index number, inside square brackets:
Example
Negative Indexing
-1 refers to the last item, -2 refers to the second last item etc.
Example
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 tuple with the specified items.
Example
By leaving out the start value, the range will start at the first item:
Example
This example returns the items from the beginning to, but NOT included, "kiwi":
33
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[: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:
Specify negative indexes if you want to start the search from the end of the tuple:
Example
This example returns the items from index -4 (included) to index -1 (excluded)
Example
Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as
it also is called. But there is a workaround. You can convert the tuple into a list, change the list, and
Example
Add Items
Since tuples are immutable, they do not have a built-in append() method, but there are other ways
34
Convert into a list: Just like the workaround for changing a tuple, you can convert it into a list,
Example
Convert the tuple into a list, add "orange", and convert it back into a tuple:
Remove Items
Tuples are unchangeable, so you cannot remove items from it, but you can use the same
Example
Convert the tuple into a list, remove "apple", and convert it back into a tuple:
You can loop through the tuple items by using a for loop.
Example
Example
PYTHON DICTIONARY
A dictionary is a collection of related data pairs which is ordered, changeable and do not allow
duplicates. For instance, if we want to store the username and age of 5 users, we can store
them in a dictionary. Dictionaries are written with curly brackets, and have keys and values,
35
To declare a dictionary, you write dictionaryName = {dictionary key : data}, with the
requirement that dictionary keys must be unique(within one dictionary). That is, you cannot
Example:
userNameAndAge = {“Peter”:38,
“John”:51,
“Alex”:13,
“Alvin”:“Not Available”
}
print(userNameAndAge)
Dictionary Items
Dictionary items are ordered, changeable, and does not allow duplicates.
Dictionary items are presented in key:value pairs, and can be referred to by using the key name.
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"]) #ford
Ordered or Unordered?
As of Python version 3.7 & 3.8, dictionaries are ordered. In Python 3.6 and earlier, dictionaries
are unordered. When we say that dictionaries are ordered, it means that the items have a defined
order, and that order will not change. Unordered means that the items does not have a defined
Changeable
Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
36
}
print(thisdict)
Dictionary Length
To determine how many items a dictionary has, use the len() function:
Example
print(len(thisdict)) #3
Example
thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
}
Accessing Items
You can access the items of a dictionary by referring to its key name, inside square brackets:
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]//Mustang
There is also a method called get() that will give you the same result:
Example
x = thisdict.get("model")
Get Keys
The keys() method will return a list of all the keys in the dictionary.
37
Example
x = thisdict.keys()
The list of the keys is a view of the dictionary, meaning that any changes done to the dictionary
Get Values
The values() method will return a list of all the values in the dictionary.
Example
x = thisdict.values()
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
Change Values
You can change the value of a specific item by referring to its key name:
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
38
Update Dictionary
The update() method will update the dictionary with the items from the given argument. The
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"year": 2020})
Adding Items
Adding an item to the dictionary is done by using a new index key and assigning a value to it:
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"color": "red"})
Removing Items
Example
The pop() method removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
39
Example
The popitem() method removes the last inserted item (in versions before 3.7 & 3.8, a random item
is removed instead):
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)
The del keyword removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict) #{}
You can loop through a dictionary by using a for loop. When looping through a dictionary, the
return value are the keys of the dictionary, but there are methods to return the values as well.
Example
You can use the keys() method to return the keys of a dictionary:
for x in thisdict.keys():
print(x)
brand
model
year
Example
You can also use the values() method to return values of a dictionary:
40
for x in thisdict.values():
print(x)
Ford
Mustang
1964
Example
Loop through both keys and values, by using the items() method:
for x, y in thisdict.items():
print(x, y)
brand Ford
model Mustang
year 1964
Making Your Program Interactive. Instead of just saying hello to the world, we want the world
to know our names and ages too. Inorder to do that, our program needs to be able to prompt
Two built-in functions can do that for us: input() and print().
Supposed you entered James. Now press Enter and it’ll prompt you foryour age.
Say you keyed in 20. Now press Enter again. You should get thefollowing statement:
Input ()
In the example above, we used the input() function twice to get our user’s name and age.
Print()
The print() function is used to display information to users. It acceptszero or more expressions
print ("Hello World, my name is", myName, "and I am",myAge, "years old.")
The next is the variable myName declared using the input function earlier. Next is the string
“and I am”, followed by the variable myAge and finally the string “years old.”.
Note that we do not use quotation marks when referring to the variables myName and myAge.
41
If you use quotation marks, you’ll get the output
Another way to print a statement with variables is to use the % formatter. To achieve the same
PYTHON MATH
The min() and max() functions can be used to find the lowest or highest value in an iterable:
Example
x = min(5, 10, 25)
y = max(5, 10, 25)
print(x) #5
print(y) #25
The abs() function returns the absolute (positive) value of the specified number:
Example
x = abs(-7.25)
print(x)#7.25
Example
x = pow(4, 3)
print(x) #64
import math
When you have imported the math module, you can start using methods and constants of the
module.
The math.sqrt() method for example, returns the square root of a number:
Example
import math
x = math.sqrt(64)
print(x) #8
42
PYTHON CONDITIONS AND IF STATEMENTS
Equals: a == b
Not Equals: a != b
These conditions can be used in several ways, most commonly in "if statements" and loops.
Example
If statement:
a = 33
b = 200
if b > a:
print("b is greater than a")
Elif
The elif keyword is Python's way of saying "if the previous conditions were not true, then try this
condition".
Example
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
Else
The else keyword catches anything which isn't caught by the preceding conditions.
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
43
You can also have an else without the elif:
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
And
The and keyword is a logical operator, and is used to combine conditional statements:
Example
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
Or
Example
a = 200
b = 33
c = 500
if a > b or a > c:
Not
The not keyword is a logical operator, and is used to reverse the result of the conditional statement:
Example
a = 33
b = 200
if not a > b:
print("a is NOT greater than b")
Nested If
You can have if statements inside if statements, this is called nested if statements.
44
Example
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
# Above ten,
# and also above 20!
PYTHON LOOPS
while loops
for loops
With the while loop we can execute a set of statements as long as a condition is true.
Example
i=1
while i < 6:
print(i)
i += 1
a=1
while a < 10:
print('The value of a is ',a)
a=a+1
print("I am done")
With the break statement we can stop the loop even if the while condition is true:
Example
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
45
The continue Statement
With the continue statement we can stop the current iteration, and continue with the next:
Example
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)
With the else statement we can run a block of code once when the condition no longer is true:
Example
i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, or a string).
This is less like the for keyword in other programming languages, and works more like an iterator
method as found in other object-orientated programming languages. With the for loop we can
execute a set of statements, once for each item in a list, tuple, etc.
Example
for x in fruits:
print(x)
Note: The for loop does not require an indexing variable to set beforehand.
Example
for x in "banana":
print(x)
46
my_str = “python”
for char in my_str:
if char==”o”:
break
print(char)
To loop through a set of code a specified number of times, we can use the range() function,
The range() function returns a sequence of numbers, starting from 0 by default, and increments by
Example
for x in range(6):
print(x)
The range() function defaults to 0 as a starting value, however it is possible to specify the starting
value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6):
Example
The range() function defaults to increment the sequence by 1, however it is possible to specify the
Example
The else keyword in a for loop specifies a block of code to be executed when the loop is finished:
Example
Print all numbers from 0 to 5, and print a message when the loop has ended:
for x in range(6):
print(x)
else:
print("Finally finished!")
47
PYTHON FUNCTIONS
A function is a block of code which only runs when it is called. You can pass data, known as
Creating a Function
Example
def my_function():
Calling a Function
Example
def my_function():
print("Hello from a function")
my_function()
Arguments
Information can be passed into functions as arguments. Arguments are specified after the function
name, inside the parentheses. You can add as many arguments as you want, just separate them
with a comma. The following example has a function with one argument (fname). When the
function is called, we pass along a first name, which is used inside the function to print the full
name:
Example
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Number of Arguments
By default, a function must be called with the correct number of arguments. Meaning that if your
function expects 2 arguments, you have to call the function with 2 arguments, not more, and not
less.
Example
48
Keyword Arguments
You can also send arguments with the key = value syntax.
Example
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")
The following example shows how to use a default parameter value. If we call the function
Example
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Return Values
Example
def add(x, y):
sum = x + y
return sum
print(add(5, 7))
Example
with its properties and methods. A Class is like an object constructor, or a "blueprint" for creating
objects.
49
Create a Class
Example
class MyClass:
x=5
Create Object
Example
p1 = MyClass()
print(p1.x)
The examples above are classes and objects in their simplest form, and are not really useful in real
life applications. To understand the meaning of classes we have to understand the built-in
__init__() function. All classes have a function called __init__(), which is always executed when the
Use the __init__() function to assign values to object properties, or other operations that are
Example
Create a class named Person, use the __init__() function to assign values for name and age:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
Note: The __init__() function is called automatically every time the class is being used to create a
new object.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
print("My name is {} and I am {} years old".format(self.name, self.age))
p1 = Person("John", 36)
50
Object Methods
Objects can also contain methods. Methods in objects are functions that belong to the object.
Example
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
Python Inheritance
Inheritance allows us to define a class that inherits all the methods and properties from another
class.
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived class
Any class can be a parent class, so the syntax is the same as creating any other class:
Example
Create a class named Person, with firstname and lastname properties, and a printname method:
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
#Use the Person class to create an object, and then execute the printname method:
x = Person("John", "Doe")
x.printname()
Example
Create a class named Student, which will inherit the properties and methods from the Person class:
51
class Student(Person):
pass
Note: Use the pass keyword when you do not want to add any other properties or methods to the
class.
Now the Student class has the same properties and methods as the Person class.
Example
Use the Student class to create an object, and then execute the printname method:
x = Student("Mike", "Olsen")
x.printname()
By using the super() function, you do not have to use the name of the parent element, it will
Add Properties
Example
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
self.graduationyear = 2019
x = Student("Mike", "Olsen")
print(x.graduationyear)
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
52
Add Methods
Example
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
def welcome(self):
print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)
53