0% found this document useful (0 votes)
2 views51 pages

Computer basic knowledge

This document serves as an introduction to Python, covering its history, operating environment, variables, data types, and conditionals. It includes practical exercises for users to familiarize themselves with Python's syntax, built-in functions, and programming concepts such as operators and conditional statements. The content is structured to guide beginners through the basics of coding in Python, with tasks designed to reinforce learning.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views51 pages

Computer basic knowledge

This document serves as an introduction to Python, covering its history, operating environment, variables, data types, and conditionals. It includes practical exercises for users to familiarize themselves with Python's syntax, built-in functions, and programming concepts such as operators and conditional statements. The content is structured to guide beginners through the basics of coding in Python, with tasks designed to reinforce learning.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 51

(Teacher’s Version)

PA05 Unit1
Introduction to
Python
1.1 About Python

1.2 Python’s Operating Environment

1.3 Variables and Data Types of Python

1.4 Conditionals ( i f Statement )


Contents
Learning Objectives
1.1 1. About Python

1.2 2. Python’s Operating Environment

1.3 3. Variables and Data Types of Python

1.4 4. Conditionals (i f Statement).

Practice 1. Consolidation 2. Practical exercise 3. Enrichment


Zone
Contents

Recently I’ve been


thinking to learn for a
Well, you can give a try
hobby a coding
on the Python language.
language that is
It totally meets up to the
popular, handy and
expectations you’ve just
easy to learn. Any
mentioned!
suggestion?
1.1 About Python Contents
吉多•范羅蘇姆
• Python was created by Guido van Rossum and was first
released in 1991. With a high level of code readability,
Python currently ranks among the most popular coding
languages for novices.

• Meanwhile , Python owns a huge open source community


where numerous powerful packages are developed, which
keeps expanding Python᾽s capabilities for a wide range of
applications such as web development, hardware automated
control, data analysis and artificial intelligence (AI).
• A global survey conducted
on 2021 by Stack Overflow
has shown that JavaScript,
HTML/CSS and Python are
the top three most
popular languages used by
programmers.

• About the download and


installation of Python
software, refer to
Appendix 1. Windows 10
is the operating system for
1.2 Home page of Python’s official site (python.org) installing and running in
this book.
Contents
1.2 Basic Syntax and Operators of
Python 函式(函數)
• Below we will learn to enter and execute a basic Python command
through Python’s built-in function print ( ), which serves to output
the date enclosed in its brackets (its parameter) to the computer
• screen.
A function is a subprogram that executes a predefined set of tasks and can be called by the program with
its name. Values can be passed to a function for execution through its parameters. Python has a host of
built-in functions, with many additional functions made available by importing libraries. USer0defined
functions will be covered in Unit 3.

 Task 1: Saying hello to Python


• Let first say hello to Python.
Select the installed IDLE
program in the app list of
Windows Start menu to open
the Python Shell operating
environment. The Python Shell
is suitable for inputting and 1.2 Select Python IDLE from
Windows program list to start it
executing simple commands .
• IDLE is Python’s integrated development environment for program development. By default, when IDLE is
started, the Python Shell window will be opened.
Contents
After the command prompt string (>>>), enter a simple
command as below and press Enter :

print("Hello Python")

The Python Shell will instantly execute the command and


output a line of text as follows

1.3 Input print ( ) command in Python Shell and the


execution result
Contents
 Task 2: Using IDLE’s built-in code editor to write a program

• To open IDLE’s built-in code editor, click the File menu of the
Python Shell window and select New File .

1.4 Open a blank Python code editor window in Python IDLE

• Input the following code in the code editor:

1.5 Input code into the code editor


Contents
Save the above code as a Python document “u1_task2.py”. Then click the
Run menu of the code editor window and select Run Module in to execute
the Python document. Write down the execution result shown in the
Python Shell in the blank below:

• To execute an opened
Python document, we
may also use the
shortcut key F5.

1. Modify the program “u1_task2.py” so that it generates the execution


result as follows:
Contents
1.3 Variables and Data Types of
Python
1.3.1 About Python Variables
變量(變數)
Variables serve to store certain data used or generated during program
execution. Python variables have the following features:

1. Variables can be used without declaring them first. By assigning a value to


a new variable, we have declared and defined the variable.

2. The data type of the same variable can change as different values are
assigned to it.

• When a variable is created, the program will assign a memory location for its use, with its name
being the identifier of the location.
Contents
 Task 3: Using comments

When writing a Python program, you can insert a hash sign (#) as a
single-line comment delimiter. Any content after it, treated a
comment, won’t be executed. Comments serve to help other users
understand a program.

In the Python Shell, enter the commands in the following table


sequentially and record the output results in the table.
• For comments that
span multiple lines,
we can use
multiline comment
delimiters by
adding three single
(''') or three double
quotes(""") before
and after the block
of comments.
Contents
1.3.2 Naming Python Variables
• In naming Python variables, the following rules must be followed:

1. A variable name must begin with an uppercase or lowercase


letter or an underscore (_).

2. A variable name can only contain alphanumeric characters and


underscores. No blank character is allowed.

3. Python code, including variable names, is case-sensitive. For


example, Name and name denote two different variables.

4. A variable name should not be a Python built-in keyword (if, for


etc.).
• Although any variable name is valid that follows the rules, variables shouldn’t be named arbitrarily. Use
meaningful variable names to facilitate future program maintenance. For example, use the variable
names teacher_name and stu_id to store a teacher’s name and a student’s ID respectively.

• To look up the full list of Python keywords, enter the following commands in the Python Shell:
import keyword
print(keyword.kwlist)
Contents

2. Determine if the following strings are valid Python variables. Circle the
correct answers.

(a) Py_thon valid invalid

(b) 3apple valid invalid

(c) sam#name valid invalid

(d) user_ID valid invalid

(e) for valid invalid


Contents
1.3.3 Data Types in Python
數字 串列 元祖 集合
Common data types in Python include number, string, list, tuple, set and
dictionary. Number and string types will be introduced in this Unit.
字典 字串(字符串)
(a) Numbers
The common types of Python numbers are integers and floating-point
numbers, denoted as int and float respectively in Python.

Floating-point numbers are real numbers containing decimals. Those of a


larger magnitude can be represented in scientific notation, such as 3.13e5
and 4.5e-4, which denote 310,000.0 and 0.00045. 科學記數法

3. Write down the output results of the commands below. • In the Python Shell,
we may place
multiple commands
(a) x=2.88e6; print(x) _____________________
2880000.0 in the same line by
using semicolons(;)
(b) x=3.14e-3; print(x) _____________________
0.00314 as separators among
them.
Contents
(b) Strings
Strings are for recording textual data. To include string data in a
program, enclose them in a pair of single quotes or double quotes as
in the following:

1.6 1.7

If both variables s and t are strings, s+t refers to their concatenation


(joining together to form one string).

As both 10 and 20 in Figure 1.7 are enclosed in a pair of single quotes,


they are strings. Therefore, adding them results in the joining of two
strings, namely “1020”.
Contents
 Task 4: Data input

This task involves using Python’s built-in function input(). When


the function is called, the system will wait for the user to input
data. After the user inputs data and presses Enter, the data input
will be stored in a variable.
• In Python 3, any data input through input()are treated as string data.

Create the following program and save it as “u1_task4.py”. Run


and test it by inputting “Jerry”. Write the output result in the
blank.

Hello, Jerry
1.8 ______________________
Contents
4. Why doesn’t the command print('Hello, '+name) output “Hello, name”?
As name in the command is a variable, the program outputs the
_________________________________________________________
value stored in the variable, which is the user’s input value received
_________________________________________________________
by the input() function, namely, “Jerry”.
_________________________________________________________

5. Modify the Python document “u1_task4.py” by adding a question to it,

“What is your favourite food?”. The program will wait for the user to
input the answer before outputting a response based on the answer
input, “[ ]! Oh, me too!” as shown in the following example:

1.9
Contents
1.3.4 Operators
Programming often involves some types of operations in which operators are
used. Common types of Python operators include arithmetic operators,
comparison operators and logical operators.
• An operator is a symbol or keyword for performing an operation on operands. An
expression is a statement made up of operators and operands.

A. Arithmetic operators: Perform common mathematical


operations
Operato Meaning Exampl Return
r e Value
+ Addition of two values 12 + 4 16
- Subtraction between two values 12 - 4 8
* Multiplication of two values 12 * 4 48
/ Division between two values 12 / 5 2.4
(Quotient)
% Remainder of the quotient 12 % 5 2
// Integral part of the quotient 12 // 5 2
Table 1.1
** (value 1) raised to the power of 12 ** 2 144
(value 2)
• The result of an operation is known as the return value.
Contents
6. Complete the right column of the table.
Contents
B. Comparison operators: Compare two values to evaluate if they
relate to each other as denoted by the operator. If true, return
True; otherwise, False.

Operato Meaning Exampl Return


r e Value
> Is … greater than …? 3>2 True
>= Is … greater than or equal to 3 >= 2 True
…?
< Is … less than …? 3<2 False
<= Is … less than or equal to …? 3 <= 2 False
== Is … equal to …? 3 == 2 False
Table!=
1.2 Is … not equal to …? 3!=2 True

• True and False are both Boolean values.


Contents
7. Complete the right column of the table.
Contents
C. Logical operators : Perform Boolean operations and return
Boolean
values.
Operato Meaning Example Return
r Value
and Return True only if both values (3>2) and True
are True; otherwise, False (4>3) False
(3>2) and
(4<3)
or Return True if at least one value (3>2) or True
is True; otherwise, False (4<3) False
Table 1.3 (3<2) or
(4<3)
not Return False if the operand is Not (3<2) True
True, and vice versa Not (3>2) False
8. Complete the right column of the table.
Contents
1.4 Conditionals (if Statement)
Python’s if statement evaluate if a specific condition is true. If the condition
is true (Boolean value: True), the program will run the indented conditional
block. If the condition is false (Boolean value: False), the block will be
skipped by the program.

Indentation of conditional blocks is a must in Python language while it is optionally used for style
and readability in many other coding languages.

There are three types of conditional structures for if statements. Below are
their syntax, flowcharts and tasks.

A. if… conditional structure


The if... conditional structure evaluates if a specific conditional expression
is true in order to determine whether to run the conditional block. If true,
the block will be executed. Otherwise, it will be skipped.
Contents
Syntax and flowchart

• A flowchart uses shapes, lines,


arrows, textual notes and
expressions to present a
program's algorithm. Below are
some common symbols and their
uses:

Start/End symbol

Process symbol

Decision symbol

Input / Output symbol

1.10 if…structure flowchart


Contents
 Task 5: Using the if… conditional structure

Create the following program and save it as “u1_task5.py”.

1.11

Note: the command print('Pass.') must be indented.


Run the above program and write down the output result.

Pass.
___________________
• Every line of a conditional block in an if statement must be indented by the same
whitespace. Instead of typing spaces before each line, it is preferable to indent each line
with the Tab key to guarantee uniform indentation.
Contents
B. if…else conditional structure
The if…else conditional structure evaluates if a specific conditional
expression is true. If true, the program will execute Block 1 right after the
conditional expression. Otherwise, the program will execute Block 2 right
after else.

Syntax and flowchart

1.12 if…else structure flowchart


Contents
 Task 6: Using the if…else conditional structure

Create the following program and save it as “u1_task6.py”.

1.13

When you run the above program, you will encounter an issue: no matter
what number you input, the program always returns an error. The reason is
that the number input by the user through the input() function is
assigned to the variable mark as a string instead of a number.
Contents
For example, when the user inputs 60, the variable will be assigned the
value '60'. When the condition mark >= 50 is evaluated, since the two sides
of the comparison operator have different data types, the program will end
with an error. To solve it, use Python’s built-in function float()to convert the
string data into a number data first. Modify the above program
“u1_task6.py” by assigning value to mark as follows:

mark = float(input())

• Python provides built-in functions int(), float(), str() for data type conversion among
integers, floating-point numbers and strings.
For example:
float('4') returns 4.0
int(4.1) returns 4
str(123) returns '123'

Now run the modified program. If the input number is greater or equal to
50, the output result will be “Pass.”; otherwise, “Fail.”
Contents
C. if…elif…else multiple-condition structure
This conditional structure is suitable for sequentially evaluating which of the
multiple conditional expressions is true. In Figure 1.14, the program first
evaluates if conditional expression 1 is true. If true, Block 1 will be executed.
Otherwise, conditional expression 2 is evaluated. If true, Block 2 will be
executed. Otherwise, Block 3 will be executed.
For simplicity’s sake, here we only include a single elif conditional expression between i f and else. In
practice, it is common to have multiple elif expressions between if and else.

Syntax and flowchart

1.14 if…elif…else structure flowchart


Contents
 Task 7: Using the if…elif…else conditional structure

Create the following program and save it as “u1_task7.py”. The


programs allows the user to input a mark and evaluates which
category it belongs according to the table below. Run the program
and input different values to test if the program outputs the correct
categories.

1.15
Contents
9. Modify the program “u1_task7.py” so that it can evaluate
which grade the input mark belongs according to the table
below.
Contents
 Task 8: Using a Python program for LED on/off control

Connect the following circuit in which LED is connected to an


Arduino board on Pin D6. To control the LED, the program needs to
communicate instructions through Pin D6.

Arduino is an open source electronic platform


providing various microcontroller models and a free
development program, Arduino IDE. An Arduino
microcontroller (or Arduino board) can be
connected to sensors for detecting changes in the
environment and control LED, motors, etc. based on
the uploaded program. It has a user-friendly I/O
interface. The board model Arduino UNO is used in
this book.

To control an Arduino board with Python, a


pyFirmata package is needed. After installing
pyFirmata, we have to install the Arduino IDE
program, from which to upload related code
(StandardFirmata) to Arduino board. ( See
Appendices 1 and 2)

1.16 Circuit diagram of LED on/off Suggested resistor: 220Ω


control with an Arduino board
Contents
Create the following program and save it as “u1_task8.py”:
Figure 1.17 shows the program in a web-based
Python editor with line numbers simply for
easy code line identification.

Code Description (numbers in brackets are line


numbers)
(1) Import pyfirmata library.
(4,5) Define the computer’s COM6 USB port
as connected to Arduino.
(6) Define Arduino’s Pin D6 for output.
(8) Run the following block in an infinite loop.
(10) Receive user input with input().
(11-12) If Y or y is input, run LED. write(1) to
turn on LED.
(15-16) If N or n is input, run LED.write(0)to
turn off LED.
(19-23) If B or b is input, end the program.
1.17 Python program for LED on/off control Terminate the loop with break.

Run the above program. During program execution, the computer will display a prompt for input:
Enter Y/N/B; Y:on; N:off; B:off and exit. If Y or y is input, the LED will turn on. If N or n is input, the
LED will turn off. If B or b is input, the LED will turn off and the program will end.

Test the program in this procedure: When prompted to input, first enter Y to turn on the LED. Then
enter N to turn off the LED. Finally enter B to end the program.
Contents
About Python
1. Python currently ranks among the most popular coding
languages for
novices and have a wide range of applications such as web
development, hardware automated control, data analysis and
AI.

Python’s Operating Environment


2. The Python Shell is suitable for inputting and executing simple
commands.

3. Python IDLE has a built-in code editor for creating and


executing Python
documents.
Contents
Variables and Data Types of Python
4. Python variables can be used without declaring them first and
their data
type can change as different values are assigned to them.

5. In a Python program, the hash sign (#) is a single-line comment

delimiter. Any content after it won’t be executed.

6. Common data types in Python include number, string, list,


tuple, set and
dictionary.

7. Common programming operators include arithmetic operators,

comparison operators and logical operators.


Conditionals ( if statement)
8. There are three types of structures with the if statement in
Python: if…
structure, if…else structure and if…elif…else structure.
Contents
A. Consolidation
1. For an Arduino board to interact with Python, which program
has to be
uploaded to the board?
A. IDLE
B. pyFirmata
C. StandardFirmata C
D. Arduino IDE

2. What is the return value of the expression 7 / / 2 ?


A. 1
B. 2
C. 3 C
D. 4
Contents
3. What is the return value of the expression 2 1 % 5 ?
A. 1
B. 2
C. 3
D. 4 A

4. Which of the following is an invalid Python variable name?


A. n a m e 1
B. 2 _ D
C. S s _ t
D. _ c o m B
Contents
B. Practical Exercise
1. Briefly describe the function of the following program.

1.18

____________________________________________________________
If the age input is greater or equal to 60 or less than 6, a 50% discount
____________________________________________________________
message will be outputted; otherwise, a 10% discount message outputted.

2. What will be outputted for the following command input in the Python
Shell?
s1='2'; s2='4'; print(s1+s2)
24
______________
Contents
C. Enrichment
Add an LED to the circuit in Figure 1.15 in this Unit. Then create, save and
run the program in Figure 1.19. Test the program for four different execution
results with different input values (1,2,3,4).

1.20

Execution results of different input values

1.19
-End-
Contents
Program file:u1_task2.py

Back
Contents
Activity Window 1 answer:
print('Who are they?')
print('Jane, Amy, Ada')

Program file: u1_q1.py

Back
Contents
Program file: u1_task4.py

Back
Contents
Program file: u1_q5.py

Back
Contents
Hints:
1. 5<8 and 7>2 are both True
2. 10<8 and 9<5 are both False
3. 4<=7 is True, and so the operand of not is True

Back
Contents
Program file: u1_task5.py

Back
Contents
Program file: u1_task6.py

Back
Contents
Program file: u1_task7.py

Execution result of Task 7 (reference answer)


Input 80.5 ➡ Output “Credit.”
Input 50 ➡ Output “Pass.”
Input 49.5 ➡ Output “Fail.”

Back
Contents
Activity Window 9 answer:
print('Please input your mark.')
mark = float(input())
if mark >= 90:
print('A.')
elif mark >= 80:
print('B.')
elif mark >= 50:
print('C.')
else:
print('Fail.')

Program file: u1_q9.py

Back
Contents
Program file: u1_task8.py

Back
Contents
As Python IDLE editor does not show line numbers, the teacher is advised
to use a web-based Python editor which shows line numbers when
presenting a long program to the class for teaching effectiveness. An
example is https://trinket.io/python (as in Figure 1.17)

Back
Contents
Program file: u1_ex.py

Back

You might also like