0% found this document useful (0 votes)
4 views34 pages

Python Lesson 1 and 2 Notes - Updated 1

The document provides an introduction to computer programming, focusing on Python as a programming language. It covers essential concepts such as algorithms, programming environments, data types, variables, and user input. Additionally, it includes practical examples and exercises to help learners create their first Python programs.

Uploaded by

gigicho0815
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views34 pages

Python Lesson 1 and 2 Notes - Updated 1

The document provides an introduction to computer programming, focusing on Python as a programming language. It covers essential concepts such as algorithms, programming environments, data types, variables, and user input. Additionally, it includes practical examples and exercises to help learners create their first Python programs.

Uploaded by

gigicho0815
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

P.

1 of 34

Contents

What is Computer Program? ......................................................................................... 2


Algorithmn ............................................................................................................. 2
Example of Algorithmn .................................................................................. 2
Programming Environment ............................................................................................ 4
Text Editor .............................................................................................................. 4
Compiler ................................................................................................................. 4
Interpreter .............................................................................................................. 5
Tools for learning Python – Python IDLE ........................................................................ 6
What is Python? ............................................................................................................. 6
Your first Python Program – Hello World ....................................................................... 7
Create Python code file .......................................................................................... 8
Insert code and save Python code file ................................................................... 8
Run Python code .................................................................................................... 9
Elaboration of First.py .................................................................................. 10
Practice 1 .............................................................................................................. 10
Data types .................................................................................................................... 11
Variables ....................................................................................................................... 12
Example of using variables ................................................................................... 12
Elaboration of variableDemo.py .................................................................. 14
Print out variables ................................................................................................ 15
Elaboration of variableDemos2.py............................................................... 17
Input from Keyboard .................................................................................................... 20
Elaboration of inputDemo.py............................................................................... 21
Type Casting ......................................................................................................... 22
Decision Making - Selection by conditional statements .............................................. 24
if statements ........................................................................................................ 24
Elaboration of ifDemo.py ............................................................................. 26
if and elif statements ........................................................................................... 28
Sample Python Program – Body Mass Index Calculation .................................... 29
Elaboration of bmi.py................................................................................... 31
Practice 2 .............................................................................................................. 34
P. 2 of 34

What is Computer Program?


A computer program is a set of instructions written in a programming language that a
computer can execute to perform specific tasks or solve problems. It serves as a
bridge between human and a computer, telling the computer how to process
information and produce desired results.

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

So, the algorithmn for the program would be like this:

Algorithmn for LoanWithGUI.py

1. init(self)

a. Layout Design (GridLayout)

b. Prepare and provide data members for:

i. Storing user input


ii. Storing calculated data that will be displayed on GUI

later

2. getMonthlyPayment(self)

a. Calculate and return the monthly payment

3. computePayment(self)

a. invoke getMonthlyPayment(self) to work

b. put the calculated answers on GUI


P. 4 of 34

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.

Computer Computer Execute


Program File Compilation Binary Format Program
(text based) File
P. 5 of 34

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

Tools for learning Python – Python


IDLE
With a view to learn Python, we have to install Python IDLE. The term IDLE stands for
Integrated Development and Learning Environement. It comes along with Text Editor,
basic Libraries of Python and the SHELL which is the Interpreter.

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

Your first Python Program – Hello


World
It’s high time creating your first Python Program. This time, we will learn the way of
printing out statement “Hello World!” in Python Shell. That is:

To begin with, start running IDLE through Start button by Python 3.12 -> IDLE
(Python 3.12 64-bit).
P. 8 of 34

Create Python code file


You should now see the Python SHELL. Under File menu, select New File or press Ctrl
+ N.

Insert code and save Python code file


That will bring up a new window called Untitled. Enter the following command in the
new window:

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

Run Python code


To run the Python code in file First.py, simply click Run -> Run Module.

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!".

2. The String "Hello World!":


✓ The text "Hello World!" is a string, which is a sequence of characters
enclosed in double quotes (") or single quotes (').
✓ Strings in Python are used to represent text or messages.

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.

Example of using variables


In Python, declaration of variables is not required. If there is need of a variable, just
think of a name and start using it as a variable.

Another remarkable aspect of using variables in Python:


Not only the value of a variable may change during program execution but the type
as well. You can assign an integer value to a variable, use it as an integer for a while
and then assign a string to the same variable.

In the following line of code, we assign the value 38 to a variable called i:

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

Here is the output of the above program:


P. 14 of 34

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.

2. Incrementing the Value of i:


i = i + 1

➢ The i + 1 operation adds 1 to the current value of i.


➢ Since i was previously 38, the expression evaluates to 38 + 1, which is 39.
➢ The result (39) is then assigned back to the variable i, so now i holds the value
39.

3. Printing the Value of i:


print(i)

➢ This line outputs the current value of i to the console.


➢ Since i is now 39, the program prints: 39

4. Taking Input from the User:


ch = input("")

➢ 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 out variables


If you would like to print out variables, there are several ways to do so. The following
example, variableDemos2.py, demonstrates different methods for your reference.

rank = 10 # An integer assignment


marks = 86.3 # A floating point
name = "Bibi" # A string

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

The output would be:

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

➢ The variables are initialized with the following values:


✓ rank is assigned the integer 10.
✓ marks is assigned the floating-point value 86.3.
✓ name is assigned the string "Bibi".

2. Printing with Method 1: Using print() with commas


print("Method 1")
print(name, "has got", marks, ".")
print("This student has a ranking of", rank, ".")

➢ The print() function in Python allows multiple arguments separated by


commas.
➢ The arguments are automatically converted to strings and separated by a
space (' ').

Output of Method 1:
P. 18 of 34

3. Printing with Method 2: Using print() with sep parameter


print("Method 2")
print(name, " has got ", marks, ".", sep="")
print("This student has a ranking of ", rank, ".", sep="")

➢ The sep parameter in print() determines the separator between arguments.


➢ By setting sep="", no space is added between the arguments.

Output of Method 2:

4. Printing with Method 3: String Concatenation


print("Method 3")
print(name + " has got " + str(marks) + ".")
print("This student has a ranking of " + str(rank) + ".")

➢ This method uses string concatenation with the + operator.


➢ Since marks and rank are not strings, they must first be converted to strings
using str().
➢ The + operator is used to combine strings.

Output of Method 3:
P. 19 of 34

5. Printing with Method 4: String Formatting with %


print("Method 4")
print("%s has got %f marks." %(name, marks))
print("This student has a ranking of %d." %rank)

➢ The % operator is used for string formatting. It replaces placeholders in the


string with values:
✓ %s is for strings.
✓ %f is for floating-point numbers.
✓ %d is for integers.
➢ marks is displayed with 6 decimal places by default because of %f.

Output of Method 4:

6. Printing with Method 5: String Formatting with %.1f


print("Method 5")
print("%s has got %.1f marks." %(name, marks))
print("This student has a ranking of %d." %rank)

➢ 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

Input from Keyboard


Every programmming language has its methods of getting input. Input can come in
various ways, for example from a database, another computer, mouse clicks and
movements or from the internet. Yet, in most cases the input stems from the
keyboard. In such case, Python provides the function input(). And it usually works
together with a string type parameter, which is know as the prompt string.

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.

Let’s see a simple example first.

Try the following program: (inputDemo.py)

name = input("What is your name? ")


print("Hello " + name + ". Nice to meet you.\n")
age = input("How old are you? ")
print("That's great! At the age of " + age + " is good!")

ch = input("")

You should see the following output:


P. 21 of 34

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:

1. Asking for the User's Name


name = input("What is your name? ")

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

2. Greeting the User


print("Hello " + name + ". Nice to meet you.\n")

➢ The print() function displays a greeting message to the user.


➢ The + operator is used to concatenate (combine) strings. The value stored in
name is inserted into the message.
➢ The \n at the end of the message adds a newline, creating a blank line after
the printed message.

3. Asking for the User's Age


age = input("How old are you? ")

➢ 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

4. Responding to the User's Age


print("That's great! At the age of " + age + " is good!")

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

name = input("What is your name? ")


print("Hello " + name + ". Nice to meet you.\n")
age = input("How old are you? ")
print("That's great! At the age of " + age + " is good!\n")

# The int() cast age from string to integer type


age = int(age)

newAge = age + 16

print("And you will be %d after 16 years !" %newAge)

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

Decision Making - Selection by


conditional statements
Decision making is crucial in conputer programming. Sometimes, there will be in a
scenario where the program is given two or more options and it has to select an
option based on the given conditions.

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.

The decision depends in most cases on the value of variables or arithmetic


expressions. These expressions are evaluated to the Boolean values True or False.
The statements for the decision taking are called conditional statements.

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

Here is an example (ifDemo.py):

nationality = input("What is your nationality?\nJapanese or American? ")

#The upper() is a built-in function for transform the string to Capital


Letters
nationality = nationality.upper()

if nationality == "JAPANESE":
print("\nKonichiwa!")
if nationality == "AMERICAN":
print("\nGood afternoon!")

ch = input("")

Here is the ouput you should obtain:

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.

1. Asking for the User's Nationality


nationality = input("What is your nationality?\nJapanese or
American? ")

➢ The input() function displays the prompt:

➢ The user is expected to type either "Japanese" or "American".


➢ Their input is stored as a string in the variable nationality.

2. Converting the Input to Uppercase


nationality = nationality.upper()

➢ 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

3. Checking the Nationality with Conditional Statements


if nationality == "JAPANESE":
print("\nKonichiwa!")
if nationality == "AMERICAN":
print("\nGood afternoon!")

➢ Condition 1: If the nationality is "JAPANESE", the program prints:


Konichiwa!
✓ "Konichiwa" is a Japanese greeting meaning "Hello."

➢ Condition 2: If the nationality is "AMERICAN", the program prints:


Good afternoon!

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 and elif statements


On top of this, the if statements can be extended to elif branches. The syntax is listed
as follows:

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

Sample Python Program – Body Mass Index


Calculation
The following example demonstrates the calculation of Body Mass Index (BMI). The
requirements of the BMI calculation are listed as follows:

1. The formula for calculating BMI is

BMI = ( Weight in Kilograms / ( Height in Meters x Height in Meters ) )

2. BMI Result
➢ <=15 (Under Weight)
➢ >15 and <=25 (Optimum Weight)
➢ Other results (Over Weight)

3. The result should be round up to 2 decimal places.

The sample output of the program is listed below:


P. 30 of 34

Try to study the code of bmi.py:

#Collect data from user


weight=input("Please input your weight (kg): ")
height=input ("Please input your height (m): ")

#Convert the input values from string to float type


weight=float(weight)
height=float(height)

#Perform calculations - calculate the BMI


bmi=(weight/(height**2))

#Print out the result in 2 decimal places


print('Your bmi is ' + "%.2f" % bmi)

print("\n==================================\n")

#Print out the analyzed result


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

#Pause the output screen


ch = input("")
P. 31 of 34

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

1. Collecting User Input


weight=input("Please input your weight (kg): ")
height=input ("Please input your height (m): ")

➢ 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".

2. Converting Input to Float


weight=float(weight)
height=float(height)

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

➢ This conversion is necessary because mathematical operations (e.g., division


and exponentiation) require numeric data types.
P. 32 of 34

3. Calculating BMI
bmi=(weight/(height**2))

➢ The formula for Body Mass Index (BMI) is:

➢ The program divides the input weight by the square of height (height**2).

Example Calculation:
➢ Suppose:
✓ weight = 70.0 kg
✓ height = 1.75 m

➢ The BMI is calculated as:

4. Printing the BMI (Rounded to 2 Decimal Places)


print('Your bmi is ' + "%.2f" % bmi)

➢ The print() function displays the calculated BMI.


➢ The "%.2f" % bmi format specifier ensures the BMI is rounded to 2 decimal
places.
✓ For example:
◆ If bmi = 22.857142857, it will be displayed as 22.86.
P. 33 of 34

5. Printing a Divider
print("\n==================================\n")

➢ This line prints a visual separator (==================================)


for better readability.

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

➢ This block uses conditional statements to categorize the BMI:


✓ Underweight: If bmi is less than or equal to 15, the program prints:
You are under weight.

✓ Optimum Weight: If bmi is greater than 15 but less than or equal to 25,
it prints:
You are in Optimum weight.

✓ Overweight: If bmi is greater than 25, it prints:


You are over weight.
P. 34 of 34

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 of 90 or above, he/she is excellent.

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

If a student gets marks below 50, he/she is failed.

The output of the program could be like this:

You might also like