Escape Characters in Coding
Coding 101 - Lesson 1: Hello World
Introduction
In this chapter, we will learn:
History of Python
Setting up the development environment
Introduction to the print and input functions
What is a Computer Program?
A computer comprises various electronic components:
Central Processing Unit (CPU)
Graphics Card
Memory (RAM)
Hard Drive, etc.
Software instructs the computer on its operations.
Software contains computer programs.
Computer programs are a set of instructions that the computer follows.
Understanding Programming Codes
Programming codes instruct a computer on its operations.
Different programming languages serve different purposes:
Scratch: For beginners, uses visual instructions.
Python: Suitable for various applications, including AI and data science. Ideal for those new to textual programming.
Python’s Readability
Here's a sample Python program. Even if you're new to Python, you might be able to guess its function due to Python's readability.
History of Python
Created by Guido van Rossum in the late 1980s.
Named after the BBC TV show "Monty Python's Flying Circus".
Python's design goals:
Simple and intuitive
Easy to read
Open-source
This course uses Python 3, the latest version.
Writing Your First Python Program
Let's begin with Python programming! Follow these steps to set up your workbook:
Click "Exercise Book" on the left
Click "Add exercise book"
Change the name of the exercise book to "Hello World"
Select "Local Execution"
Introduction to the Development Environment
An Integrated Development Environment (IDE) is where you write and run programs. Any code errors will be raised.
Examples include IDLE, PyCharm, etc.
Each IDE offers unique features.
Using the Jupyter Notebook
In this course, we'll use the Jupyter notebook as our IDE.
Check the accompanying video for a demonstration.
Understanding the Print Function
printis a function that displays its argument.Functions execute specific tasks.
Proper Syntax with the Print Function
Python is case-sensitive.
Ensure correct spelling and capitalization with
print.Incorrect usage will lead to errors. Try it out!
Syntax with Strings in the Print Function
Strings must be enclosed in single (' ') or double (" ") quotes.
Incorrect usage will lead to errors. Try it out!
The Input Function
Run the input function and observe its behavior:
name = input("Please enter your name:")
print("Hi", name)
Understanding the Input Function
inputprompts the user to enter text.The entered text can be stored in a variable.
Our next topic will delve deeper into variables.
Summary
We've covered:
Python's history
Using the IDE to write and execute programs
The print and input functions
The next chapter will focus on variables.
Chapter Two: Variables
Introduction
In this chapter, we will learn:
Understanding variables
Creating and utilizing variables
Exploring variable types
What is a Variable?
In Algebra: Symbols like
xandπrepresent unknowns or values.In Programming: Variables store data useful for program execution.
Types include numbers, strings, and boolean values.
Examples to Conceptualize Variables
Think of a variable as a box:
Store values inside.
Retrieve values from it.
Variable types: Integer, Floating Point, String
Using Variables
Using Variables:
Store a value.
Retrieve and utilize the value.
For instance, capture user input and display it.
Create a variable
nameand store the text value entered by the user in the variable.Read the value stored in the variable
nameand print it.
Creating and Using Variables
Assignment: Use
=to store a value in a variable.Example 1:
a = 1
b = "Hello world"
c = True
Variable Assignment
The right side can be any expression.
The expression's result is assigned to the variable.
Overwriting Variables
Variables can be reassigned.
For instance, if
astarts as 1 and is changed to 3:
a = 1
a = 3
Output:
ais now 3.
Understanding Comments
Comments explain the program.
They start with
#and are ignored during execution.
Naming Variables: Rules
Comprised of letters, numbers, and underscores.
Cannot start with a number.
Reserved words in Python can't be used.
Case-sensitive: "name" and "Name" are distinct.
Examples of Variable Naming
Legal Names:
name = "David"
bmFtZQ_ = "This is okay"
st111 = "This is also okay"
Illegal Names:
two words = "This will give an error"
NotOkay = "This will give an error too"
if = "This will also give an error"
Importance of Naming
Variable names should reflect their purpose.
Clear naming improves code readability.
Types of Variables
Variables can hold different data types:
Numbers (e.g., 1, 213, 4.5)
Strings (e.g., 'c', "Hello")
Boolean (True or False)
Summary
We covered:
Variable concept and usage
Creation and utilization in Python
Basic variable types and determining value types
Up next: Delving into numbers and arithmetic operations in Python.
Chapter 3 (Section 1): Numbers
Introduction
Exploring numbers in Python
Understanding common arithmetic operations
Types of Numbers in Python
Integers (int): Whole numbers without decimal places
Floating Points (float): Numbers with decimals
Both types can be positive or negative
Determining Number Types
Use the
type()function to identify the type of a number.
Basic Arithmetic Operators
Introduction to common arithmetic symbols:
Operator
Description
Example
Result
+
addition
5 + 8
13
-
subtraction
9 - 4
5
*
multiplication
4 * 7
28
/
floating point division
7 / 2
3.5
%
modulus (remainder)
7 % 3
1
**
exponentiation
3 ** 4
81
Order of Operations
Python follows standard mathematical precedence (e.g., multiplication before addition).
Use parentheses
()to modify order of operations.Avoid using
[]and{}in arithmetic.
Demonstrating Operators
Example calculations and their results:
print(1 + 2 * 3) # Outputs 7 print((1 + 2) * 3) # Outputs 9Modifying Variables Based on Original Value
Examples:
Decrease AC temperature by 1 degree.
Deposit $500 in a bank.
Use expressions like
num = num + 1for modifications.
Examples of Variable Modifications
temperature = 24 balance = 10000 temperature = temperature - 1 balance = balance + 500 print(temperature) print(balance)Additional Common Operations
abs(): Obtain the absolute value.round(): Round a number to specified decimal places or nearest integerround(3.14159)outputs3round(3.14159, 2)outputs3.14
Hands-on Activity
Try out the given programs and observe their behavior:
print("Absolute value of -2 is", abs(-2)) print("5.6712 rounded to 2 decimal places is", round(5.6712, 2)) print("5.6712 rounded to the nearest integer is", round(5.6712))Generating Random Numbers
Use
random.randint(a, b)to get a random integer betweenaandb.The random module must be imported to utilize this function.
Summary
Covered:
Number types in Python.
Arithmetic operations and operators.
Absolute value, rounding, and generating random numbers.
Next: A deep dive into Python strings.
Chapter 3 (Section 2): Strings
Introduction
Delving into escape characters
Exploring common string operations
Introduction to Strings
In Python, literals are enclosed in single (
') or double (") quotes.Without quotes, Python interprets it as a variable or number.
Consistency in using quotation marks is essential.
String Examples
Example:
my_text = "Hello" print(my_text) print('my_text') print(Hello)Outputs:
Hello my_text NameError: name 'Hello' is not defined on line 6The Challenge with Quotes in Strings
Using quotes within strings can lead to errors if not managed correctly.
Python may interpret a quote as a sign of the end of the string.
Handling Quotes in Strings
One method: If you're using one type of quote in the string, enclose the string with the other type.
Example:
print("He said, 'Hello'!")Escape Character for Quotes
Use the backslash (
\) before a quote to treat it as a regular character within a string.Example:
print('It\'s a nice day.')Additional Escape Characters
\n: Starts a new line.\t: Inserts a tab.Example:
print("One\t: 1\nTwo\t: 2\nThree\t: 3")Outputs:
One: 1 Two: 2 Three: 3Printing the Backslash
To print a backslash itself, use
\\.Example:
print(" / _ \")Outputs:
/ _ \String Operations
Use
+for string concatenation.Note: No spaces are added during concatenation.
To combine numbers with strings, convert the number using the
str()function.
Useful String Functions
len(): Returns the length of a string.count(): Counts occurrences of a substring in a string.Example:
text = "Hello World" print(len(text)) print(text.count('o'))Summary
We covered:
Understanding and using escape characters.
Common string operations and functions.
Up next: Exploring boolean values and conditional statements in Python.
Chapter 3 (Section 3): Boolean Values
Introduction
Introduction to boolean values
Exploration of logical operators
Decision Making in Daily Life
Examples of daily decisions influenced by changing conditions:
Example 1: You're about to head to the airport, but the news comes in about traffic jams. What are you going to do?
Example 2: You're planning to go on a picnic tomorrow, but the weather forecast says it's going to rain, what do you do?
Understanding Boolean Values
Conditions: Statements that can be evaluated as true or false.
Decisions are based on these conditions.
Examples: Is it raining? Is the number greater than 3?
Expressing Conditions
Introduction to relational operators for creating conditions.
Operator
Name
Example
< | Less than | x < y | | <= | Less than or equal to | x <= 5 | | >
Greater than
x > y
>=
Greater than or equal to
x >= 8
Boolean Value Examples
Demonstrating outputs of conditions.
Conditions yield only two results: True or False.
True and False are boolean values.
Assigning Boolean Values
Demonstrating how to assign boolean values to variables.
result = True print(result)Using Equality Operators
Introduction to determining equality between two values.
Operator
Name
Example
==
Equal to
x == y
!=
Not equal to
x != 5
Distinguishing Between
=and====: Used for comparison (to determine equality).=: Used for assignment (to assign a value to a variable).
Demonstrating Equality Operator
Example:
x = 7 y = 6 print(x == 7) # True print(y != 6) # FalseLogical Operators in Python
Introduction to the three logical operators:
and,or,not.Operator
Description
Example
and
True if both are true
a > 0 and a < 10 | | or | True if at least one is true | a < 0 or a > 10
not
True if false
not (a > 0)
Using
andandorOperatorsDemonstrating how logical operators work with true and false conditions.
Example scenarios demonstrating truth values using
andandor.
Using the
notOperatornot: Inverts the truth value of a condition.Example:
a = True print(not a) # Outputs FalseLogical Operator Examples
Demonstrates the use of logical operators. - Example:
x = 2 y = 5 print(x > y and y > 3) # Outputs False print(x < y or y > 10) # Outputs True print(not x < y) # Outputs FalseSummary
Covered:
Introduction to boolean values.
Understanding and using logical operators.
Up next: Delving into conditional statements in Python.
Chapter 4 (Section 1): Conditional
ifStatementsIntroduction
Understanding conditional statements.
Using conditions to control program flow.
Topics to cover:
Flowcharts
ifconditional statements
Real-life Conditional Examples
Example 1: "If it doesn't rain tomorrow, we'll go swimming."
Condition: It doesn't rain tomorrow.
Action: We'll go swimming.
Actions are executed when conditions are met.
Flowcharts & Conditionals
Flowcharts help visualize conditional statements.
They guide program flow based on conditions being true or false.
The Value of Flowcharts
Flowcharts aid beginners in understanding conditionals.
They help in planning the program's logic.
Flowchart Components
Rectangles represent program actions or operations.
Diamonds represent decisions or conditions.
Example: Print "You qualify for an elderly discount."
Flowchart Conditional Representation
Diamonds represent decisions or conditions.
Two arrows from diamonds direct program flow:
"T" (True): Path for when the condition is met.
"F" (False): Path for when the condition is not met.
Flowchart Start and End
Rounded rectangles indicate the beginning and end of a program.
Applying the
ifStatementThe
ifstatement is followed by a condition.Commands indented under the
ifare executed when the condition is true.
Syntax of the
ifStatementConditions in
ifstatements end with a colon (:).Commands under the
ifshould be indented.
Importance of Indentation: An Example
Consider two programs taking age as input.
Different outputs based on indentation.
Why do they differ?
Explaining the First Program
The "Good Bye" print statement is within the
ifscope (i.e. part of theifstatement).It only prints when age is greater than or equal to 60.
Explaining the Second Program
The "Good Bye" print statement is outside the
ifscope (i.e. not part of theifstatement).It prints irrespective of the age condition.
Visualizing with a Flowchart
Flowchart representation of the two programs discussed.
Highlighting the impact of indentation on program logic.
Importance of Consistent Indentation
Development environments often handle indentation.
Inconsistent indentation can lead to errors.
Example showcasing an indentation error:
Summary
Covered:
Using flowcharts for program planning.
Understanding and using conditional statements.
Up next: Detailed exploration of the
elseconditional statement.
Chapter 4 (Section 2): Conditional
elseStatementsIntroduction
The
elseconditionalUsing logical operators in
if...elsestatements
The
elseConditionalAn
ifstatement can optionally be followed by anelsestatement.When the condition in the
ifstatement evaluates to False, the code within theelseblock executes.
Key Points about the
elseConditionalelsecannot be used on its own; it must be paired with anif.A colon (:) follows
else.The statements inside the
elseblock must be indented.
Importance of Indentation
Activity: Input an age value less than 60 and observe the outputs of the two provided programs.
Highlight the significance of proper indentation.
Indentation Explained
First program: "Good bye!" is printed regardless of the age value.
This is because the print statement is outside the
elseblock.Second program: "Good bye!" is printed only if the age is less than 60.
Here, the print statement is indented inside the
elseblock.
Logical Operators
Previously discussed logical operators:
and,or, andnot.Their behaviors:
x and y: True if bothxandyare True.x or y: True if at least one ofxoryis True.not x: Opposite ofx.
Using Logical Operators in Conditionals
Activity: Run the provided program after modifying values for marks and
finish_all_homework.Note: Only one colon (:) is used at the end of the
ifstatement.
Summary
Covered:
The
elseconditional statement.Using logical operators in
if..elsestatements.
Up next: Detailed exploration of multiple
if..elsestatements and theelifconstruct.
Chapter 4 (Section 3): Conditional
elifStatementsIntroduction
Multiple
if...elsestatementsif...elif...elsestatement patternsLogical operators in
elifstatements
Multiple
if…elseStatementsAn
if...elsestatement can be nested inside anotheriforelsestatement.This enables more complex logic.
Note: Nested
if...elsestatements require additional indentation.
Activity
Experiment by inputting different option values to see program responses:
option = input("Enter your option (a, b, c): ") if option == "a": print("You entered a") else: if option == "b": print("You entered b") else: if option == "c": print("You entered c") else: print("Why you no listen")## Observation
The second program, which uses logical operators, yields the same output as the first program.
This demonstrates that multiple approaches can achieve the same result.
The
if...elifStatement PatternUseful when evaluating multiple conditions.
Instead of multiple nested
if...elsestatements, theif...elifpattern can be more streamlined.
Understanding
elifelifstands for "else if"It checks a new condition if the previous conditions were not met.
Instructions under
elifexecute when its condition is True.
Key Points about
elifelifmust follow anifstatement.It is followed by a condition and a colon (:).
The instructions under
elifmust be indented.
The
if...elif...elseStatement PatternAllows for multiple conditions and a fallback action.
If none of the
iforelifconditions are met, theelseblock executes.
Guidelines for Using
if...elif...elseThe
elsestatement directly follows a colon (:) and its block is indented.While multiple
elifstatements are allowed, only oneelsestatement is permitted.
Activity: Logical Operators with
elifAnalyze the provided program that incorporates logical operators in
elifstatements.
Summary
Covered:
Multiple
if...elsestatementsif...elif...elsestatement patternsLogical operators in
elifstatements
Next: A detailed look into Python loops.
Chapter 5 (Section 1): The
whileStatementsIntroduction
The
whileloopThe concept of a count variable
Introduction to
whileloopComparing two programs that both print numbers from 1-100.
These programs showcase how to instruct a computer to execute repetitive tasks:
print(0) print(1) print(2) ... # continutes up to 100Program 2:
number = 0 while number <= 100: print(number) number = number + 1Flowcharts
Flowcharts help visualize how loops control program flow.
Observe the differences between the two flowcharts provided.
Analyzing the First Flowchart
Demonstrates the use of the
ifconditional statement.Steps:
Prompt the user for a password.
Verify if the password is correct.
If correct, log the user in and display "Welcome".
Conclude the login process.
Analyzing the Second Flowchart
Describes the use of a loop statement.
Steps:
Prompt the user for a password.
Verify if the password is correct.
If correct, log the user in and display "Welcome".
If not, revert to the first step.
End the login process once the correct password is entered.
The
whileloopA mechanism that repeatedly executes instructions based on a Boolean condition.
Syntax is similar to the
ifstatement.The loop continues to run the indented instructions as long as the condition remains True.
whileLoop ExampleThe program will continually prompt the user for a password until the correct one is provided:
password = input("Please enter your password:") while password != 'MyPassword': password = input("Incorrect password, please try again:") print("Welcome!")Count Variable
The
whileloop is often used when a task needs to be repeated a known number of times.The provided program will print a statement 10 times.
Note: The variable
iacts as a counter to track the number of repetitions.Example:
i = 1 while i <= 10: print(i) i = i + 1Count Variable Flowchart
Visual representation of the previous example.
i = 1 while i <= 10: print(i) i = i + 1Terminating Loops
Every loop example given must have a statement that renders the condition to eventually become False, allowing the loop to terminate.
Without such conditions, the loop will run indefinitely, resulting in an infinite loop.
Summary
This section covered:
The
whileloopThe concept of a count variable
Next, we'll delve into the
breakcommand in thewhileloop and its interaction with theif...elsestatement.
Chapter 5 (Section 2):
breakStatement in thewhileLoopIntroduction
The
breakcommandHow to utilize the
breakinstruction within loops
Combining
whileLoop andif...elseStatementThe
whilestatement can be paired withif...elsefor more complex tasks.Example: User login procedure.
trial_number = 1 while trial_number <= 3: password = input("Please enter your password: ") if password == "MyPassword": print("You're now logged in. Welcome!") trial_number = 4 else: print("Incorrect password.") trial_number += 1Flowchart Analysis
Illustrating the combination of
whileandif...elsestatements.Two decision diamonds represent:
The
ifconditional statementThe
whileloop condition
The
breakCommandIn the user login example, setting
trial_numberto 4 (when the correct password is entered) aims to exit the loop.The
breakcommand provides a direct way to achieve this:
trial_number = 1 while trial_number <= 3: password = input("Please enter your password: ") if password == "MyPassword": print("You're now logged in. Welcome!") break else: print("Incorrect password.") trial_number += 1Understanding the
breakCommandbreakexits the loop immediately, ignoring subsequent instructions.Important notes:
breakmust be used within a loop.Once
breakis executed, the loop terminates and subsequent commands inside the loop are skipped.
Utilizing the
breakCommandMultiple exit conditions can be managed conveniently using
break.The loop will terminate when:
The user enters the correct password.
The user enters three incorrect passwords (
trial_number > 3).
Example:
trial_number = 1 while trial_number <= 3: password = input("Please enter your password: ") if password == "MyPassword": print("You're now logged in. Welcome!") break else: print("Incorrect password.") trial_number += 1The
breakCommand with theelsePatternThe
elseblock after awhileloop executes when the loop condition becomes False.However, if the loop is exited using
break, theelseblock won't execute.
trial_number = 1 while trial_number <= 3: password = input("Please enter your password: ") if password == "MyPassword": print("You're now logged in. Welcome!") break # use 'break' instead of setting trial_number = 4 else: print("Incorrect password.") trial_number += 1 else: print("3 Wrong Guess.")Activity
Experiment with the given program, removing the
elsestatement.Observe how the behavior changes compared to the previous example:
import random secret = random.randint(1, 10) trial = 0 while trial < 3: number = int(input("Your guess: ")) if number == secret: print("Congratulations!") break trial = trial + 1 print("3 Wrong Guesses.")Summary
Covered:
The
breakcommand and its usage.
Up next: In-depth exploration of Python lists.
Chapter 6 (Section 2): The
forStatementsIntroduction
Reading list items using a
whileloopThe
forloopThe
rangefunction
Importance of Loops with Lists
Do you want to manually check price reductions for games in a wishlist or use a program?
How about converting game prices from USD to HKD one by one?
Using a list lets us automate repetitive operations on multiple items with loops.
Using a
whileLoop to Iterate Over ListsApart from accessing list items with their indices, we can use a
whileloop to iterate over a list.Example:
fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana'] i = 0 # Counter variable while i < len(fruits): # Use len() function to get the length of the list print(fruits[i]) i += 1 # Incrementing the counterThe
forLoopA more concise way to iterate over list items.
Note: Maintain proper indentation!
for {loop_variable} in {list}:Activity: for vs. while
Compare the given
forandwhileloop programs to determine which is more concise:
namelist = ['Alice', 'Bob', 'Charlie'] # Using the while loop i = 0 while i < len(namelist): print(namelist[i]) i += 1 print(10 * "=") # Using the for loop for name in namelist: print(name)Benefits of the
forLoopIt's more compact than the
whileloop for iterating over lists.In many cases,
whileloops with loop variables can be replaced withforloops.
The
rangeFunction (Part 1)When given a single value
n, the function produces numbers from 0 to n−1:
for i in range(8): print(i)The
rangeFunction (Part 2)With two numbers
mandn, it produces numbers frommto n−1:
for i in range(2, 8): print(i)Activity: Experiment with Range
Test the provided program and observe the output:
for i in range(10): print(i) print(10 * "=") for i in range(3, 9): print(i)Summary
Covered:
Reading list items using a
whileloopThe
forloopThe
rangefunction