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

Week 3 to 5, Data type, Function, Module, Package, While Loop, For loop, VS Code

The document outlines a Python programming course covering data types, functions, loops, and modules. It includes various tasks for creating functions to determine ticket prices based on age, greeting users, and generating random numbers. The importance of using functions for code reusability and the structure of defining functions in Python is emphasized throughout the document.

Uploaded by

charlottelauyee
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)
1 views

Week 3 to 5, Data type, Function, Module, Package, While Loop, For loop, VS Code

The document outlines a Python programming course covering data types, functions, loops, and modules. It includes various tasks for creating functions to determine ticket prices based on age, greeting users, and generating random numbers. The importance of using functions for code reusability and the structure of defining functions in Python is emphasized throughout the document.

Uploaded by

charlottelauyee
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/ 109

Week 3 - 5

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:

• Free entry if under 4 years old


• If you are 4-60 years old, you need to buy a full ticket, 60 yuan RMB
• If you are over 60 years old, you need to buy half ticket, 30 yuan RMB

• Please create a simple piece of programming that asks visitors to enter


their age and then inform them of the appropriate ticket requirements.
solution:
Task 2:
• The ticket policy for a park is as follows:

• Free entry if under 7 years old


• If you are 7-65 years old, you need to buy a full ticket, 60 yuan RMB
• If you are over 65 years old, you need to buy half ticket, 30 yuan RMB

• Please create a simple piece of programming that asks visitors to enter


their age and then inform them of the appropriate ticket requirements.
Solution:
Task3:
• The ticket policy for a park is as follows:

• Free entry if under 10 years old


• If you are 10-70 years old, you need to buy a full ticket, 60 yuan RMB
• If you are over 70 years old, you need to buy half ticket, 30 yuan RMB

• Please create a simple piece of programming that asks visitors to enter


their age and then inform them of the appropriate ticket requirements.
Solution:
Task:

• If you make changes manually:


• Repetitive work, waste of time.
• Changing the numbers one by one is prone to errors.

• We need automated solutions!


Think about use more variables
• Actually, only two threshold age:
• one is for little child
• one is for elder

• We could create two more variables


• thage1, thage2
Think about use more variables
• Actually, only two threshold age:
• one is for little child
• one is for elder

• We could create two more variables


• thage1, thage2
• Further,
• we can wrap this ticket programming into a function ——This is
the way we create functions. We use some variables (for example,
thage1 and thage2) as the parameters for this self-created
function. “def” is the key word to define this new function. You
can name this new function by yourself (for example, tic).

• 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

Use def at the beginning:


Tell python you are going to create a function
not the must to use these names, create yourself
Parameters: actually they are variables, tell python which parts can adjust

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.

• User-defined functions bring several important benefits:


• Functions are convenient when you need to regularly accomplish the same task. After defining a
function, you simply call it instead of typing or copy-pasting the same code snippet over and over
again. Moreover, if you decide to change a block of code, you only need to change it where you
define the function. This change will be applied anywhere the function is called.
• By defining and using functions, you can break complex programs into smaller steps. Each step
can be a separate function solving a specific task.
• Finally, with user-defined functions, your code is usually easier to follow. You can clearly see which
task is accomplished with each code block. This is especially true when functions are defined
following the best practices discussed later.
Create a self-defined function
• To define a function, we write the following elements in a single line:

• 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”

• Sometimes we need to get a result (e.g. get a calculated result)---→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.

• And then, to use this function to calculate the square of 4.


Task:
• Please create a function to calculate the square of a number.

要出計算答案時要⽤return

• And then, to use it calculate the square of 4.


Four steps to define a function
• The four steps for defining a function in Python are the following:

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

• 3 Add statements (content) that the functions should execute.

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

• Some of the fundamental characteristics of Python are its simplicity,


readability and flexibility, making it among the most popular and sought-
after skills to learn as a software engineer.

• Python has a huge community of developers that have contributed


hundreds of thousands of third-party packages.

• Python also includes several built-in packages, modules, and functions


out of the box that simplify adoption, increase developer productivity and
promote code consistency.
Open source
Build-in
• A set of functions→Module Or
Third party
Build-in
• A set of modules→Library/Package Or
Third party

• We can easily and freely use packages and modules


written by others to efficiently implement specific tasks
such as data processing, crawlers, dynamic charting,
machine learning, etc.
How start to use a build-in Module?
• Some modules are build-in, so
• No need to install Library/Package
• Directly impose module name
• Format:
• import module name

• Then use the functions in this module

• Format of calling the functions in a module:

• module name . function name

• module name dot function name


Task: Random Number
• Please display a random int number comes from between 1 and 9 on
your screen.
Task: Random Number
• Python does not have a random() function to make a random
number, but Python has a built-in module called random that can
be used to make random numbers.

• To display a random number between 1 and 9, we need to use


functions in this module.

• Module name: random


• Function name: randint()
Task: Random Number
• Please display a random int number comes from between 1 and 9 on
your screen.

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

Still have chance?

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

Still have chance?

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

Still have chance? No Fail

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

Still have chance? No Fail

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.

• A common sign we use to go to next loop:


• “+=“, to tell program to run the loop again
• i+=1
• Means i=i+1

• If at first, value of i is 1, then after run i+=1, value of i now becomes 2.

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

• This is the way, we create a loop machine.


Get to understand the process
If more than one chance
a=random.randint()

Still have chance? No Fail

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:

A simple game, more than one round


• Let the computer to randomly generate an int number between 1 and 3.
Invite the user to guess the number (only have 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.
An example of solution:
Examples of potential results in terminal

• The result may be win:

• Or lose:
A typical Wrong solution:
• What will happen by using this?

• Tips: use Ctrl+c to stop your terminal! Or it may run forever.


Back to the 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 have 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.
Task:
• Please print your name 30 times in terminal.
• Use while loop to build it.
Task:
• Please create a function to print your name more than one times
at once automatically in terminal.
• Use while loop to build it.
• Parameter should be used to control how many times you print.
Task:
• Please print int numbers from 0-10 in terminal.
• Use while loop to build it.
Task:
• Please print numbers from 0-10 in terminal.
• Use while loop to build it.

• Please create a function to print a sequence of numbers at once


automatically in terminal.
• Use while loop to build it.
• Parameters should be used to control the start point and end
point.
More about VS Code
Get more familiar with VS Code
• Menu on the top:
• Edit
• Undo, Redo
• Cut, Copy, Paste
• Find, replace

• File
• Open
• Save

• Click mouse right key:


• Run Python → Run selection in terminal window (no continuity)
• Run in interactive window (has continuity) (you need to install some extensions)
You could explore more extensions
More about Data Types
Data Type
• 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:

integer with dot,⼩數


Data Type
• 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:
blue: taught
red: going to teach

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

• For single value:


• Integers
• Float
• String
• Boolean

• For a set of values:


• List
• Tuple
• Set
• Dictionary
• Range
Data Type- For single value
• Integers
• no limit to how long an integer value can be. Of course,
it is constrained by the amount of memory your system
has, as are all things, but beyond that an integer can be
as long as you need it to be.
• Floating-Point Numbers
• float values are specified with a decimal point.
• String letter
• Strings are sequences of character data.
• String literals may be delimited using either single or
double quotes. All the characters between the opening
delimiter and matching closing delimiter are part of the
string.
• Boolean Type
• Objects of Boolean type may have one of two values,
True or False (Be careful, the first letter should be
capitalized.)
Boolean Type
• It is special, try to understand it.
• 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:

• if else is based on whether the condition is True or False.


Data Type
• 9 most commonly used data types:

• For single value:


• Integers
• Float
• String
• Boolean

• For a set of values:


• List
• Tuple
• Set
• Dictionary
• Range
Data Type for a set of values
List
• Lists are used to store multiple items in a single variable.
• List items are ordered, changeable, and allow duplicate values.
• Items can be of any data type.
• Lists could be directly created by using square brackets:

name = [“Andy", “Alice", "cherry"]

Variable name, multiple items, square brackets

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

• Tuples are written with round brackets (paren).

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


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

• Sets are written with curly brackets.


• set = {"apple", "banana", "cherry"}
Data Type for a set of values
Dictionary
• Dictionaries are used to store data values in key:value pairs.

• A dictionary is a collection which is ordered, changeable and do not


allow duplicates.
• Items can be of any data type
• Format:

Variable name= { Index : value }


Data Type for a set of values
Range
• The range() function is a built-in-function used in python, it is used to generate a
sequence of numbers.
• A range is a series of values between two numeric intervals.
• If you want to generate a sequence of numbers given the starting and the ending
values then you can give these values as parameters of the range() function. For
example: Starting value (5) is included

If you want to print all the items


you need to use for loop→ Ending value (12)
is not included. End at 11

• But you can also consider it as a data type. For example:


• The result is “range”, and it could be seen a data type.
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)
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.

• range (6) means range(0,6), means 0,1,2,3,4,5. Is this true?


• Let us try this code:
For loop
• No need to create a variable before the for.
• Just directly use a new variable in the for statement.
• A for loop is used for iterating over a sequence (that is either a list, a tuple, a
dictionary, a set, a range, or a string).
repeating
• Format:
for i in sequence:
statement

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,

• Loop 4: find no more items, the program stops.


For loop
• use for loop to iterate over a range from 0 to 3.

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

• Some of the fundamental characteristics of Python are its simplicity,


readability and flexibility, making it among the most popular and sought-
after skills to learn as a software engineer.

• Python has a huge community of developers that have contributed


hundreds of thousands of third-party packages.

• Python also includes several built-in packages, modules, and functions


out of the box that simplify adoption, increase developer productivity and
promote code consistency.
Open source
Build-in
• A set of functions→Module Or
Third party
Build-in
• A set of modules→Library/Package Or
Third party

• We can easily and freely use packages and modules


written by others to efficiently implement specific tasks
such as data processing, crawlers, dynamic charting,
machine learning, etc.
Python library/package from third parties
• Python library contains a collection of related modules and
packages
• Actually, library is often used interchangeably with “Python package”
because packages can also contain modules and other packages
(subpackages)

• 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

For example, install pandas:


In Windows system:
pip install pandas
In Mac:
pip3 install pandas

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 install, call the package/library


(in programming window)

import package name as a short nickname

• Give the package a short nickname


• Keep it short and easy to use in the following steps.
• This nickname can fully represent the package
• When you need to use the package, just call the nickname
instead of call the full name.
Pandas
• Pandas is a Python third-party library/package.
• Pandas is used to analyze data.

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.

• Our course is your starting point.

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

• Living in the digital age, this should be a lifelong learning process.


• The course is the beginning, not the end.
With ChatGPT, then, we still need to learn coding?
With ChatGPT, then, we still need to learn coding?
• Yes
With ChatGPT, then, we still need to learn coding?
• Yes
• Why?
With ChatGPT, then, we still need to learn coding?
• Yes
• Why?
• Think about this:
• We already know that:

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

• With ChatGPT, our programming knowledge can become more useful!

• Because we only need to have the most basic introductory programming


knowledge, then we can use ChatGPT to help us write very complex and
advanced programs!

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

• So you only need to have a basic knowledge of programming, and then


with ChatGPT’s help, you are free to move on to the next level. And even
faster to become an expert programmer.
+ ChatGPT
• Our simple knowledge Get more knowledge conveniently
Task:
• Create a function of your own (and write a comment about what
the function is for)

You might also like