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.
- Concepts
- Questions
- Sort and link
- Scenarios
- Understand
- 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 77 22 72 2
Show the answer
7 7x = yoverwrites the 2: only 7 is left in both variables, andy = xcopies 7 back. To swap, first keep the old value ofxsafe 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 = 18in 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 + 4adds and gives7;'3' + '4'joins end to end and gives'34': same sign, two operations, because the types differ.