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:

    1. Click "Exercise Book" on the left

    2. Click "Add exercise book"

    3. Change the name of the exercise book to "Hello World"

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

  • print is 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

  • input prompts 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 x and π 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 name and store the text value entered by the user in the variable.

    • Read the value stored in the variable name and 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 a starts as 1 and is changed to 3:

a = 1  
a = 3  
  • Output:

  • a is 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 9  
    

    Modifying Variables Based on Original Value

    • Examples:

      • Decrease AC temperature by 1 degree.

      • Deposit $500 in a bank.

      • Use expressions like num = num + 1 for 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 integer

      • round(3.14159) outputs 3

      • round(3.14159, 2) outputs 3.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 between a and b.

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

    The 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: 3
    

    Printing 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)  # False  
        

        Logical 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 and and or Operators

          • Demonstrating how logical operators work with true and false conditions.

          • Example scenarios demonstrating truth values using and and or.

          Using the not Operator

          • not: Inverts the truth value of a condition.

          • Example:

          a = True  
          print(not a)  # Outputs False  
          

          Logical 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 False  
          

          Summary

          • Covered:

            • Introduction to boolean values.

            • Understanding and using logical operators.

          • Up next: Delving into conditional statements in Python.

          Chapter 4 (Section 1): Conditional if Statements

          Introduction

          • Understanding conditional statements.

          • Using conditions to control program flow.

          • Topics to cover:

            • Flowcharts

            • if conditional 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 if Statement

          • The if statement is followed by a condition.

          • Commands indented under the if are executed when the condition is true.

          Syntax of the if Statement

          • Conditions in if statements end with a colon (:).

          • Commands under the if should 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 if scope (i.e. part of the if statement).

          • It only prints when age is greater than or equal to 60.

          Explaining the Second Program
          • The "Good Bye" print statement is outside the if scope (i.e. not part of the if statement).

          • 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 else conditional statement.

          Chapter 4 (Section 2): Conditional else Statements

          Introduction

          • The else conditional

          • Using logical operators in if...else statements

          The else Conditional

          • An if statement can optionally be followed by an else statement.

          • When the condition in the if statement evaluates to False, the code within the else block executes.

          Key Points about the else Conditional

          • else cannot be used on its own; it must be paired with an if.

          • A colon (:) follows else.

          • The statements inside the else block 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 else block.

          • Second program: "Good bye!" is printed only if the age is less than 60.

          • Here, the print statement is indented inside the else block.

          Logical Operators

          • Previously discussed logical operators: and, or, and not.

          • Their behaviors:

            • x and y: True if both x and y are True.

            • x or y: True if at least one of x or y is True.

            • not x: Opposite of x.

          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 if statement.

          Summary

          • Covered:

            • The else conditional statement.

            • Using logical operators in if..else statements.

          • Up next: Detailed exploration of multiple if..else statements and the elif construct.

          Chapter 4 (Section 3): Conditional elif Statements

          Introduction

          • Multiple if...else statements

          • if...elif...else statement patterns

          • Logical operators in elif statements

          Multiple if…else Statements

          • An if...else statement can be nested inside another if or else statement.

          • This enables more complex logic.

          • Note: Nested if...else statements 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...elif Statement Pattern

          • Useful when evaluating multiple conditions.

          • Instead of multiple nested if...else statements, the if...elif pattern can be more streamlined.

          Understanding elif

          • elif stands for "else if"

          • It checks a new condition if the previous conditions were not met.

          • Instructions under elif execute when its condition is True.

          Key Points about elif

          • elif must follow an if statement.

          • It is followed by a condition and a colon (:).

          • The instructions under elif must be indented.

          The if...elif...else Statement Pattern

          • Allows for multiple conditions and a fallback action.

          • If none of the if or elif conditions are met, the else block executes.

          Guidelines for Using if...elif...else

          • The else statement directly follows a colon (:) and its block is indented.

          • While multiple elif statements are allowed, only one else statement is permitted.

          Activity: Logical Operators with elif

          • Analyze the provided program that incorporates logical operators in elif statements.

          Summary

          • Covered:

            • Multiple if...else statements

            • if...elif...else statement patterns

            • Logical operators in elif statements

          • Next: A detailed look into Python loops.

          Chapter 5 (Section 1): The while Statements

          Introduction

          • The while loop

          • The concept of a count variable

          Introduction to while loop

          • Comparing 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 100
          
          • Program 2:

          number = 0
          while number <= 100:
           print(number)
           number = number + 1
          

          Flowcharts

          • 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 if conditional 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 while loop

          • A mechanism that repeatedly executes instructions based on a Boolean condition.

          • Syntax is similar to the if statement.

          • The loop continues to run the indented instructions as long as the condition remains True.

          while Loop Example

          • The 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 while loop 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 i acts as a counter to track the number of repetitions.

          • Example:

          i = 1
          while i <= 10:
           print(i)
           i = i + 1
          

          Count Variable Flowchart

          • Visual representation of the previous example.

          i = 1
          while i <= 10:
           print(i)
           i = i + 1
          

          Terminating 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 while loop

            • The concept of a count variable

          • Next, we'll delve into the break command in the while loop and its interaction with the if...else statement.

          Chapter 5 (Section 2): break Statement in the while Loop

          Introduction

          • The break command

          • How to utilize the break instruction within loops

          Combining while Loop and if...else Statement

          • The while statement can be paired with if...else for 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 += 1
          

          Flowchart Analysis

          • Illustrating the combination of while and if...else statements.

          • Two decision diamonds represent:

            • The if conditional statement

            • The while loop condition

          The break Command

          • In the user login example, setting trial_number to 4 (when the correct password is entered) aims to exit the loop.

          • The break command 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 += 1
          

          Understanding the break Command

          • break exits the loop immediately, ignoring subsequent instructions.

          • Important notes:

            • break must be used within a loop.

            • Once break is executed, the loop terminates and subsequent commands inside the loop are skipped.

          Utilizing the break Command

          • Multiple 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 += 1
          

          The break Command with the else Pattern

          • The else block after a while loop executes when the loop condition becomes False.

          • However, if the loop is exited using break, the else block 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 else statement.

          • 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 break command and its usage.

          • Up next: In-depth exploration of Python lists.

          Chapter 6 (Section 2): The for Statements

          Introduction

          • Reading list items using a while loop

          • The for loop

          • The range function

          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 while Loop to Iterate Over Lists

          • Apart from accessing list items with their indices, we can use a while loop 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 counter
          

          The for Loop

          • A more concise way to iterate over list items.

          • Note: Maintain proper indentation!

          for {loop_variable} in {list}:
          

          Activity: for vs. while

          • Compare the given for and while loop 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 for Loop

          • It's more compact than the while loop for iterating over lists.

          • In many cases, while loops with loop variables can be replaced with for loops.

          The range Function (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 range Function (Part 2)

          • With two numbers m and n, it produces numbers from m to 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 while loop

            • The for loop

            • The range function