Python - #2 - Variables
1. Number Variables
A variable is a value that can change.
​
Imagine there are 20 biscuits in a jar. Then I eat one. Now there are only 19.
​
You must state what the value of a variable is before it is used. e.g. biscuits = 20
Task 1 - Create a new Python program and save the file as 2-Variables.py
​
Create a variable called sweets and give it the value 15. Then print sweets.
Variable names cannot have spaces. You can use underscores if you want, e.g. num_of_eggs
​
When you are printing variables, you don't put them in speech marks. Otherwise, it will print the variable name and not the value.
2. String Variables
A string is a programming term for a collection of characters.
​
When you are giving a variable a string value, it must be written in speech marks.
​
Remember when you print the variable however, it is never printed in speech marks.
Task 2 - Create a variable called name and give it the value of your name. Then print the name variable.
3. Using Variables in a Sentence
When we have printed the variables so far, they have not been very informative!
​
You can print variables together with sentences so that they mean more.
​
Use a comma ( , ) between variables and sentences.
Task 3 - Use the pictures to help you add commas and sentences to your program to be more informative.
4. Using Variables Together
You can print more than one variable together in the same sentence by separating them with sentences and commas.
​
If this doesn't work, double-check your program has a comma between each variable and sentence.
Task 4 - Type a new print line that uses both your name and your sweets variables together. Use the image to help you.
Challenge Programs
Use everything that you have learned on this page to help you create these programs...
​
Challenge Task 1 - Funny Animals
-
Create a new Python program. Save it as '2-FunnyAnimals.py'
-
Add a comment at the top with your name and the date.
-
Create a variable for a colour and give it a value (e.g. "blue")
-
Create a variable for an animal and give it a value (e.g. "horse")
-
Print a funny sentence that uses both variables.
​
-
BONUS: Try to use only one print line.
-
BONUS: Try to use only three lines in total.​
Remember: Break up variables in a print line by using commas.
​
When you run it, it could look something like this:
Challenge Task 2 - Funny Sentence
-
Create a new Python program. Save is as '2-FunnySentence.py'
-
Add a comment at the top with your name and the date.
-
Write a program that uses three variables, an adjective (descriptive word), a number and an animal. Print a funny response using all variables.
​
-
BONUS: Try to use only one print line.
-
BONUS: Try to use only four lines in total.​
Remember: Break up variables in a print line by using commas.
​
When you run it, it could look something like this: