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

CSC201 Python 092740

Uploaded by

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

CSC201 Python 092740

Uploaded by

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

MODIBBO ADAMA UNIVERSITY, YOLA

FACULTY OF PHYSICAL SCIENCES


DEPARTMENT OF COMPUTER SCIENCE

LECTURE NOTE
(First Part)

COURSE TITLE: COMPUTER PROGRAMMING I

COURSE CODE: CSC201

Course Lecturer: Mr. I. H. Ibrahim

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.

Programming is the process of writing programs.

LEVELS OF PROGRAMMING LANGUAGES

Programs and programming languages have been in existence since the invention of computers,

and there are three levels of programming languages. These are:

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

of the machine language were:

 Coding in machine language was a very tedious and boring job

 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

program instruction from the beginning to the end.

The advantage of machine language is that it requires no translation since it is already in machine

language and is therefore faster to execute.

Low Level Language

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

into machine language. An example of assembly language statement is:

MOVE A1, A2 → Move the contents of Register A2 to A1

JMP b →Go to the process with label b

The disadvantages of assembly language are that:

 It is specific to particular machines

 It requires a translator called an assembler.

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.

High Level Language

This programming language consists of English-like codes. High-level language is independent of

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

language to the other.

Some advantages of high-level language:

 It is more user friendly, that is, easy to learn and write

 It is very portable, that is, it can be used on almost any computer

 It saves much time and effort when used compared to any other programming level

language.

 Codes written in this language can easily be debugged

FEATURES OF PROGRAMMING LANGUAGES

There are some conventional features which a programming language must possess, these features

are:

 It must have syntactic rules for forming statements.

 It must have a vocabulary that consists of letters of the alphabet.

 It must have a language structure, which consists of keywords, expressions and statements.

 It may require a translator before it can be understood by a computer.

 Programming languages are written and processed by the computer for the purpose of

communicating data between the human being and the computer.

CHARACTERISTICS OF PROGRAM

Here are some desirable characteristics of program

 Integrity: Refer to the accuracy of the 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

things as simple as possible, consistent with the overall program objectives.

 Efficiency: It is concerned with the execution speed and efficient memory utilization.

 Modularity: Many program can be decomposed into an independent procedures or

modules.

2
 Generality: Program must be as general as possible.

PROGRAM DESIGN PROCESS

 Problem Solving Phase: Creates an algorithm that solves the problem

 Implementation (Coding) Phase: Translates the algorithm into a programming language

DIFFERENCE BETWEEN ALGORITHM AND PROGRAM

 A program is an implementation of an algorithm to be run on a specific computer and

operating system.

 An algorithm is more abstract – it does not deal with machine specific details – think of it as

a method to solve a problem.

 What is good algorithm? Efficient algorithms are good, we generally measure efficiency of

an algorithm on the basis of:

 Time: algorithm should take minimum time to execute.

 Space: algorithm should use less memory.

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

comparisons. Aim of a particular Program is to obtain solution to a given problem.

We can design a program by going through the following first four major steps:

1. Analyze the program.

2. Design a solution/Program

3. Code/Enter the program

4. Test the program

5. Evaluate the solution

 Analyze the program: When we analyze a problem, we think about the requirements of the

program and how the program can be solved.

 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

suitable programming language.

 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.

Here are some more points to be considered while designing a program.

 Use of procedures.

 Choice of variable names.

 Documentation of program

 Debugging program

 Testing

 Procedures: is a part of code used to carry out independent task. Separate

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

eventually programs readable and modular.

 Choice of variable: We can make programs more meaningful and easier to

understand by choosing appropriate variable and constant names. For example: if

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

 Documentation of Program: Brief and accurate comments can be included at the

beginning of each procedure/function. Program should be documented so that it

can be used easily by the other people unfamiliar with the working and input

requirements of the program. Thus documentation will specify what response it

requires from the user during execution.

 Debugging the Program: It is expected that one should carry out number of tests

during implementation of algorithm, to ensure that the program is behaving

correctly according to its specifications. The program may have some logical

errors, which may not be detected during compilation.

To detect such type of errors we may print computed values at various steps

involved in algorithm. We should always manually execute the program by hand

before ever attempting to execution it on machine.

 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

possible problem, whether it may not be possible or necessary to write programs

that handle all input conditions, all the time. Whenever possible, programs should

be accomplished by input and output section.

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.

Examples of a translator are:

 Assembler: This is a program that converts programs written in assembly or low-level

language to 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

the next instruction.

FEATURES OF TRANSLATORS

 They exist to make programs understandable by the computer

 There exist different translators for different levels and types of programming languages

 Without them, the programs cannot be executed.

INTRODUCTION TO PYTHON

 Python is one of the most widely used user-friendly programming languages. It is an open-

source and easy to learn programming language.

 Python is an object-oriented, high level language, interpreted, dynamic and multipurpose

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

we can write a=10 to declare an integer value in a variable.

 Python makes the development and debugging fast because there is no compilation step

included in python development

HISTORY

 Python was first introduced by Guido Van Rossum in 1991 at the National Research

Institute for Mathematics and Computer Science, Netherlands.

 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

(CWI) in the Netherlands.

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.

 Python is influenced by programming languages like: ABC language, Modula-3, Python is

used for software development at companies and organizations such as Google, Yahoo,

CERN, Industrial Light and Magic, and NASA.

 Why the Name Python?

 Python developer, Rossum always wanted the name of his new language to be short,

unique, and mysterious.

 Inspired by Monty Python’s Flying Circus, a BBC comedy series, he named it Python.

PYTHON VERSION LIST

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

is Python 3.11 which was released in 2022.

FEATURES

There are a lot of features provided by python programming language as follows:

1. Easy to Code:

 Python is a very developer-friendly language which means that anyone and everyone can

learn to code it in a couple of hours or days.

 As compared to other object-oriented programming languages like Java, C, C++, and C#,

Python is one of the easiest to learn.

2. Open Source and Free:

 Python is an open-source programming language which means that anyone can create and

contribute to its development.

 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

system, be it Windows, Mac or Linux.

3. Support for GUI:

 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

programs to be efficient in the long run.


6
5. Highly Portable:

 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

to worry about changing the code.

 This is not possible in other programming languages, thus making Python one of the most

portable languages available in the industry.

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

during coding, thus saving time and increasing efficiency.

7. Large Standard Library:

 Out of the box, Python comes in built with a large number of libraries that can be

imported at any instance and be used in a specific program.

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

 Having downloaded the Python distribution now execute it.

RUNNING PYTHON PROGRAM

Using IDLE (Python GUI) to Execute Python Program:

 Another useful method of executing the Python code. Use the Python IDLE GUI Shell to

execute the Python program on Windows system.

 In Python, IDLE stands for "Integrated Development and Learning Environment." It is an

integrated development environment (IDE) that comes bundled with the Python

7
programming language. IDLE provides a graphical user interface (GUI) for writing,

executing, and debugging Python code.

 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

execute Python statements and see the results immediately.

 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

like the image given below.

 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 to overcome program from any bad issues.

 Debugging is a healthier process for the program and keeps the diseases bugs far away.

 The process of removing errors from a program is called Debugging.

ERRORS IN PYTHON PROGRAM

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

if x == 5 # Missing colon at the end of the line


print("x is equal to 5")

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

print("Hello World" # Missing closing parenthesis

Runtime Errors:

 The second type of error is a runtime error, so called because the error does not appear

until after the program has started running.

 These errors are also called exceptions because they usually indicate that something

exceptional (and bad) has happened.

 Some examples of Python runtime errors:

 division by zero

 performing an operation on incompatible types

 using an identifier which has not been defined

 accessing a list element, dictionary value or object attribute which doesn’t exist

Example

“Hello” – 1, “Hello”/123, “Hello” * “Hello”

radius = 5
area = 3.14 * r * r # Incorrect variable name 'r' instead of 'radius'
print ("Area:", area)

Semantic Errors:

 An error, which occurs due to improper use of statements in programming language.

 The problem is that the program you wrote is not the program you wanted to write. The

meaning of the program (its semantics) is wrong.

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

to mistake in the logic of the program.

 Unlike other errors logical errors are not displayed while interpreting because interpreter

does not understand the logic of the program.

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

program is successfully executed.

PYTHON COMMENTS

 Comments can be used to explain Python code.

 Comments can be used to make the code more readable.

 Comments can be used to prevent execution when testing code.

Creating a Comment

Comments starts with a #, and Python will ignore them:

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.

A variable is created the moment you first assign a value to it.

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

Single or Double Quotes?

String variables can be declared either by using single or double quotes:

Example
x = "John"
# is the same as
x = 'John'

Case-Sensitive

Variable names are case-sensitive.

Example

This will create two variables:

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,

total_volume). Rules for Python variables:

 A variable name must start with a letter or the underscore character

 A variable name cannot start with a number

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

 A variable name cannot be any of the Python keywords

Example

Legal variable names:

myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"

Example

Illegal variable names:

2myvar = "John"
my-var = "John"
my var = "John"

Multi Words Variable Names


Variable names with more than one word can be difficult to read.

There are several techniques you can use to make them more readable:

Camel Case

Each word, except the first, starts with a capital letter:

myVariableName = "John"

Pascal Case

Each word starts with a capital letter:

MyVariableName = "John"

Snake Case

Each word is separated by an underscore character:

my_variable_name = "John"

Assign Multiple Values

Python allows you to assign values to multiple variables in one line:

Example
x, y, z = "Orange", "Banana", "Cherry"

One Value to Multiple Variables

And you can assign the same value to multiple variables in one line:

Example
x = y = z = "Orange"
13
Output Variables

The Python print() function is often used to output variables.


Example
x = "Python is awesome"
print(x)

In the print() function, you output multiple variables, separated by a comma:

Example
x = "Python"
y = "is"
z = "awesome"
print(x, y, z)

You can also use the + operator to output multiple variables:

Example
x = "Python "
y = "is "
z = "awesome"
print(x + y + z)

For numbers, the + character works as a mathematical operator:

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

Create a variable outside of a function, and use it inside the function

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,

global and with the original value.

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)

PYTHON DATA TYPES

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:

Text Type: str

Numeric Type: int, float

Sequence Type: list, tuple and range

Mapping Type: dict

Boolean Type: bool

None Type: NoneType

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 = "Hello World" str

x = 20 int

x = 20.5 float

x = ["apple", "banana", "cherry"] list

x = ("apple", "banana", "cherry") tuple

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.

To declare an integer in Python, simply write variableName =initial value

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.

To declare a float in Python, we write variableName = initial value

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

#convert from int to float:

a = float(x)

#convert from float to int:

b = int(y)

print(a) # 1.0

print(b) # 2

print(type(a)) #<class ‘float’>

print(type(b)) #<class ‘int’>

To change a string to an integer, we can type int (“4”) and we’ll get 4. However, we cannot type

int (“Hello”) or int (“4.22321”). We’ll get an error in both cases.

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

type str(2.1), we’ll get “2.1”.

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

variableName = “initial value”(double quotes)

Example:

userName = ‘Peter’, userSpouseName = “Janet”

You can display a string literal with the print() function:

Example

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

Strings are Arrays


Like many other popular programming languages, strings in Python are arrays of bytes

representing unicode characters. However, Python does not have a character data type, a single

character is simply a string with a length of 1.

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

Looping Through a String

Since strings are arrays, we can loop through the characters in a string, with a for loop.

Example

Loop through the letters in the word "banana":

for x in "banana":
print(x)

String Length

To get the length of a string, use the len() function.

Example

The len() function returns the length of a string:

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

# print only if "expensive" is NOT present:


txt = "The best things in life are free!"
if "expensive" not in txt:
print("No, 'expensive' is NOT present.")

Slicing

You can return a range of characters by using the slice syntax.

Specify the start index and the end index, separated by a colon, to return a part of the string.

18
Example

Get the characters from position 2 to position 5 (not included):

b = "Hello, World!"
print(b[2:5]) #llo

Slice From the Start

By leaving out the start index, the range will start at the first character:

Example

Get the characters from the start to position 5 (not included):

b = "Hello, World!"
print(b[:5])

Slice To the End

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

The upper() method returns the string in upper case:

a = "Hello, World!"
print(a.upper())

Lower Case
Example

The lower() method returns the string in lower case:

a = "Hello, World!"
print(a.lower())

Replace String
Example

The replace() method replaces a string with another string:

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

Merge variable with a variable b into variable c:

a = "Hello"
b = "World"
c=a+b
print(c)

Example

To add a space between them, add a " ":

a = "Hello"
b = "World"
c=a+""+b
print(c)

String find() Method


Example

Where in the text is the word "welcome"?:

txt = "Hello, welcome to my world."


x = txt.find("welcome")
print(x) # return 7

Definition and Usage

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"?:

txt = "Hello, welcome to my world."


x = txt.find("e")
print(x)#1
Example

Where in the text is the first occurrence of the letter "e" when you only search between position 5
and 10?

txt = "Hello, welcome to my world."


x = txt.find("e", 5, 10)
print(x) #8

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

the format() method:

Example

Use the format() method to insert numbers into strings:

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

Format the price to be displayed as a number with two decimals:

txt = "The price is {:.2f} dollars"

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

in the correct placeholders:

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

otherwise have a different meaning.

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

print (‘Hello\tWorld), you’ll get Hello World

Example
You will get an error if you use double quotes inside a string that is surrounded by double quotes:

txt = "We are the so-called "Vikings" from the north."

To fix this problem, use the escape character \":

Example
The escape character allows you to use double quotes when you normally would not be allowed:

txt = "We are the so-called \"Vikings\" from the north."

22
Escape Characters

Other escape characters used in Python:

Code Result Example

\' Single Quote txt = 'It\'s alright.'

\\ Backslash txt = "This will insert one \\ (backslash)."

\n New Line txt = "Hello\nWorld!"

\r Carriage Return txt = "Hello\rWorld!"

\t Tab txt = "Hello\tWorld!"

\b Backspace txt = "Hello \bWorld!"

Python Booleans

Booleans represent one of two values: True or False.

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,

the expression is evaluated and Python returns the Boolean answer:

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

When you run a condition in an if statement, Python returns True or False:

Example

Print a message based on whether the condition is True or False:

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

the + operator to add together two values:

Example
print(10 + 5)

Python divides the operators in the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
23
 Membership operators

Python Arithmetic Operators

Arithmetic operators are used with numeric values to perform common mathematical operations:

Operator Name Example

+ Addition x+y

- Subtraction x-y

* Multiplication x*y

/ Division x/y

% Modulus x%y

** Exponentiation x ** y

// Floor division (Round down to nearest whole x // y

number: E.g. 15//2 = 7)

Python Assignment Operators

Assignment operators are used to assign values to variables:

Operator Example Same As

= 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

Python Comparison Operators

Comparison operators are used to compare two values:

== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

24
Python Logical Operators

Logical operators are used to combine conditional statements:

Operator Description Example

and Returns True if both x < 5 and x < 10

statements are true

or Returns True if one of the x < 5 or x < 4

statements is true

not Reverse the result, returns not(x < 5 and x < 10)

False if the result is true

Python Membership Operators

Membership operators are used to test if a sequence is presented in an object:

Operator Description Example

in Returns True if a sequence with x in y

the specified value is present in

the object

x = ["apple", "banana"]

print("banana" in x) //True

not in Returns True if a sequence with x not in y

the specified value is not present

in the object

x = ["apple", "banana"]

print("pineapple" not in x)//True

Operator Precedence

Operator precedence describes the order in which operations are performed.

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

from left to right:

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

user5Age, it makes more sense to store them as a list.

To declare a list, you write listName = [initial values]. Note that we use square brackets [ ]

when declaring a list. Multiple values areseparated by a comma.

Example:
userAge = [21, 22, 23, 24, 25]

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

List Items

List items are ordered, changeable, and allow duplicate values.

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

will not change.

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:

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

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

List items can be of any data type:

Example

String, int and boolean data types:

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


list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]

A list can contain different data types:

Example

A list with strings, integers and boolean values:

list1 = ["abc", 34, True, 40, "male"]

Access Items

List items are indexed and you can access them by referring to the index number:

Example

Print the second item of the list:

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


print(thislist[1])

Note: The first item has index 0.

Negative Indexing
Negative indexing means start 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.

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":

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" 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 "orange" (-4) to, but NOT including "mango" (-1):

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


print(thislist[-4:-1])

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

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)

Change a Range of Item Values

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":

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

thislist[1:3] = ["blackcurrant", "watermelon"]

print(thislist)

28
Insert Items

To insert a new list item, without replacing any of the existing values, we can use

the insert() method.

The insert() method inserts an item at the specified index:

Example

Insert "watermelon" as the third item:

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


thislist.insert(2, "watermelon")
print(thislist)

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

Using the append() method to append an item:

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

thislist.append("orange")

print(thislist)

Extend List

To append elements from another list to the current list, use the extend() method.

Example

Add the elements of tropical to thislist:

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


tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)

You can assign a list, or part of it, to a variable. If you write userAge2 = userAge, the variable

userAge2 becomes [21, 22, 23, 24, 25].

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].

Remove Specified Item

The remove() method removes the specified item.

Example

Remove "banana":

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


thislist.remove("banana")
print(thislist)

If there are more than one item with the specified value, the remove() method removes the first

occurance:
29
Example

Remove the first occurance of "banana":

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


thislist.remove("banana")
print(thislist)

Remove Specified Index

The pop() method removes the specified index.

Example

Remove the second item:

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


thislist.pop(1)
print(thislist)

If you do not specify the index, the pop() method removes the last item.

Example

Remove the last item:

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


thislist.pop()
print(thislist)

del

Remove items from a list[Example]

myList = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’, ‘i’,‘j’, ‘k’, ‘l’]

#delete the third item (index = 2)


del myList[2]
print (myList)
# [‘a’, ‘b’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’, ‘i’, ‘j’, ‘k’, ‘l’]

#delete items from index 1 to 5-1


del myList[1:5]
print (myList)
# [‘a’, ‘g’, ‘h’, ‘i’, ‘j’, ‘k’, ‘l’]

#delete items from index 0 to 3-1


del myList [ :3]print (myList)
# [‘i’, ‘j’, ‘k’, ‘l’]

#delete items from index 2 to end


del myList [2:]
print (myList)
#[‘i’, ‘j’]

Clear the List

The clear() method empties the list.

The list still remains, but it has no content.

30
Example

Clear the list content:

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


thislist.clear()
print(thislist)#[]

reverse()

Reverse the items in a list[Example]

myList = [1, 2, 3, 4]
myList.reverse()
print (myList)
#[4, 3, 2, 1]

sort()

Sort a list alphabetically or numerically[Example]

myList = [3, 0, -1, 4, 6]


myList.sort()
print(myList)
# [-1, 0, 3, 4, 6]

Addition Operator: +

Concatenate List[Example]

myList = [‘a’, ‘b’, ‘c’, ‘d’]


print (myList + [‘e’, ‘f’])
# [‘a’, ‘b’, ‘c’, ‘d’,‘e’, ‘f’]

Multiplication Operator: *

Duplicate a list and concatenate it to the end of the list[Example]

myList = [‘a’, ‘b’, ‘c’, ‘d’]


print (myList*3)
# ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd', 'a', 'b', 'c', 'd']

Note: The + and * symbols do not modify the list. The list stays as [‘a’, ‘b’,‘c’, ‘d’] in both cases.

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)

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

months of the year.

To declare a tuple, you write tupleName = (initial values). Notice that we use round brackets

( ) when declaring a tuple. Multiple values are separated by a comma.

Example:
monthsOfYear = (“Jan”, “Feb”, “Mar”, “Apr”, “May”,
“Jun”, “Jul”, “Aug”, “Sep”, “Oct”, “Nov”, “Dec”)

Tuple Items

Tuple items are ordered, unchangeable, and allow duplicate values.

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

will not change.

Unchangeable

Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple

has been created.

Allow Duplicates

Since tuples are indexed, they can have items with the same value:

Example

Tuples allow duplicate values:

thistuple = ("apple", "banana", "cherry", "apple", "cherry")


print(thistuple)

Tuple Length

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

Example

Print the number of items in the tuple:

thistuple = ("apple", "banana", "cherry")


print(len(thistuple)) #3

Tuple Items - Data Types


Tuple items can be of any data type:

32
Example

String, int and boolean data types:

tuple1 = ("apple", "banana", "cherry")


tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)

A tuple can contain different data types:

Example

A tuple with strings, integers and boolean values:

tuple1 = ("abc", 34, True, 40, "male")

Access Tuple Items

You can access tuple items by referring to the index number, inside square brackets:

Example

Print the second item in the tuple:

thistuple = ("apple", "banana", "cherry")


print(thistuple[1])

Negative Indexing

Negative indexing means start from the end.

-1 refers to the last item, -2 refers to the second last item etc.

Example

Print the last item of the tuple:

thistuple = ("apple", "banana", "cherry")


print(thistuple[-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 tuple with the specified items.

Example

Return the third, fourth, and fifth item:

thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")


print(thistuple[2:5])

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:

thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")


print(thistuple[2:])

Range of Negative Indexes

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)

thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")


print(thistuple[-4:-1])

Check if Item Exists

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

Example

Check if "apple" is present in the tuple:

thistuple = ("apple", "banana", "cherry")


if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")

Change Tuple Values

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

convert the list back into a tuple.

Example

Convert the tuple into a list to be able to change it:

x = ("apple", "banana", "cherry")


y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)

Add Items

Since tuples are immutable, they do not have a built-in append() method, but there are other ways

to add items to a tuple.

34
Convert into a list: Just like the workaround for changing a tuple, you can convert it into a list,

add your item(s), and convert it back into a tuple.

Example

Convert the tuple into a list, add "orange", and convert it back into a tuple:

thistuple = ("apple", "banana", "cherry")


y = list(thistuple)
y.append("orange")
thistuple = tuple(y)

Remove Items

Tuples are unchangeable, so you cannot remove items from it, but you can use the same

workaround as we used for changing and adding tuple items:

Example

Convert the tuple into a list, remove "apple", and convert it back into a tuple:

thistuple = ("apple", "banana", "cherry")


y = list(thistuple)
y.remove("apple")
thistuple = tuple(y)

Loop Through a Tuple

You can loop through the tuple items by using a for loop.

Example

Iterate through the items and print the values:


thistuple = ("apple", "banana", "cherry")
for x in thistuple:
print(x)

Join Two Tuples

To join two or more tuples you can use the + operator:

Example

Join two tuples:

tuple1 = ("a", "b", "c")


tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)

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,

multiple pairs are separated by a comma.

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

declare a dictionary like this myDictionary = {“Peter”:38, “John”:51, “Peter”:13}.

This is because “Peter” is used as the dictionary key twice.

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

Print the "brand" value of the dictionary:

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

order, you cannot refer to an item by using an index.

Changeable

Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary

has been created.

Duplicates Not Allowed

Dictionaries cannot have two items with the same key:

Example

Duplicate values will overwrite existing values:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020

36
}
print(thisdict)

{'brand': 'Ford', 'model': 'Mustang', 'year': 2020}

Dictionary Length

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

Example

Print the number of items in the dictionary:

print(len(thisdict)) #3

Dictionary Items - Data Types

The values in dictionary items can be of any data type:

Example

String, int, and boolean, data types:

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

Get the value of the "model" key:

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

Get the value of the "model" key:

x = thisdict.get("model")

Get Keys

The keys() method will return a list of all the keys in the dictionary.

37
Example

Get a list of the keys:

x = thisdict.keys()

#dict_keys(['brand', 'model', 'year'])

The list of the keys is a view of the dictionary, meaning that any changes done to the dictionary

will be reflected in the keys list.

Get Values

The values() method will return a list of all the values in the dictionary.

Example

Get a list of the values:

x = thisdict.values()

# dict_values(['Ford', 'Mustang', 1964])

Check if Key Exists

To determine if a specified key is present in a dictionary use the in keyword:

Example

Check if "model" is present in the dictionary:

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

Change the "year" to 2018:

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

argument must be a dictionary, or an iterable object with key:value pairs.

Example

Update the "year" of the car by using the update() method:

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)

Add a color item to the dictionary by using the update() method:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"color": "red"})

Removing Items

There are several methods to remove items from a dictionary:

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

The clear() method empties the dictionary:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict) #{}

Loop Through a Dictionary

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

PYTHON USER INPUT

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

us for information and display them on the screen.

Two built-in functions can do that for us: input() and print().

myName = input("Please enter your name: ")


myAge = input("What about your age: ")
print ("Hello World, my name is", myName, "and I am",myAge, "years old.")

The program should prompt you for your name.

Please enter your name:

Supposed you entered James. Now press Enter and it’ll prompt you foryour age.

What about your age:

Say you keyed in 20. Now press Enter again. You should get thefollowing statement:

Hello World, my name is James and I am 20 years old.

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

as parameters, separated by commas. In the statement below, we passed 5 parameters to the

print() function. Can you identify them?

print ("Hello World, my name is", myName, "and I am",myAge, "years old.")

The first is the string ”Hello World, my name is”

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

Hello World, my name is myName and I am myAge yearsold.

Another way to print a statement with variables is to use the % formatter. To achieve the same

output as the first print statement above, we can write

print ("Hello World, my name is %s and I am %s years old." %(myName, myAge))

Also, to print the same statement using the format()method, we write

print (“Hello World, my name is {} and I am {} years old”.format(myName, myAge))

PYTHON MATH

Built-in Math Functions

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

The pow(x, y) function returns the value of x to the power of y (xy).

Example

Return the value of 4 to the power of 3 (same as 4 * 4 * 4):

x = pow(4, 3)
print(x) #64

The Math Module


Python has also a built-in module called math, which extends the list of mathematical functions.

To use it, you must import the math module:

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

Python supports the usual logical conditions from mathematics:

 Equals: a == b

 Not Equals: a != b

 Less than: a < b

 Less than or equal to: a <= b

 Greater than: a > b

 Greater than or equal to: a >= b

These conditions can be used in several ways, most commonly in "if statements" and loops.

An "if statement" is written by using the if keyword.

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

Test if a is greater than b, AND if c is greater than a:

a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")

Or

The or keyword is a logical operator, and is used to combine conditional statements:

Example

Test if a is greater than b, OR if a is greater than c:

a = 200

b = 33

c = 500

if a > b or a > c:

print("At least one of the conditions is True")

Not

The not keyword is a logical operator, and is used to reverse the result of the conditional statement:

Example

Test if a is NOT greater than b:

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

Python has two primitive loop commands:

 while loops

 for loops

The while Loop

With the while loop we can execute a set of statements as long as a condition is true.

Example

Print i as long as i is less than 6:

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

The break Statement

With the break statement we can stop the loop even if the while condition is true:

Example

Exit the loop when i is 3:

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

Continue to the next iteration if i is 3:

i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)

The else Statement

With the else statement we can run a block of code once when the condition no longer is true:

Example

Print a message once the condition is false:

i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")

Python For Loops

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

Print each fruit in a fruit list:

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

for x in fruits:

print(x)

Note: The for loop does not require an indexing variable to set beforehand.

Looping Through a String


Even strings are iterable objects, they contain a sequence of characters:

Example

Loop through the letters in the word "banana":

for x in "banana":
print(x)

46
my_str = “python”
for char in my_str:
if char==”o”:
break
print(char)

The range() Function

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

1 and ends at a specified number.

Example

Using the range() function:

for x in range(6):
print(x)

Note that range(6) is not the values of 0 to 6, but the values 0 to 5.

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

Using the start parameter:

for x in range(2, 6):


print(x)

The range() function defaults to increment the sequence by 1, however it is possible to specify the

increment value by adding a third parameter: range(2, 30, 3):

Example

Increment the sequence with 3 (default is 1):

for x in range(2, 30, 3):


print(x)

Else in For Loop

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

parameters, into a function. A function can return data as a result.

Creating a Function

In Python a function is defined using the def keyword:

Example
def my_function():

print("Hello from a function")

Calling a Function

To call a function, use the function name followed by parenthesis:

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

This function expects 2 arguments, and gets 2 arguments:

def my_function(fname, lname):


print(fname + " " + lname)
my_function("Emil", "Refsnes")

48
Keyword Arguments

You can also send arguments with the key = value syntax.

This way the order of the arguments does not matter.

Example
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")

Default Parameter Value

The following example shows how to use a default parameter value. If we call the function

without argument, it uses the default value:

Example
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")

Return Values

To let a function return a value, use the return statement:

Example
def add(x, y):
sum = x + y
return sum
print(add(5, 7))

Create a function with if and else

Example

def printMax(a, a):


if a > b:
print(a, “is maximum”)
else:
print(b, “is maximum”)
printMax(9, 5) #directly give literal value
x, y = 5, 7
printMax(x, y) #give variable as argument

PYTHON CLASSES AND OBJECTS

Python is an object oriented programming language. Almost everything in Python is an object,

with its properties and methods. A Class is like an object constructor, or a "blueprint" for creating

objects.

49
Create a Class

To create a class, use the keyword class:

Example

Create a class named MyClass, with a property named x:

class MyClass:
x=5

Create Object

Now we can use the class named MyClass to create objects:

Example

Create an object named p1, and print the value of x:

p1 = MyClass()
print(p1.x)

The __init__() Function

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

class is being initiated.

Use the __init__() function to assign values to object properties, or other operations that are

necessary to do when the object is being created:

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.

Let us create a method in the Person class:

Example

Insert a function that prints a greeting, and execute it on the p1 object:

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

Create a Parent 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

automatically inherit the methods and properties from its parent.

Add Properties
Example

Add a property called graduation year to the Student class:

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)

Add a property called graduation year as argument to the Student class

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

x = Student("Mike", "Olsen", 2019)


print(x.graduationyear)

52
Add Methods
Example

Add a method called welcome to the Student class:

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)

x = Student("Mike", "Olsen", 2019)


x.welcome()

# Welcome Mike Olsen to the class of 2019

53

You might also like