2.2. VariablesΒΆ
One of the most powerful features of a programming language is the ability to manipulate variables. A variable is a name that refers to a value.
An assignment statement creates new variables and gives them values:
Before you keep reading...
Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.
This example makes three assignments and then prints the value of each of the variables. The first assigns a string to a
new variable named message
; the second assigns the integer
17 to a variable named n
; and the third assigns the (approximate)
value of pi to a variable named pi
.
The type of a variable is the type of the value it refers to.
-
csp-10-2-2: Using the code above, match the variables up with their type.
Look at the variable assignments above.
- message
- string
- n
- integer
- pi
- float
message = 'And now for something completely different' n = 17 number = "123456789" pi = 3.1415926535897931
- name = 'Penelope"
- The quotation marks on each side of the string need to be the same, either single or double, not a mix.
- name = "Penelope"
- An equals sign is needed to assign a variable and quotation marks tell the program that the value is a string.
- name = Penelope
- What symbols are missing to make
Penelope a string? - name, "Penelope"
- Look at the variable assignments above, what's missing?
csp-10-2-4: How would you assign the variable name
to the string Penelope
?