Variables, types and assignment

What a variable is, the basic types, assignment and its pitfalls, swapping two variables and type conversions: reading each line and predicting what it does.

  • 28 cards
  • 6 topics
  • Free

The outline, topic by topic

Each topic is weighted the way the exam weighs it.

  1. Concepts
  2. Questions
  3. Sort and link
  4. Scenarios
  5. Understand
  6. Line by line

A few cards from the deck

  • Variable: what is it?

    Show the answer

    A name bound to a value held in memory, which the program can read back and replace.

    It has a name, a type and a value; an assignment replaces the value, not the name.

  • What does this program print?

    ```python
    x = 2
    y = 7
    x = y
    y = x
    print(x, y)
    `

    • 7 7
    • 7 2
    • 2 7
    • 2 2
    Show the answer

    7 7

    x = y overwrites the 2: only 7 is left in both variables, and y = x copies 7 back. To swap, first keep the old value of x safe in a third variable.

  • In C or Java, a … announces a variable's name and type before it is used; in Python, the first … creates the variable.

    Show the answer

    In C or Java, a declaration announces a variable's name and type before it is used; in Python, the first assignment creates the variable.

    int age; in C, age = 18 in Python: a Python variable has the type of the value it refers to, and may change type at the next assignment.

  • Data type: what is it?

    Show the answer

    The category of a value, which sets the values it may take and the operations allowed on it: integer, float, boolean, string.

    3 + 4 adds and gives 7; '3' + '4' joins end to end and gives '34': same sign, two operations, because the types differ.