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

ENGG1003 Lab08 PythonBasics

This document provides instructions for Lab 08 activities in the ENGG1003 Digital Literacy and Computational Thinking course. It discusses setting up Python on one's computer by following an installation guide. It also covers properly saving one's work in an organized folder structure. The lab activities include practicing using variables and expressions interactively in Python, using basic commands like input(), data types, if/elif/else statements, and printing number sequences using for loops. Students are instructed to upload and submit their saved Python files to Blackboard. Two coding tasks are described - one involving calculating circumference of a circle from user input radius, and another involving concert ticket pricing based on seat number and student membership status.

Uploaded by

蛇精男
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

ENGG1003 Lab08 PythonBasics

This document provides instructions for Lab 08 activities in the ENGG1003 Digital Literacy and Computational Thinking course. It discusses setting up Python on one's computer by following an installation guide. It also covers properly saving one's work in an organized folder structure. The lab activities include practicing using variables and expressions interactively in Python, using basic commands like input(), data types, if/elif/else statements, and printing number sequences using for loops. Students are instructed to upload and submit their saved Python files to Blackboard. Two coding tasks are described - one involving calculating circumference of a circle from user input radius, and another involving concert ticket pricing based on seat number and student membership status.

Uploaded by

蛇精男
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 33

ENGG1003

Digital Literacy and


Computational Thinking - P

Lab 08 Python Basics


2023-24 Term 2
Setup Python on Your Computer
(Recap)
 Download and follow the steps on Blackboard
 InstallationGuide_python_Win11_macOS.pptx
 Windows users: slides 1 – 6
 macOS users: slides 7 – 15

 You may also work on your VM !


Save Your Work Properly
(Recap)
 Setup your own filing system: create a folder for
your works in ENGG1003
 Keep on your own computer, e.g., Documents
 Keep on portable storage such as USB drive
 Keep on cloud storage such as OneDrive (CUHK
O365)

 Folder structure is hierarchical, i.e., tree-like


with branches called sub-folders
Lab 08 Activities

 Practice using variables and expressions interactively

 Use of basic python commands


 input(), data types such as int() and float() commands

 Solving problems using if: elif: else:

 Last problem, print number sequences using for:

 Upload and submit your saved files to Blackboard

 Bonus exercise
 To try and practice while loop
Variables and Expressions
temperature = 24.6
humidity = 0.75 Key-in OR copy-and-paste
print(temperature > 24) one line at a time!
print(humidity > 0.85)
 Practice on print(temperature >= 24 or humidity < 0.7)
print(22 < temperature < 28)
IDLE (Python) approx_dew_point = temperature - (100 - humidity * 100) / 5
print('Dew point =', approx_dew_point)
Execute a batch of codes
 Feel troublesome?
 If you have a batch of codes to be executed (like the codes
in the previous slide, it is good to create a python
(program) file by Python IDLE.
 Start up the Python IDLE, you will see the Python Shell
environment.
This is Python Shell
environment. We can
enter and execute code
one-by-one only.
Execute a batch of codes
 Click on “File” from menu ribbon, then click “New
File”, a new window with the name “untitled” will be
prompted.
 This is the Python editor. We can type in a batch of
codes here and execute them together. It will help to
organize the execution of codes.

This is Python editor. We


can enter and execute a
series of codes together.
Execute a batch
of codes
 Try to type in the example codes to the
editor.
 Click Run  Run Module, or click [F5] key.
 Python editor request to save the file (.py)
before execution. Let’s save the file as
“Lab08Example.py” [F5] : Execute the python
(Lab08Example.py) file
 The Python IDLE Shell will show the output(s)
of the corresponding python program file
“Lab08Example.py” in IDLE Shell.
 This is convenience to make corrections
that if the codes contain any mistakes.
 Enjoy your programming~!
TASK 1
Task 1 - User Input: Coding basic
mathematical operations

 Write a python code to calculate circumference of a circle.


 Formula :
 Here, c = Circumference of the circle
 Pi ≅ ≅ Constant with value 3.1416
 r = radius of the circle
 In this task you are going to practice
 input() statement,
 understand different datatypes and
 print() statement
 Unit of measurement is NOT indicated in the calculation
Task 1 - User Input: basic
mathematical operations

 To start, download the “task1.py” file from the blackboard.


 It is always better to understand what is your workspace. And
therefore, always keep your downloaded file in your workspace
for easy use.

 To open “task1.py” file, launch IDLE Python, click File 


Open  browse and pick task1.py  click Open.

 Check the code in the file. Read the comments. And begin
to write your code.
Task 1 - User Input: basic
mathematical operations
Anything that starts with # is a comment which is not executed
#Task 1: Calculate the circumference of the circle.

pi = 3.1416

# Display the input prompt "Enter the value of radius in cm :" to obtain r from user
Use the input( ) command along with a message “Enter the
r = int( ))
value of radius : ”, to request the value from the user Try test cases.
# Implement the equation to calculate the circumference of the circle
Given r : 3
# Fill your code on the line below…
Implement the formula Expected ans:
18.8496
# Print the message, "The circumference of the circle is :", followed by c

print( ) Print the message “The circumference of the circle is :”


and the value of c on one line Given r : 5
Expected ans:
 31.416
Run  Run Module [F5] to check your result.
 Save the “task1.py” python file in your working folder
Task 1 - Submission

 Once you complete the task, upload “task1.py” file to


Blackboard

 Make sure the submitted file “task1.py” contains your


complete work, NOT the raw initial given file.
Task 2
Task 2: Using user input function
and if-elif-else statements

 Task 2 is divided into two parts, task 2a and task 2b.

 We are going to deal with concert ticketing.


 Understand the application will help in completing your tasks

 You will implement and practise:


 input() statement
 if-else statement
Task 2a: Using user input function
and if-elif-else statements

 Application problem statement: CUHK is going to organize


a digital concert, with the following fare table.
CUHK DIGITAL CONCERT 2024
Arena Seat Number Range Ticket Price (HK$)
Arena A 61 – 100 50
Arena B 31 – 60 70
Arena C 11 – 30 90
Arena D 1 – 10 150

 We request user to input a seat number.


 For ticketing, you need to implement ticketing structure
based on the seat numbers with the help of if-elif-else
statement.
Task 2a: Using user input function
and if-elif-else statements

 For example: When you run your code, the code must ask
the user to input a seat number that the user want to
reserve. Based on the seat number, your code should
charge the ticket to the user.
 To start the task, download “task2.py” file from the
blackboard.
 To open “task2.py” file, launch IDLE Python, click File 
Open  browse and pick task2.py and click Open.
 Check the code in the file. Read the comments. And begin
to write your code.
Work on Task 2a First
# Task 2a : Implement the if-else statements

print('Welcome to the CUHK Digital Concert 2024')

sn = int(input('Please enter the seat number you want to reserve for yourself
(enter a number from 1 to 100) : '))
if seat number (sn) is greater or equal to 1
# Implement the if-elif-else statements below:
and sn is less than or equal to 10 then:
ticket_price shall be 150
elif ...:
ticket_price shall be ...
elif ...:
ticket_price ...
else:
print("Invalid data")
# Task 2b: Check the status of student society membership information using if
ticket_price = 0
statement and implement the equation to calculate the new discounted ticket
exit()
price of the concert

#Remove the "#" from the line below

#sm = input('Are you a member of student society? (enter y/n) : ')

# Implement the if statement here and equation to calculated the discounted


price here
To check the result

print("You need to pay: $", ticket_price) Run  Run Module [F5] to check your result.
Save the “task2.py” python file in your working folder.
Task 2b: Using user input function
and if-elif-else statements

 Application problem statement: CUHK is going to organize


a digital concert, with the following fare table.
CUHK DIGITAL CONCERT 2023
Arena Seat Number Range Ticket Price (HK$)
Arena A 61 – 100 50
Arena B 31 – 60 70
Arena C 11 – 30 90
Arena D 1 – 10 150

 Give 10% discount if the student has society membership


Task 2b: Using user input function
and if-elif-else statements

 Task 2a: ask the user for a seat number


 Task 2b: ask the user a y/n question about society membership
 If the user does not have society membership,
charged the user original ticket price according to fare table
 If the user has society membership, apply
updated ticket price = ticket price - 10% * ticket price

 To do this task continue with your own “task2.py” file,


 Read the comments for task 2b
 Complete the code
 Note: When you work on task2b, make sure you have completed
task2a first: task2b cannot work without task2a.
Task 2b FOLLOWS Task 2a
# Task 2a : Implement the if-else statements

print('Welcome to the CUHK Digital Concert 2024')

sn = int(input('Please enter the seat number you want to reserve for yourself (enter a
number from 1 to 100) : '))

# Implement the if-elif-else statements below:

if ...:
ticket_price shall be 150
elif ...:
...
else:
...

# Task 2b: Check the status of student society membership information using if statement and
implement the equation to calculate the new discounted ticket price of the concert

# We shall remove the "#" from the line below, like this: Leading # sign removed
sm = input('Are you a member of student society? (enter y/n) : ')

# Implement the if statement here and equation to calculate the discounted price here

if student membership is equal to "y": To check the result


ticket price = ticket price – ticket price *
0.1 Run  Run Module [F5] to check your result.
print("You need to pay: $", ticket_price) Save the “task2.py” python file in your working folder.
Task 2a+2b: Submission

 Save the “task2.py” python file in your working folder

 Once you complete BOTH tasks 2a and 2b in the same file,


upload “task2.py” file to Blackboard

 Make sure the submitted file “task2.py” contains your


complete work, NOT the raw initial given file.
Task 3
Task 3: Use for loop statement

 In task 3, you are going to implement and practise for


statement, a kind of looping/repetition construct.
 We have to generate a number series from 1 to 50, AND
print only the even numbers.
 There are different solutions indeed.
 How to check and single out the even numbers?
 Use the modulo/remainder (%) operator
 For example: (7 % 2) gives 1
 Another example: (48 % 2) gives 0
Task 3: Use for loop statement

 We may generate a number series starting from number


1 using for statement with a range().

 For each number generated in the for loop, we apply


the modulo operator and check the remainder
 If the remainder of the modulo operator is zero, then it is
an even number; otherwise it is not.
 Print each even number one on a line

 To open “task3.py” file, launch IDLE python, click File


 Open  browse and pick task3.py  click Open.

 Check the code in the file. Read the comments. And


Task 3: Hints

 Problem statement: Print only the even numbers from 1


to 50 using a for loop and the modulo operator

# Task 3: Print only the even numbers from 1 to 50 using a for loop and the modulo operator

print("Print even numbers only")


for
if for i in the range of 1, XX
print() if i modulo 2 is equal to 0
print(the value of i)

 Run  Run Module [F5] to check your result.


Task 3: Submission

 Once you complete the task, upload “task3.py” file to


Blackboard

 Make sure the submitted file “task3.py” contains your


complete work, NOT the raw initial given file.
Task 4
Bonus Task 4 : Guessing Game
- using while statement
 Task 4 is a bonus task. In this task you will work on a
password guessing game.
 In this task you will use while loop and if-else statement
to complete the task
 You all are encouraged to attempt the bonus task 4.
 Understanding the application problem will help a lot to
complete the bonus task 4
Bonus Task 4 : Guessing Game
- using while statement
 Application problem statement: ”Password guessing game”.
 It is a two-player game.
 Firstly, player 1 enters a secret password. The password is hidden during
input. For simplicity, we assume it contains only lowercase alphabets
AND it must have at least one character.
 The program provides 4 hints to player 2:
 Password length, i.e., number of characters
 Reveal the first character of the hidden password
 Reveal the middle character of the hidden password
 For password with even length, take the middle one nearer to the first half
 Reveal the last character of the hidden password
 Player 2 shall guess the secret password in 5 attempts only.
 The game ends on a correct guess OR after 5 attempts.
Bonus Task 4 : Guessing Game
- using while statement
 To start, download the “task4bonus.py” file from
Blackboard.
 Always keep your files in your workspace for easy use.

 To open “task4bonus.py” file, launch IDLE Python, click File


 Open  browse and pick task4bonus.py  click Open.

 Check the code in the file. Read the comments. And begin
to write your code.
#Task 4 - Bonus: Complete the guessing game (Complete the codes in red)

print('Welcome to the password guessing game!')

print('This game requires two people. One person will enter the password that is to be
guessed while the second person will guess the password.')

# Player 1 enters the password to be guessed


password = input('Player 1: Enter the password that is to be guessed: ‘)

for i in range(50):
print("Scrolling screen to hide player 1's password...")
prints the length of the password
# Print some hints for player 2
print('Hint 1: The length of the password is :', len(password) ) prints the first letter of the password

print('Hint 2: The first letter of the password is :', password[0])

# Complete the hints for the player 2 How to print the middle and the last
letter of the password?
print('Hint 3: The middle letter of the password is :', )

print('Hint 4: The last letter of the password is :', )

#Player 2 starts to perform the guesses to complete the task


print('Player 2:')
counter = 1 counter = 1
while while counter condition is valid for 5 attempts
guess = guess = request player 2 to "Enter a guess : "
if if the guess is same as the hidden password
print(" ") print "Congratulations! You guessed the correct password."
break quit the loop using the break statement
else else:
print(" ") print "Incorrect password. Try again."
counter counter = Update the counter of the while loop

print("End of the program.")


Bonus Task 4: Submission

 Once you complete the task, upload “task4bonus.py”


file to Blackboard

 Make sure the submitted file “task4bonus.py” contains


your complete work, NOT the raw initial given file.

You might also like