3.1 Variables and Assignments

47 阅读1分钟

1. Exam Points

  • Use the assignment operator to assign a value to a variable.
  • Predict output of a variable after some assignment steps.
  • Select the correct data type for a given piece of data.
  • Benefits of well-named variables. (more readable and easy to modify)
  • How to swap the values of two variables. (use a third variable temp)

2. Knowledge Points

(1) Programming Languages

  • Programming languages are categorized by their level of abstraction from the computer's hardware to:
    • Low-level : assembly language(汇编语言), machine language(机器语言).
      • high execution efficiency, high control over hardware.
      • complex, lack of portability(可移植性)
      • Assembly language is a specific type of low-level language. It uses (mnemonic symbol) for instructions.
    • High-level : Python, Java, C++, C#, JavaScript, etc.
      • resembles natural language and increase readability
      • portability
      • slower execution and less control over hardware
  • Assembly language is a specific type of low-level language. It uses (mnemonic symbol-助记符) for instructions.

(2) Variables (变量)

  • A variable is an abstraction inside a program that can hold a changable value.
  • Using meaningful variable names helps with the readability of program code and understanding of what values are represented by the variables. (readable and easy to modify)
  • Some programming languages connect data types to variables.
  • Commonly used types include:
    • integer: whole number, no decimal point.
      • Ex. 10, 200
    • fractional number: with a decimal point, also called floating numbers/real numbers.
      • Ex. 2.56
    • Boolean: either true or false.
    • String: an ordered sequence of characters.
      • Ex. Annabelle, 13697665261
    • list: a collection of data.
      • Ex. [10, 20, 40, 50, 60]
    • number: integers and fractional numbers.
      • 100, 2.5

(3) Assignment Operator (赋值运算符)

  • The assignment operator is used to initialize or change the value represented by a variable.

  • The value stored in a variable will be the most recent value assigned.

  • Assignment operator in AP CSP (pseudocode):

    image.png image.png
  • Input and Output in AP CSP:

    image.png

  • Examples:

    • a ← INPUT()
    • DISPLAY(a)
    • DISPLAY("Annabelle")
  • Swap(交换) the values of two variables. You need to use a third variable to implement swapping/interchanging.

    • Example:
    a ← 10
    b ← 20
    
    temp ← a
    a ← b
    b ← temp
    
    or 
    
    temp ← b
    b ← a
    a ← temp
    

3. Exercises