NEXT PAGE >
OPERATORS |
WHAT ARE VARIABLES
A variable can be thought of as a container or a storage box where you can keep different types of information or data. Just like you might store toys in a toy box or books on a bookshelf, in programming, we use variables to store data like numbers, words, or even more complex information.
The purpose of variables
Imagine you're playing a video game, and you have a score. That score might start at 0 and increase as you progress. In the game's programming, a variable is used to store your score. As you earn points, the value inside that variable changes.
In simple terms, a variable is like a labelled jar where you can put something inside, look at it whenever you want, and even change its contents!
The purpose of variables
- Storage | Variables allow us to store data that we can use and manipulate later in our program.
- Reference | Once data is stored in a variable, we can refer to it by the variable's name whenever we need it.
- Flexibility | Variables can change or "vary" (hence the name "variable"). This means that the data inside a variable can be updated or changed as needed.
Imagine you're playing a video game, and you have a score. That score might start at 0 and increase as you progress. In the game's programming, a variable is used to store your score. As you earn points, the value inside that variable changes.
In simple terms, a variable is like a labelled jar where you can put something inside, look at it whenever you want, and even change its contents!
WATCH THIS VIDEO TO GUIDE YOU THROUGH THIS SECTION
SECTION 1 | CREATING VARIABLES
In the below line of code, a variable is made and the label 'myName' is assigned to the variable. Inside the variable is a string of text "King Bob".
myName = ("King Bob")
Try to give your variables sensible and meaningful names. A variable cannot contain spaces and if it is more than one word it is good practice to use an underscore to separate words or each word starts with a capital letter(excluding the first word) for example:
myName
my_name
You can give the variable nearly any name you want, however some command names should not be used such as 'print', 'python', for, exit and many more command names you will learn should not be use as the variable name.
VARIABLE NAMING RULES
✘ Cannot start the name with a number
✘ Cannot contain spaces
✘ Cannot use command words such as print, python, turtle, exit, for, while and many more...
VARIABLE NAMING CONVENTIONS
✓Should start with a lowercase letter
✓If more than one word used the first letter uppercase of proceeding words or use _ to join words
✓Names should be meaningful to the content of the variable
DEFINING, CALLING AND ASSIGNING VALUES TO A VARIABLE
Creating a variable is called 'defining a variable' and using the variable is called 'calling the variable'. In the example below we define a variable call firstName and we assign the value 'Jane' to the variable. We then call the variable by printing it on the next line of code.
firstName = ("Jane")
print (firstName)
In summary, variables are like a box, we store things in them and we give them a sensible name.
myName = ("King Bob")
Try to give your variables sensible and meaningful names. A variable cannot contain spaces and if it is more than one word it is good practice to use an underscore to separate words or each word starts with a capital letter(excluding the first word) for example:
myName
my_name
You can give the variable nearly any name you want, however some command names should not be used such as 'print', 'python', for, exit and many more command names you will learn should not be use as the variable name.
VARIABLE NAMING RULES
✘ Cannot start the name with a number
✘ Cannot contain spaces
✘ Cannot use command words such as print, python, turtle, exit, for, while and many more...
VARIABLE NAMING CONVENTIONS
✓Should start with a lowercase letter
✓If more than one word used the first letter uppercase of proceeding words or use _ to join words
✓Names should be meaningful to the content of the variable
DEFINING, CALLING AND ASSIGNING VALUES TO A VARIABLE
Creating a variable is called 'defining a variable' and using the variable is called 'calling the variable'. In the example below we define a variable call firstName and we assign the value 'Jane' to the variable. We then call the variable by printing it on the next line of code.
firstName = ("Jane")
print (firstName)
In summary, variables are like a box, we store things in them and we give them a sensible name.
SECTION 2 | JOINING VARIABLES
There is a few different ways we can join multiple variables together, the process of connecting variables is called 'concatenation'.
Let's say you have two variables, 'firstName' and 'lastName' and you want to join them together. Firstly defining the two variables:
firstName = ("King")
lastName = ("Bob")
We can print the two names together (concatenate) by using one of the following method:
Method 1 - Using the + sign:
print (firstName + lastVersion)
Output: KingBob
Method 2 - Using the , comma:
print (firstName, lastVersion)
Output: King Bob
There are a few differences between using the + sign and the , (comma) sign. Firstly you can see above that when using the comma sign a space in inserted automatically, this is not the case when the + sign was used. When using the + sign python will actually print the strings as separate objects, so effectively printing multiple times, whereas using a comma python will see it as just one string. Using the + sign sometimes is necessary when using loops and calculations, this is covered in other sections.
We recommend using method 1, this will help you later as you get to grips with different data types. Using method 1 you can see there is no gap between the words King and Bob Bob and The, to add the space you could do add speech marks with a space in:
print (firstName + " " + lastName)
Output: King Bob
Let's say you have two variables, 'firstName' and 'lastName' and you want to join them together. Firstly defining the two variables:
firstName = ("King")
lastName = ("Bob")
We can print the two names together (concatenate) by using one of the following method:
Method 1 - Using the + sign:
print (firstName + lastVersion)
Output: KingBob
Method 2 - Using the , comma:
print (firstName, lastVersion)
Output: King Bob
There are a few differences between using the + sign and the , (comma) sign. Firstly you can see above that when using the comma sign a space in inserted automatically, this is not the case when the + sign was used. When using the + sign python will actually print the strings as separate objects, so effectively printing multiple times, whereas using a comma python will see it as just one string. Using the + sign sometimes is necessary when using loops and calculations, this is covered in other sections.
We recommend using method 1, this will help you later as you get to grips with different data types. Using method 1 you can see there is no gap between the words King and Bob Bob and The, to add the space you could do add speech marks with a space in:
print (firstName + " " + lastName)
Output: King Bob
SECTION 3 | DATA TYPES
Is it a letter? is it a number? what type of number is it? When we see thing written down it is easy for us too recognise if it is a number or a word. However when we code we need to explicitly tell the program what type of data it is dealing with. The following three data types are common with programming.
string - this is text
int - this is a integer number (no decimal places)
float - the is a number with decimal places
In the previous example we have stored text into variable, text is classified as a string in programming, in Python when you place data inside speech marks " ", python will class it as a string(text) even if it is a number.
In some cases we might have to explicitly tell Python what the type of data is, however Python knows from your code when you use the following structure.
print ("Hello " + "world")
print ("10" + "5")
Try the above two lines in your Python program: You might expect 10 + 5 to = 15, however because it is in speech marks Python treats it as text and prints 105. Now try the same but this time remove the speech marks, you will see that Python now treats the 10 and 5 as integers.
print (10 + 5)
Run your code and you can see the Python now prints the correct answer of 15.
You can also store numbers in variables, just remember not to use speech marks around the number because with speech marks Python will treat the number as a string (text). An example of storing two numbers, (one integer and one float) adding them together and showing the result can be seen below.
num1 = (2)
num2 = (2.4)
ans = (num1 + num2)
print (ans)
Multiple, divide, subtract - The same as above can be done for multiplication, subtraction and division by using * - /.
CONCATENATING A NUMBER WITH A STRING
There will be many occasions where you want to join strings with numbers, however if you try to join a number with a string you will get an error message saying:
Error: You cannot concatenate a str with an int
To solve this problem you can tell Python to treat the number as a string by adding str before the variable that holds the number, as can be seen below.
num1 = (2)
num2 = (2.4)
ans = (num1 + num2)
print ("The answer is " + str(ans))
string - this is text
int - this is a integer number (no decimal places)
float - the is a number with decimal places
In the previous example we have stored text into variable, text is classified as a string in programming, in Python when you place data inside speech marks " ", python will class it as a string(text) even if it is a number.
In some cases we might have to explicitly tell Python what the type of data is, however Python knows from your code when you use the following structure.
- Python will treat it as text/strings if it has speech marks " " around it. Note text/strings will appear in green.
- Python will treat it as a number if it does not have speech marks around it.
- Python will treat it as a float if it has a decimal point.
print ("Hello " + "world")
print ("10" + "5")
Try the above two lines in your Python program: You might expect 10 + 5 to = 15, however because it is in speech marks Python treats it as text and prints 105. Now try the same but this time remove the speech marks, you will see that Python now treats the 10 and 5 as integers.
print (10 + 5)
Run your code and you can see the Python now prints the correct answer of 15.
You can also store numbers in variables, just remember not to use speech marks around the number because with speech marks Python will treat the number as a string (text). An example of storing two numbers, (one integer and one float) adding them together and showing the result can be seen below.
num1 = (2)
num2 = (2.4)
ans = (num1 + num2)
print (ans)
Multiple, divide, subtract - The same as above can be done for multiplication, subtraction and division by using * - /.
CONCATENATING A NUMBER WITH A STRING
There will be many occasions where you want to join strings with numbers, however if you try to join a number with a string you will get an error message saying:
Error: You cannot concatenate a str with an int
To solve this problem you can tell Python to treat the number as a string by adding str before the variable that holds the number, as can be seen below.
num1 = (2)
num2 = (2.4)
ans = (num1 + num2)
print ("The answer is " + str(ans))
SECTION 4 | USER INPUT
STORING USER INPUT IN A VARIABLE
The person who is using your program is known as the 'user'. When you ask the user of your program a question you can use a variable to store the answer. Use the Python command input to allow the user to type. Follow these simple steps:
See the example below:
userName = input("Please enter your name: ")
If you want the user to type a number then you need to explicitly tell Python to treat the user input as a number by using the int command (short for integer), for example:
num1 = int(input("Please enter a number: "))
Remember to close two brackets at the end of the statement.
MAKING USE OF WHAT WE KNOW SO FAR
Now we have nearly complete stage 2 of learning to code, why not try a simple program like the one below. Copy and paste the code, change the code, see what happens, explore and try new things.
The person who is using your program is known as the 'user'. When you ask the user of your program a question you can use a variable to store the answer. Use the Python command input to allow the user to type. Follow these simple steps:
- First create the variable
- Make the variable equal the input
- Give the user a prompt message
See the example below:
userName = input("Please enter your name: ")
If you want the user to type a number then you need to explicitly tell Python to treat the user input as a number by using the int command (short for integer), for example:
num1 = int(input("Please enter a number: "))
Remember to close two brackets at the end of the statement.
MAKING USE OF WHAT WE KNOW SO FAR
Now we have nearly complete stage 2 of learning to code, why not try a simple program like the one below. Copy and paste the code, change the code, see what happens, explore and try new things.
Want to make the program more user friendly? You can join/concatenate strings with integers in your output to give better user feedback. To do this you will need to tell Python that the integer is a string in the occasion that it is joined with a string. You can do this by adding str before you call the variable, as can be seen in the example below it gives a neater print statement at the end:
Code Editor
ELEMENT |
DESCRIPTION |
Variables |
Variables are containers for storing data values. Remember the rules for creating variables. VARIABLE NAMING RULES ✘ Cannot start the name with a number ✘ Cannot contain spaces ✘ Cannot use command words such as print, python, turtle, exit, for, while and many more... VARIABLE NAMING CONVENTIONS ✓Should start with a lowercase letter ✓If more than one word used the first letter uppercase of proceeding words or use _ to join words ✓Names should be meaningful to the content of the variable firstName = "John" age = 25 |
input() |
The input() function allows you to prompt the user for input. user_name = input("Enter your name: ") |
Single Line Comments |
Used to add comments to your code that Python will ignore during execution. # This is a single-line comment |
Multi Line Comments |
Python does not have a specific syntax for multi-line comments, but you can use triple quotes. ''' This is a multi-line comment. Python will ignore this during execution. ''' |
print() |
The print() function outputs text or variables to the console. print("Hello, World!") |
Strings |
Strings are sequences of characters, enclosed in either single or double quotes. greeting = ("Hello") |
Concatenate with + |
Concatenate strings and variables using the + sign joins them together as one value. message = ("Hello " + name) |
Concatenate with , |
Using a comma in the print() function to join strings and variables. print("Hello", name) |
Concatenate with f{} |
Using the f method to format strings allow you to embed expressions inside string literals. message = (f"My name is {name} and I am {age} years old.") |
DEFINE AND CALL VARIABLES
1: Create a variable and store the name of your favourite food in the variable.
2: Print the variable
3: Without deleting the variable you created in task 1. Create another variable and store the name of your favourite sport in the variable
4: Print the variable
2: Print the variable
3: Without deleting the variable you created in task 1. Create another variable and store the name of your favourite sport in the variable
4: Print the variable
CONCATENATE VARIABLES
1: Create a variable and store the value of 'cat' in the variable.
2: Create a print statement to print "The <variable> sat on the mat".
When you replace the <variable> with the variable that stores the value 'cat', your print statement should read:
The cat sat on the mat
2: Create a print statement to print "The <variable> sat on the mat".
When you replace the <variable> with the variable that stores the value 'cat', your print statement should read:
The cat sat on the mat
STRINGS, INTEGERS AND FLOATS
1: Create a variable to hold a number
2: Create a second variable to hold another number
3: Add the two number together
4: Output: "<firstNumber> plus <secondNumber> equals <answer>"
Replace the values in the <> with your variables.
EXTENSION TASK:
You now know how to add 2 numbers together. Try do same task with the following.
2: Create a second variable to hold another number
3: Add the two number together
4: Output: "<firstNumber> plus <secondNumber> equals <answer>"
Replace the values in the <> with your variables.
EXTENSION TASK:
You now know how to add 2 numbers together. Try do same task with the following.
- Add 3 numbers
- Divide two numbers
- Multiply 2 numbers
- Subtract a number from another number
USER INPUT
The following program has 3 errors, find and correct the errors then test your program.
Code Editor
Question 1: Assigning Variables
What is the correct way to assign the value 10 to a variable named x in Python?
A) X == 10
B: X = 10
C: X := 10
D: => 10
EXPLANATION
In Python, the single equals sign = is used to assign a value to a variable. x = 10 means that the value 10 is assigned to the variable x. The double equals == is used for comparison, not assignment.
Question 2: Data Types
Which of the following is an example of a string in Python?
A) "42"
B: 42
C: True
D: 3.14
EXPLANATION
A string in Python is a sequence of characters enclosed in quotes. "42" is a string because it is enclosed in double quotes, even though it looks like a number. The other options represent a number (42), a Boolean value (True), and a floating-point number (3.14).
Question 3: Concatenation
Given the following code, what will be the output?
Given the following code, what will be the output?
first_name = "John"
last_name = "Doe"
print(first_name + " " + last_name)
last_name = "Doe"
print(first_name + " " + last_name)
A) JohnDoe"
B: John Doe
C: John
D: Joe John
explanation
The + operator is used to concatenate (join) strings in Python. In this case, "John" and "Doe" are concatenated with a space " " in between them. So the output will be John Doe. The other options don't correctly represent the result of the concatenation.
Question 4: User Input
Which of the following correctly takes user input and stores it in a variable called name?
A: name = input("Enter your name: ")
B: input = name("Enter your name: ")
C: name == input("Enter your name: ")
D: input("Enter your name:", name)
explanation
The input() function in Python prompts the user for input. The text inside the parentheses is displayed as a prompt to the user. The entered input is then stored in the variable name. The other options use incorrect syntax for handling user input.
Question 5: Data Type Conversion
Which of the following is the correct way to convert a user input, stored in age, into an integer in Python?
A: age = int(age)
B: age = str(age)
C: age = input(age)
D:age = float(age)
explanation
The input() function always returns data as a string, so to use the input as an integer (e.g., for age), you need to convert it using the int() function. The other options either use incorrect functions (str() converts to string, and float() converts to a floating-point number) or incorrect syntax.
AT THIS STAGE IS WOULD ALSO BE USEFUL TO LEARN ABOUT COMMENTING CODE
When coding it is very useful to leave yourself notes, we can use comments to leave notes that Python will not read when it iterates through your code. There are two main methods of commenting your code; Single line comments and Multi line comments. To do a single line comment you simply need to put a # tag in front of your comment, you will see in the videos that these are often used. An example can be seen below:
#This is my first Python program
print ("Hello World")
Python will not read the comment "This is my first Python Program" because it is commented out with a # tag. The other method is to do Multi line comments, to do multi line comments you put the lines to comment in triple (single) quotation marks, the first set to start the comment and the last set to end the comment. An example can be seen below:
print ("Hello world")
' ' '
print ("Welcome to my Program")
print ("Keen to get coding")
' ' '
The only line that Python will read is the first line. Also not the the entire comment highlights in green. Using comments is also a great way to comment out code during testing stage, or as a method to help you detect errors.
#This is my first Python program
print ("Hello World")
Python will not read the comment "This is my first Python Program" because it is commented out with a # tag. The other method is to do Multi line comments, to do multi line comments you put the lines to comment in triple (single) quotation marks, the first set to start the comment and the last set to end the comment. An example can be seen below:
print ("Hello world")
' ' '
print ("Welcome to my Program")
print ("Keen to get coding")
' ' '
The only line that Python will read is the first line. Also not the the entire comment highlights in green. Using comments is also a great way to comment out code during testing stage, or as a method to help you detect errors.
KAHOOT QUESTIONS: VISIT KAHOOT FOR A QUICK QUIZ ON VARIABLES