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

Week 2, Python Comments, input, Data type convert, if else

The document provides an overview of basic Python concepts including comments, data types, and functions. It explains the importance of comments, introduces data types such as numbers, strings, and booleans, and details the use of built-in functions like print() and input(). Additionally, it includes tasks for users to practice getting input and displaying output in Python.

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 PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Week 2, Python Comments, input, Data type convert, if else

The document provides an overview of basic Python concepts including comments, data types, and functions. It explains the importance of comments, introduces data types such as numbers, strings, and booleans, and details the use of built-in functions like print() and input(). Additionally, it includes tasks for users to practice getting input and displaying output in Python.

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 PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 85

Week 2

Python: Comments, Functions, Data type convert, if else

Dr. Li Ruozhu
City University of Hong Kong
[email protected]
• Let’s review comment, data type, and function, and
learn a little bit more new things about them~
Enter comment: Why we need
comments?

• 1 Write to yourself. Because later maybe you will forget why you wrote this line. Once
forgotten, it is difficult to continue the project.
• 2 Write to your teammates. Facilitate teammates to immediately understand your purpose,
efficient teamwork.
• 3 Show the students when explaining. It is easy for students to understand what is going
on at the moment.
• 4 When writing programs, temporarily save the content that you don't need but don't want
to delete, so that the process of thinking and input could be smoother.
• Format:
• Starting by #
• Enter human language naturally
3
3 Ways to Create Comments
• For single line:
• #

• For multiple lines:


• 3 quotation marks comments content 3 quotation marks

• Shortcut key in VS Code:


• Ctrl+/
• To converts single/multiple lines of program code into comments at once.
• If this doesn’t work, please check whether this website could help you:
Data Types
• Different data types have different writing formats.
• Python has many data types.
• Today you only need to know the most basic two.

• Number type: ---------for calculation

• Enter the number directly. E.g. 11334455

• Text type (string): --------------for text

• Wrap the content in double quotation marks. E.g. "apple"


• Single and double quotation marks can be used interchangeably 5
happens if you wrap a number in double quotation marks?
Data Types
• Number type:
• Enter the number directly. E.g. 11334455
• We can do some calculations and show the results using the print Function.
• +-*/

• Text type (string):


• Wrap the content in double quotation marks. E.g. "apple"
• Strings are used for representing textual data——a sequence of characters.
• We can try to combine two words into one word (by using +) and display the
result using the print Function.

• How to combine a number and a string?


• Use , 6
A New Data Type——Boolean
Type
• Objects of Boolean type may have one of two values, True or False (Be careful, the
first letter should be capitalized.)

• 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, please try the below lines, and check the answers in terminal :

• Boolean is special, try to understand it.


Now you already know 3 data types
• 1 Number
456

• 2 String
“apple”

• 3 Boolean
True False
print, Your First Function in Python
• print is a built-in Function of Python.
• No need to build it. Just directly use.
• A Function is a command you use to tell Python what to do.
• You could directly use built-in Functions, or build Functions by yourself.

• print, as a Function, is to make content show up to the user.


• Its format is:

• print ( )

• A English word (lowercase) A pair of parentheses (English pattern,


no space)
• Put the content you want to show the user in parentheses
• Then, run it. 9
Functions——Parameter
• Parameter is used to pass values into functions, to adjust the
behavior of the functions.
• So, when you want to learn how to make a function behave the
way you want, you need to learn what parameters the
function has that you can adjust freely.

• For example:
• print() is a function. What you put into the (), is the
Parameter/arguments.

• Function name paren parameter (actually, this parameter


called object)
Parameters of Print ()

• Full format of print():


• print(object(s), sep=separator, end=end, file=file,
flush=flush)
Parameters of Print ()

• Full format of print():


• print(object(s), sep=separator, end=end, file=file,
flush=flush)

• There are 5 parameters you can adjust:


• 1 object, 2 sep, 3 end, 4 file, 5 flush
• The first one is required and the last four are optional.
Parameters of Print ()

• Full format of print():


• print(object(s), sep=separator, end=end, file=file,
flush=flush)

• There are 5 parameters you can adjust:


• 1 object, 2 sep, 3 end, 4 file, 5 flush
• The first one is required and the last four are optional.
Parameter Description
object(s) Any object, and as many as you like. Will be converted to string before printed

sep='separator' Optional. Specify how to separate the objects, if there is more than one. Default
is ' '
end='end' Optional. Specify what to print at the end. Default is '\n' (line feed)

file Optional. An object with a write method. Default is sys.stdout

flush Optional. A Boolean, specifying if the output is flushed (True) or buffered (False).
Default is False
Parameters of Print ()

• Full format of print():


• print(object(s), sep=separator, end=end, file=file,
flush=flush)

• There are 5 parameters you can adjust:


• 1 object, 2 sep, 3 end, 4 file, 5 flush
• The first one is required and the last four are optional.
Parameter Description
object(s) Any object, and as many as you like. Will be converted to string before printed

sep='separator' Optional. Specify how to separate the objects, if there is more than one. Default
is ' '
end='end' Optional. Specify what to print at the end. Default is '\n' (line feed)

file Optional. An object with a write method. Default is sys.stdout

flush Optional. A Boolean, specifying if the output is flushed (True) or buffered (False).
Default is False
Parameters of Print ()
• Print three messages together, and specify the separator as
you wish:

• End a print statement with any character/string you want,


instead of skiping to the next line.
Your Second Function in Python
• print() is for transferring data from computer to the
user(terminal)
• What is for data transferring data form the user to the
Developer
computer?
User/
print() Terminal


input, Your Second Function in
Python
• print() is for transferring data from computer to the
user(terminal)
• input() is for data transferring data form the user to the
Developer
computer
User/
print() Terminal

input()
input, Your Second Function in Python
• A Function is a command you use to tell Python what to do. You could directly use built-in
Functions.

• input, as a Function, is to give the user a way to speak to the program by keying in text.
• The input() function pauses the program while it waits for the user to type some text.
Use input() to take user’s
• Its format is: input

• input ( “” )
• A English word (lowercase) A pair of parentheses (English pattern, no space)
• Put prompt into quotation mark. Prompt is the text we wish to display on the screen. It is optional.
• Then, run it.
• For example:

• And then, in terminal, the prompt will show up.

• And user can enter text after the prompt, in terminal, and then press Enter key.
input, Your Second Function in Python
• Most of the time we want to store the text that the user entered.
• So we need a variable (container) to store it as the data.
• How to do this?

• k=input(“Please enter your name:”)

• Variable, equal sign, input, paren, quotation mark, a prompt that prompts the
user to enter

• When python gets the user‘s input text, it stores the text the user
keyed in (as data) into the variable on the left side of the equal
sign.
• And then, we can use this variable.
Task:
• We need to get the user's name and then show a
greeting with a specific name on the screen.
Task:
• We need to get the user's name and then show a
greeting with a specific name on the screen.

• This is a very simple example, but I hope you to start thinking


logically about how to turn tasks into programming.
• Drawing a flowchart is a helpful tool for thinking.
• In general, start with the end result.
• The result should be, showing a sentence on the screen “Hello,
XXX. Nice to meet you!”
• To get this result, what should we do? What function should we
use?
Flowchart help thinking

show a sentence on the screen “Hello, XXX. Nice to meet you!” (XXX is the user’s
Flowchart help thinking

Use function print(). print(“Hello, XXX. Nice to meet you!”)

show a sentence on the screen “Hello, XXX. Nice to meet you!” (XXX is the user’s
Task:
• We need to get the user's name and then show a
greeting with a specific name on the screen.

• In general, start with the end result.


• The result should be, showing a sentence on the screen “Hello,
XXX. Nice to meet you!”
• To get this result, what should we do? What function should we
use?
• print(“Hello, XXX. Nice to meet you!”)
• But we don’t know the specific name of the user. How to get
the name?
Flowchart help thinking

XXX is not what we want. We need to get user’s name.

Use function print(). print(“Hello, XXX. Nice to meet you!”)

show a sentence on the screen “Hello, XXX. Nice to meet you!” (XXX is the user’s
Flowchart help thinking

Use input() to get user’s name. input(“Please enter your name:”)

XXX is not what we want. We need to get user’s name.

Use function print(). print(“Hello, XXX. Nice to meet you!”)

show a sentence on the screen “Hello, XXX. Nice to meet you!” (XXX is the user’s
Task:
• We need to get the user's name and then show a
greeting with a specific name on the screen.

• In general, start with the end result.


• The result should be, showing a sentence on the screen “Hello,
XXX. Nice to meet you!”
• To get this result, what should we do? What function should we
use?
• print(“Hello, XXX. Nice to meet you!”)
• But we don’t know the specific name of the user. How to get
the name?
• Use input
Flowchart help thinking

We need to put the user’s name into the greeting sentence

Use input() to get user’s name. input(“Please enter your name:”)

XXX is not what we want. We need to get user’s name.

Use function print(). print(“Hello, XXX. Nice to meet you!”)

show a sentence on the screen “Hello, XXX. Nice to meet you!” (XXX is the user’s
Flowchart help thinking
eate a variable to store the input and put this variable into the greeting sentence

We need to put the user’s name into the greeting sentence

Use input() to get user’s name. input(“Please enter your name:”)

XXX is not what we want. We need to get user’s name.

Use function print(). print(“Hello, XXX. Nice to meet you!”)

show a sentence on the screen “Hello, XXX. Nice to meet you!” (XXX is the user’s
Task:
• We need to get the user's name and then show a greeting
with a specific name on the screen.

• In general, start with the end result.


• The result should be, showing a sentence on the screen “Hello, XXX.
Nice to meet you!”
• To get this result, what should we do? What function should we use?
• print(“Hello, XXX. Nice to meet you!”)
• But we don’t know the specific name of the user. How to get the
name?
• Use input
• How to store the name and put the name into the sentence?
• Create a variable.
Flowchart help thinking, a simple one:
Create a variable.

To store name and put name into the sentence

Use input().

To get user’s name.

Use print().

To show a sentence
Flowchart help thinking
Create a variable.

To store name and put name into the sentence

Use input().

To get user’s name.

Use print().

To show a sentence
Flowchart help thinking
Create a variable.

To
result store name and put name into the sentence

Use input().

result To get user’s name.

Use print().

result To show a sentence


Flowchart help thinking
solutionCreate a variable.

To store name and put name into the sentence

solutionUse input().

To get user’s name.

solutionUse print().

To show a sentence
Flowchart help thinking
solutionCreate a variable.

To
result store name and put name into the sentence

solutionUse input().

result To get user’s name.

solutionUse print().

result To show a sentence


Flowchart help thinking
To do√ solutionCreate a variable.

To
result store name and put name into the sentence

To do√ solutionUse input().

result To get user’s name.

solutionUse print().

To do√ result To show a sentence


Flowchart help thinking
To do√ solutionCreate a variable.

To
result store name and put name into the sentence

To do√ solutionUse input().

result To get user’s name.

solutionUse print().

To do√ result To show a sentence


Flowchart help thinking
To do√ solutionCreate a variable.

To
result store name and put name into the sentence

To do√ solutionUse input().

Thinking direction

result To get user’s name.

solutionUse print().

To do√ result To show a sentence


Flowchart help thinking
To do√ solutionCreate a variable.

To
result store name and put name into the sentence

To do√ solutionUse input().

Thinking direction Writing direction

result To get user’s name.

solutionUse print().

To do√ result To show a sentence


Programming

or

Prompt shows in terminal:

User key in name in terminal:

Result in terminal:
AI assistant
• Please run above program in anaconda.cloud
• And seek its AI assistant’ help to deepen your
understanding of the program
• And get some advice from the AI to improve the
program
What about input numbers ?
• Use input(), the data we get is always string.
• But sometimes what we want to input is a number that
we can calculate.
• How to convert text into numbers?
Data Types
• Number type:
• Enter the number directly. E.g. 11334455
• We can do some calculations and show the results using the
print Function.
•+-*/

• Text type (string):


• Wrap the content in double quotation marks. E.g. “apple”
• We can try to combine two words into one word and display
the result using the print Function.

43
Convert Data Types
• Text type (string) →Number type (integer)

• int()

• Number type (integer) → Text type (string)

• str()

• Check data type


• Use type() and print() together

44
• print(type())
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.
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.
Task:
• Ask the user to enter his age, and then you help him
calculate the year he was born. Then you display the
results on the screen.
Task:
• Ask the user to enter his age, and then you help him
calculate the year he was born. Then you display the
results on the screen.
• Till now, what can we type in the Python by using VS code
as the IDE?

• 1 Programing: communicate to Python. For example, print(1+1)

• 2 Comments: communicate to human being. For example, #


example in class

• 3 VS code command: communicate to VS code. For example, cls


(in terminal)

• 4 Input as the user of the Program: pretend to be a user and


communicate to the program you created. For example, run
input(), and key in answer in terminal 49
• Ok, now let’s learn some really new stuff~
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.
Flowchart help thinking

welcome sorry
Flowchart help thinking

Andy Not Andy

welcome sorry
Flowchart help thinking

judgment

Andy Not Andy

welcome sorry
Flowchart help thinking

Get user’s name

judgment

Andy Not Andy

welcome sorry
Flowchart help thinking
result

result Get user’s name

result judgment

result Andy Not Andy

result welcome sorry


Flowchart help thinking

Get user’s name

judgment

Andy Not Andy

welcome Print() sorry Print()


Flowchart help thinking

Get user’s name

judgment

Andy Not Andy

welcome Print() solution sorry Print() solution


To do√ To do√
Flowchart help thinking

Get user’s name Variable, input() solution


To do√

judgment

Andy Not Andy

welcome Print() solution sorry Print() solution


To do√ To do√
Flowchart help thinking

Get user’s name Variable, input() solution


To do√

judgment ???

Andy Not Andy

welcome Print() solution sorry Print() solution


To do√ To do√
Condition Statement
• It is used to make judgments about which path to take next.
• Conditional statements are part of every programming language. With
conditional statements, we can have code that sometimes runs and at
other times does not run, depending on the conditions of the program at
that time.
• By using conditional statements, programs can determine whether certain
conditions are being met and then be told what to do next.

• if else (if elif else)


• for
• while
If else
• We will start with the if statement (that is the condition/judgement),
which will evaluate whether a statement is true or false, and run code
only in the case that the statement is true.

• Format:

Line 1 if condition colon


Next line indentation order

Next line else colon


Next line indentation order
If else
• We will start with the if statement (that is the condition/judgement),
which will evaluate whether a statement is true or false, and run code
only in the case that the statement is true.

• Format:
Line 1 if condition colon
Next line indentation order
Next line else colon
Next line indentation order

Colon and indentation indicate the


structure!
If else
• We will start with the if statement (that is the condition/judgement),
which will evaluate whether a statement is true or false, and run code
only in the case that theCondition
statement is true.
(judgment) colon
• Format:
order
if

indentation

else

indentation order

colon

if condition colon next line indentation order


else colon next line indentation order
Signs used to make judgments
(serve as the condition)

•>
•<
• >=
• <=
• ==
• !=
Signs related to “=“, be careful!
• =
• Single equal sign
• Means “put into”
• Put data (on the right) into the variable (on the left)

• ==
• 2 equal signs
• Means “is equivalent to”
• Judge or claim
• It is used to determine whether the left and right sides of an equal sign
are exactly equal.

• !=
• Exclamation point and equal sign
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.
Flowchart help thinking

Get user’s name Variable, input()

judgment ???

Andy Not Andy

welcome Print() sorry Print()


Flowchart help thinking

Get user’s name Variable, input()

judgment if else

Andy Not Andy

welcome Print() sorry Print()


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.

• Be careful, we use “or” in the if statement to make sure


both “Andy” and “andy” could be identified:
• if Name=="Andy" or Name=="andy":
Task:
• If a user tells you name is Andy, then welcome him and
tell him he is allowed in. If a user tells you the name is
Alice, then let the user wait. Users with other names
should be told they are not allowed in.
Task:
• If a user tells you name is Andy, then welcome him and
tell him he is allowed in. If a user tells you the name is
Alice, then let the user wait. Users with other names
should be told they are not allowed in.
Task:
• There is a system for evaluating civil servants
• Citizens gave civil servants marks on a scale of 1 to 100
• Let’s say you are working in a department of the government
• Your department requires you to convert the raw data into grades (A-F)

• Greater than or equal to 75, A


• Greater than or equal to 60, less than 75, B
• Greater than or equal to 50, less than 60, C
• Greater than or equal to 40, less than 50, D
• Less than 40, Fail
Try to use if else first:
When there are many paths:
• Use if-elif-else
• Make the coding more concise and better organized.

• In Python, elif is short for "else if" and is used when the
first if statement isn't true, but you want to check for
another condition. Meaning, if statements pair up with
elif and else statements to perform a series of checks.

• Only the block of code associated with the first true elif
condition encountered will be executed.
Try to use if-elif-else:
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

You might also like