Values and variables
By the end of this step you can store information in a program, do sums with it, and print it.
Values come in kinds
Programs work with values. The three you'll use most:
| Kind | What it is | Python | JavaScript |
|---|---|---|---|
| Text (a "string") | Letters, words, sentences. Always in quotes. | "Trail Tent" | "Trail Tent" |
| Number | For counting and maths. No quotes. | 249.99 | 249.99 |
| True or false (a "boolean") | A yes/no answer | True / False | true / false |
Quotes matter: "42" is text that happens to look like a number. 42 is a number you can do maths with.
Variables are labelled boxes
A variable is a name for a value, so you can use it later. Think of a box with a label on it:
| Python | JavaScript | |
|---|---|---|
| Make a variable | price = 249.99 | const price = 249.99; |
| Use it | print(price) | console.log(price); |
Read = as "store", not "equals": store 249.99 in the box called price.
JavaScript adds a word in front. const means "this box won't change". let means "this box might change later". Python doesn't bother.
Names are up to you, but no spaces. Python style joins words with underscores (in_stock); JavaScript style uses capitals (inStock). Same idea, different habit.
Try it
Read the code first, top to bottom, and guess what each line will print. Then press Run and check your guesses.
Output
Press Run (or Ctrl+Enter) to see the output here.
Output
Press Run (or Ctrl+Enter) to see the output here.
A few things to spot:
- Lines starting with
#(Python) or//(JavaScript) are comments: notes for humans. The computer skips them. price * 1.08is maths:*multiplies,/divides,+adds,-subtracts.- Joining text needs care. In Python,
"costs $" + 249.99is an error: you can't add text to a number.str(price)turns the number into text first. JavaScript's backticks (`) let you drop values straight into text with${ }.
Want to see an error on purpose? In the Python box, remove str( ) around price and run it. Read the last line of the error: it tells you exactly what went wrong. Then press Reset.
Your turn
At the bottom of either box: add a variable called quantity set to 3, then print how much 3 tents cost, with tax.