Python Lesson 1 and 2 Notes - Updated 1
Python Lesson 1 and 2 Notes - Updated 1
1 of 34
Contents
Algorithmn
An algorithm is a step-by-step procedure or a set of rules designed to solve a specific
problem or perform a specific task. It is essentially a blueprint or a recipe that
outlines how to achieve a particular goal in a logical and systematic manner. In other
words, an algorithmn is simply a solution to the problem.
Example of Algorithmn
For instance, if a programmer would like to write a computer program that would
create a Graphical User Interaface (GUI) as shown below:
Of course, this program allows user to input information. Thereafter, user clicks the
“Compute Payment” button and the program will caculate and display the calculated
answers on the GUI.
P. 3 of 34
1. init(self)
later
2. getMonthlyPayment(self)
3. computePayment(self)
Programming Environment
Once a programmer got algorithmn prepared, he/she should set up Programming
Environment before writing the computer program. The Programming Environment
usually involves the following 3 aspects:
➢ Text Editor
➢ Compiler
➢ Interpreter
Text Editor
A text editor is a software that allows you to write, edit and store computer programs
in files of text mode.
Compiler
As mentioned above, the computer programs are stored in files of text mode.
Unfortunately, the computer is not possible to realize the program directly written in
text mode, so we have to convert the text file to a binary one, which can be
understood and interpreted by the computer.
In such case, the Compiler is a kind of software, which will be used to convert those
text-based programs to binary format files. And this process is also known as
program compilation.
Interpreter
As mentioned above, compilers are required by the time we are going to write
computer program in a programming language that would be compiled to binary
format before execution.
Please also be aware that some programming languages such as Python, PHP, and
Perl, which do not need any compilation into binary format. Thus, an interpreter can
be used directly to read such programs line by line. Thereafter, execute them directly
without any further conversion. Please refer to the following figure for reference:
Computer Execute
Program File Interpreter Program
(text based)
P. 6 of 34
You may download the Python IDLE via the following URL:
https://www.python.org/
Please be reminded that we are are going to use Python 3.XX or above version
throughout this course. After installation, we are going to create the first Python
program which can help you realize the usage of Python IDLE.
What is Python?
Python is a interactive, object-oriented and high-level programming language which
is easy to learn.
With Python, you not only can create text-based application, but also write GUI
Programming, Drawing or Database connection programs. You can also use it to
create web applications.
P. 7 of 34
To begin with, start running IDLE through Start button by Python 3.12 -> IDLE
(Python 3.12 64-bit).
P. 8 of 34
print("Hello World!")
To save the above code in file, simply click File -> Save. And name the file as First.py.
P. 9 of 34
Now, back to the Shell window, you will see “Hello World!” is printed out there.
P. 10 of 34
Elaboration of First.py
1. The print() Function:
✓ The print() function in Python is used to display output on the screen.
✓ It takes one or more arguments (text, numbers, variables, etc.) and outputs
them in the console or terminal.
✓ In this case, the argument passed to the print() function is "Hello World!".
3. Output:
✓ When the print() function is executed, it displays the string "Hello World!"
in the terminal or output window.
Practice 1
1. Create a new Python script file called classwork.py.
2. Write code for printing “I love Python !”
3. Run the above script file
P. 11 of 34
Data types
For data type, it represents the type of data which will be processed within
computer program. In Python, there are 5 standard data types:
✓ Numbers
✓ Strings
✓ List
✓ Tuple
✓ Dictionary
For Numbers in Python, it specifies all types of numbers including decimal numbers.
And Strings in Python represents a sequence of characters with a length of 1 or even
more characters.
At this moment, we will elaborate on Numbers and Strings first. The List, Tuple and
Dictionary are actually advanced data types in Python. We will proceed to them in a
little bit future moment.
P. 12 of 34
Variables
A variable is something which can be altered. It is a way of referring to a memory
location used by a computer program. A variable is a symbolic name for this physical
location. This memory location contains values, such as numbers, text or more
complicated types. We can use this variable to tell the computer save some data in
this location or to retrieve some data from this location.
A variable can also be seen as a container for storing certain values. While the
program is running, variables are accessed and sometimes changed, i.e. a new value
may be assigned to a variable.
One of the main differences between Python and strongly-typed languages like C,
C++ or Java is the way it deals with types. In strongly-typed languages, every variable
must have a unique data type. For instance, if a variable is of type integer, solely
integers can be saved in the variable during the duration of the the program. Besides,
In Java or C, every variable has to be declared before it can be used. Declaring a
variable means binding it to a data type.
i=38
Notice that the equal "=" sign in the above assignment statement shouldn't be seen
as "is equal to". It should be "read" or interpreted as "is set to", meaning in our
example "the variable i is set to 38".
P. 13 of 34
All right, we can increase the value of variable i by 1 and then print out the updated
value:
variableDemo.py
i=38
i=i+1
print (i)
ch = input("")
Elaboration of variableDemo.py
1. Variable Initialization:
i = 38
➢ This line creates a variable i and assigns it the integer value 38.
➢ At this point, i holds the value 38.
➢ The input() function pauses the program and waits for the user to enter some
input.
➢ Whatever the user types (followed by pressing Enter) is captured as a string
and stored in the variable ch.
➢ The "" inside input() is an empty string, meaning no prompt or message will
be displayed to the user before taking the input.
5. End of Program:
➢ After the user provides input, the program ends. The value entered by the
user is stored in the variable ch, but there are no further operations
performed on it in this code.
P. 15 of 34
print("Method 1")
print(name, "has got", marks, ".")
print("This student has a ranking of", rank, ".")
print()
print("Method 2")
print(name, " has got ", marks, ".", sep="")
print("This student has a ranking of ", rank, ".", sep="")
print()
print("Method 3")
print(name + " has got " + str(marks) + ".")
print("This student has a ranking of " + str(rank) + ".")
print()
print("Method 4")
print("%s has got %f marks." %(name, marks))
print("This student has a ranking of %d." %rank)
print()
print("Method 5")
print("%s has got %.1f marks." %(name, marks))
print("This student has a ranking of %d." %rank)
P. 16 of 34
ch = input("")
Notice that you may select any methods to print out variables. The choice is yours.
The only thing that needs concern is you have to regulate the print() to best fit your
preference of output.
P. 17 of 34
Elaboration of variableDemos2.py
This program demonstrates 5 different methods of printing formatted output in
Python. Let’s break it down step by step:
1. Variable Initialization
rank = 10 # An integer assignment
marks = 86.3 # A floating point
name = "Bibi" # A string
Output of Method 1:
P. 18 of 34
Output of Method 2:
Output of Method 3:
P. 19 of 34
Output of Method 4:
➢ Similar to Method 4, but the %.1f format specifier limits the floating-point
number to 1 decimal place.
Output of Method 5:
P. 20 of 34
When the input() function is called, the text of the prompt string will first be printed
on the screen. At this moment, the program flow will be stopped until the user has
given an input and ended the input with the return key.
The input of the user will be returned as a string without any changes. If this raw
input has to be transformed into another data type needed by the algorithm, we can
use either a casting function or the eval function.
ch = input("")
Elaboration of inputDemo.py
This code demonstrates how to interact with the user using input() for taking user
input and print() for displaying messages. Let’s break it down step by step:
➢ The input() function displays the prompt "What is your name? " and waits for
the user to type their name.
➢ Once the user presses Enter, their input is stored as a string in the variable
name.
➢ The input() function displays the prompt "How old are you? " and waits for
the user to type their age.
➢ Whatever the user types (e.g., 25) is stored as a string in the variable age.
P. 22 of 34
➢ The print() function displays a response that includes the user's age.
➢ The + operator is used to concatenate the string "That's great! At the age of "
with the value stored in age and the additional string " is good!".
Type Casting
The above program works fine for collecting all the input in string type and then print
them out on console directly.
But how about we would like to calculate the age of the user after 16 years and put
the age on the console? You may refer to the following figure for reference.
P. 23 of 34
The above output can be created by the Python program, inputAndAge.py as shown
below:
newAge = age + 16
ch = input("")
Refer to the program, you can see that we have to cast the age collected from user to
integer type. This is done by utilizing the int(). Note that Python allows data type of a
variable being altered within the program. The age variable is changed from string
type to integer type. And this situation is also known as type casting.
Another stuff that worths attention is the use of \n in the string while calling the
print(). It is called the Escape Character which aims at creating a new line within the
string.
P. 24 of 34
These conditions, mostly in the form of if statements, are one of the essential
features of a programming language and Python is no exception.
A decision has to be made when the script or program comes to a point where it has
a choice of actions. For example, different computations to choose from.
if statements
The simplest form of an if statement in Python looks like this:
if conditional ststement:
statement to be executed
statement to be executed
# ... some more indented statements if necessary
P. 25 of 34
if nationality == "JAPANESE":
print("\nKonichiwa!")
if nationality == "AMERICAN":
print("\nGood afternoon!")
ch = input("")
Be aware that in the conditional statement, we use operator == to check if the values
of two operands are equal or not, if yes then condition becomes true.
Another operator != to check if the values of two operands are equal or not. In case
the values are not equal, then condition becomes true.
P. 26 of 34
Elaboration of ifDemo.py
This code demonstrates how to take user input, process it using a built-in string
function (upper()), and use conditional statements (if) to provide appropriate
responses based on the input.
➢ The upper() method is a built-in string function that converts all characters
in the string to uppercase.
✓ For example:
◆ If the user types "Japanese", it is transformed to "JAPANESE".
◆ If the user types "american", it is transformed to "AMERICAN".
➢ This ensures that the program handles the input case-insensitively (e.g.,
"Japanese", "japanese", or "JAPANESE" will all be treated as "JAPANESE").
P. 27 of 34
Note: Both conditions are independent because they use two separate if
statements. If the input doesn't match either "JAPANESE" or "AMERICAN", no
message is printed.
P. 28 of 34
if condition_1:
statement_block_1
elif condition_2:
statement_block_2
...
elif another_condition:
another_statement_block
else:
else_block
Lets’s take an example to see how if and elif work together for solving problems.
P. 29 of 34
2. BMI Result
➢ <=15 (Under Weight)
➢ >15 and <=25 (Optimum Weight)
➢ Other results (Over Weight)
print("\n==================================\n")
Elaboration of bmi.py
Program bmi.py calculates the Body Mass Index (BMI) based on the user's weight
and height, then categorizes the result into 3 groups:
underweight
optimum weight
overweight
➢ The program prompts the user to input their weight (in kilograms) and height
(in meters).
➢ The input() function captures the user's input as a string.
✓ For example:
◆ If the user types 70 for weight, it is stored as the string "70".
◆ If the user types 1.75 for height, it is stored as the string "1.75".
➢ The float() function converts the string inputs (weight and height) into
floating-point numbers.
✓ For example:
◆ "70" becomes 70.0.
◆ "1.75" becomes 1.75.
3. Calculating BMI
bmi=(weight/(height**2))
➢ The program divides the input weight by the square of height (height**2).
Example Calculation:
➢ Suppose:
✓ weight = 70.0 kg
✓ height = 1.75 m
5. Printing a Divider
print("\n==================================\n")
6. Categorizing BMI
if bmi<=float(15):
print("You are under weight.")
elif bmi>float(15) and bmi<=float(25):
print("You are in Optimum weight.")
else:
print("You are over weight.")
✓ Optimum Weight: If bmi is greater than 15 but less than or equal to 25,
it prints:
You are in Optimum weight.
Practice 2
Try to write a Python program (StudentPerformance.py) that will analyze the
performance of a student based on the marks of a student.
If a student gets marks between 70 and 89, he/she is good. That means if the student
gets 70 or 89, he/she is still good.
If a student gets marks between 50 and 69, he/she is average. That means if the
student gets 50 or 69, he/she is still average