Week 3 to 5, Data type, Function, Module, Package, While Loop, For loop, VS Code
Week 3 to 5, Data type, Function, Module, Package, While Loop, For loop, VS Code
Python: Data type, Function, Module, Package, While Loop, For loop, VS Code
Dr. Li Ruozhu
City University of Hong Kong
[email protected]
Now
• You already have a basic understanding of the elements of Python, such as data
types, variables, functions, etc.
• Let‘s get more relevant knowledge together:
• Functions
• Import
• While loop
• Data types
• For loop
Task 1:
• The ticket policy for a park is as follows:
• The next time we use it, we can call the function name directly and
modify the parameters in the parentheses.
How to create a function
How to create a function
Key word
to define Parameters:
a new function • Parameter is used to pass values into functions, to adjust the behavior of the functions.
You can decide
the function name
• Parameters are the adjustable part of the function. Parameters are actually some
variables.
• Because parameters can function on various inputs, they make functions more versatile
and reusable.
Indent
Call the function: this is how we use the function, and you can decide the value of parameters
How to create a function? tic= the name of
function
Indent: tell python which part is the content of your function 要tab/space
Create a self-defined function
• In programming, a function is a block of code that performs a certain task or a group of related
tasks.
• If you notice that you often use the same block of code over and over again, consider writing a
corresponding function. Then, the next time you need this piece of code, you can simply call the
function.
• The def
• The name of the function (which we can freely choose).
• The function parameters inside parentheses (leave the parentheses empty if there are no
parameters).
• A colon : at the end.
Create a self-defined function
• When you understand what parameters are, you will have a better understanding of how to
create a new function. So please go back to week 2 slides to review parameters, if you need.
• With the help of functions, we can avoid rewriting the same logic or code again and again in
a program.
• In a single Program, we can call (use) Python functions anywhere and also call multiple times.
We can track a large Python program easily when it is divided into multiple functions.
• Values can be passed to a function using variables — we call these parameters or arguments.
Functions can also return values.
• In another word, functions are an excellent alternative to having repeating blocks of code in
a program. Functions increase the reusability of code.
Task:
• We need to get the user's name and then show a greeting with a
specific name on the screen.
• Remember this exercise? We did this the in last class. This time, let's
use the method of creating a function to come up with a solution for
it.
Task:
• Ask the user to enter his age and his brother's age. You help him
figure out how many years his brother is older than him. Then you
display the results on the screen.
• Remember this exercise? We did this the in last class. This time, let's
use the method of creating a function to come up with a solution for
it.
Task:
• If a user tells you his name is Andy, then welcome him and tell him he
is allowed in. Users with other names should be told they are not
allowed in.
• Remember this exercise? We did this the in last class. This time, let's
use the method of creating a function to come up with a solution for
it.
When creating a function, in some cases, we need to use
the word "return"
• Sometimes we need to get a process (e.g. the process of determine who enjoy free
ticket) -- → no need to use “return”
——The result of the “return expression” is what we get after use the function:
Task:
• Please create a function to calculate the square of a number.
要出計算答案時要⽤return
• 1 Use the keyword def to declare the function and follow this up with the function
name.
• 2 Add parameters to the function: they should be within the parentheses of the
function. End your line with a colon.
• 4 End your function with a return statement if the function should output
something. Without the return statement, your function will return an object None.
How to import module
Function→ Module, Library/Package
• A set of functions→Module
• A set of modules→Library/Package
Open Source: get modules and packages easily
• Python is a dynamic and multi-paradigm programming language that
possesses a lengthy history of success and community support.
or
Task: a simple game
• Let the computer to randomly generate an int number between 1 and 3.
Invite the user to guess the number (give the user only 1 chance). If the
user guesses correctly, say congratulations to the user; If the user guesses
wrong, tell the user that sorry you are wrong.
Task: a simple game
• result
While Loop
Why we need loop?
• Loops are important in Python or in any other programming
language:
• They help you to run a block of code repeatedly.
• You will often come face to face with situations where you would
need to use a piece of code over and over but you don't want to
write the same line of code multiple times.
Task: a simple game, more than one round
• Let the computer to randomly generate an int number between 1 and 15.
Invite the user to guess the number (only 3 chances). If the user guesses
correctly, congratulations to the user; If the user guesses wrong, tell the
user that sorry you are wrong, and please try again.
Get to understand the process
If only one chance
Get to understand the process
If only one chance
a=random.randint()
Get to understand the process
If only one chance
a=random.randint()
b=input()
Get to understand the process
If only one chance
a=random.randint()
b=input()
b==a?
Get to understand the process
If only one chance
a=random.randint()
b=input()
b==a?
b==a
Good job
Stop here
Get to understand the process
If only one chance
a=random.randint()
b=input()
Fail b!=a
b==a?
b==a
Good job
Stop here
Get to understand the process
If more than one chance ???
a=random.randint()
b=input()
b!=a
b==a?
b==a
Good job
Stop here
Get to understand the process
If more than one chance
a=random.randint()
b=input()
b!=a
b==a?
b==a
Good job
Stop here
Get to understand the process
If more than one chance
a=random.randint()
Yes
b=input()
b!=a
b==a?
b==a
Good job
Stop here
Get to understand the process
If more than one chance
a=random.randint()
Yes
b=input()
b!=a
b==a?
b==a
Good job
Stop here
Get to understand the process
If more than one chance
a=random.randint()
Yes
Loop
b=input()
b!=a
b==a?
b==a
Good job
Stop here
While Loop
• If the “while condition” is True, keep on going in the loop (run statements).
• If the “while condition” is False, jump out of the loop.
• With the while loop we can execute a set of statements as long as a condition is
true.
While Loop
• If the “while condition” is True, keep on going in the loop (execute statements).
• If the “while condition” is False, directly go to a result.
• With the while loop we can execute a set of statements as long as a condition is true.
• We need a variable (for example i) to count the number of loops, and we need to add one to the
count at the end of each loop, to tell program to run the next loop.
Yes
Loop
b=input()
b!=a
b==a?
• We need a variable (for example i) to count the
number of loops, and we need to add one to the b==a
value of i at the end of each loop, to count how
many loops it already run. Good job
Stop here
• This is the way, we create a loop machine.
Create a loop machine
• The elements you need:
• counter variable (define and name it by yourself, for example i)
• while
• else (optional)
• break (optional)
Format:
while loop 就係如果無
counter variable=0
while condition (compare the counter variable with a certain number):
statement
counter variable+=1 0 係開始數
else:
this is number 0
statement this is number 1
this is number 2
done
Back to the Task:
• Or lose:
A typical Wrong solution:
• What will happen by using this?
• File
• Open
• Save
• 9 of them are the most common, and they're the ones we ask you to remember and
use in this course.
Data Type
• 9 most commonly used data types:
• 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:
• List items are indexed, the first item has index [0], the second item has index [1] etc.
Data Type for a set of values
Tuple
• Tuples are used to store multiple items in a single variable
• A tuple is a collection which is ordered and unchangeable.
• Very similar to list, but unchangeable.
• Tuple items are indexed, the first item has index [0], the second item has index [1] etc.
Data Type for a set of values
Set
• Sets are used to store multiple items in a single variable.
• A set is a collection which is unordered, and unindexed.
不順序
• Not allow duplicate values.
• 2 parameters:
• Specify the starting value by adding a parameter as the first parameter, and the ending value
become the second parameter:
• range(3, 9), means values from 3 to 9 (but not including 9)
• 3 parameters:
• The third parameter is the step size. The default step size is 1. If you want it to use other step
sizes, add a third parameter:
• Range (3, 9, 2)
Range, as a function, it has 3 parameters
• 1 parameter:
• The range() function defaults to 0 as a starting value,
• So, if you use only one parameter, it is the ending value:
• range (6) means range(0,6), means 0,1,2,3,4,5
• range (557) means range(0,557)
• 2 parameters:
• Specify the starting value by adding a parameter as the first parameter, and the ending value
become the second parameter:
• range(3, 9), means values from 3 to 9 (but not including 9)
• 3 parameters:
• The third parameter is the step size. The default step size is 1. If you want it to use other step
sizes, add a third parameter:
• Range (3, 9, 2)
For Loop
For loop
• We already know how to build a while loop.
• This time let us learn to build a for loop.
• It is more concise, and easier to operate.
• But the logic is a little abstract, please focus.
New variable,
any name is ok
For example:
For Loop
• Loop 1:
• Grab 4, put 4 into x,run
• Loop 2
• Grab 1, put 1 into x, run
• Loop 3:
• Grab 2, put 2 into x,
• The value of i is set to 0 and it is updated to the next number of the range on
each iteration. This process continues until 3 is reached.
Task:
• Please print your name 20 times in terminal.
• Use for loop to build it.
Task:
• Please print int numbers from 0-10 in terminal.
• Use for loop to build it.
Third party package
Function→ Module, Library/Package
• A set of functions→Module
• A set of modules→Library/Package
Open Source: get modules and packages easily
• Python is a dynamic and multi-paradigm programming language that
possesses a lengthy history of success and community support.
• For examples:
• NumPy https://numpy.org/
• Openpyxl https://openpyxl.readthedocs.io/en/stable/
• Beautiful Soup https://beautiful-soup-4.readthedocs.io/en/latest/
• Pandas https://pandas.pydata.org/
• Plotly https://plotly.com/python/
How to start to use a third party package and its modules?
• First, install package/library
in terminal window key in:
For Windows
pip install package name
pip3 install package name
For Mac
Be careful: pip is a software. please keep your pip in the latest version, If this prompt appears, copy the green words
and paste in terminal window, press Enter key to run it:
If done:
How to start to use a third party package and its modules?
After installation,
please try this code,
see whether it work:
Pandas
• Pandas is a famous Python library used for working with data sets.
• It has functions for analyzing, cleaning, exploring, and manipulating data.
• Pandas allows us to analyze big data and make conclusions based on
statistical theories.
• Pandas can clean messy data sets, and make them readable and relevant.
• Relevant data is very important in data science.
• Data Science: is a branch of computer science where we study how to store,
use and analyze data for deriving information from it.
• If you know how to use Pandas, it deserves to be written on your CV. This
will enhance your career competitiveness.
Pandas
• If you know how to use Pandas, it deserves to listing on your CV. This will
enhance your career competitiveness.
Pandas
• If you know how to use Pandas, it deserves to listing on your CV. This will
enhance your career competitiveness.
• From this starting point, you can have the ability, patience and experience to
continue learning it on your own in the future.
Pandas——data frame
• Print a data frame
• Data sets in Pandas are usually multi-dimensional tables, called DataFrames.
Pandas——data frame
• Print a data frame
• Data sets in Pandas are usually multi-dimensional tables, called DataFrames.
Pandas—— work for various types of data
• It can open various types of data. Not just excel.
• So it's convenient to work with big data, because excel can only store
a limited number of rows of data. 1,048,576 rows.
• But for csv and Json file:
• You can consider them as no limit.
• So the next time you come across csv and Json types of data, don't be
afraid. Be bold enough to handle them with Pandas!
How to know what package to use for your task?
How to know what modules and functions each package has?
• 1 Learn from the our course
• 2 Go to the official website of package/library
• 3 Take advantage of the abundant teaching materials available on the
Internet: both text and video; both in Chinese and English.
• There is no class in the world that can teach you all the ways to use all
the packages. The point of this course is to get you started, to help
you build confidence, to help you gain strategies for self-study, and
then you should use the course as a starting point to continue
exploring on your own.
• We can use ChatGPT to write an article directly for us. But whether
we actually use this article, we have to make a judgment.
• Why do we have the ability to make judgments?
• Because at least we know how to read and write.
• Same logic:
• We can use ChatGPT to write program code directly for us. But
whether we actually use this code, we have to make a judgment.
• How can we be able to make judgments? At least know whether the
AI is fooling us or being harmful to use?
• We need basic programming knowledge.
With ChatGPT, then, we still need to learn coding?
• Yes, still need to learn.
+ ChatGPT
• Our simple knowledge Get advanced results
With ChatGPT, we still need to learn coding, but easier
• ChatGPT is an excellence teacher
• You can ask ChatGPT questions directly and get direct answers that are
more relevant. It's like having a personal tutor.