Using Variables - Lakelands Computing

Title
Go to content
Print (), Input () and Variables
This page takes a quick look at how we can let the user put data into variables using input () and then output it to screen using print() along with the variable.

To allow the user to assign (enter) data into a variable  You need to use the input function:

  • name = input ("What is your name?").

This will store whatever name they type in (or any other data they type) in the variable called name. Data stored in a variable from the input function will be stored as a string unless you tell it to do otherwise. Changing data from one type to another is called casting (more on it here) - with input there are two simple ways to do this. They do exactly the same thing, approach 2 just does it in one line rather than two. This example converts to an integer

approach 1:
  • age = input ("what is your age?")
  • age = int(age)

approach 2:
  • age = int (input("what is your age?")

Printing a variable
To simply print the variable, say one called price use print(price)

If you want to use the variable with other elements, such as a string, you need to separate each of the elements out with a comma eg print ("that will be ", price , "please") .  Note the comma after the first string, and then the second comma after the variable. There are more examples in the trinket.

All Text copyright Lakelands Academy & Mr T Purslow 2020.
All images copyright free / creative commons unless otherwise stated.
You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
All Text copyright Lakelands Academy & Mr T Purslow 2020.  All images copyright free / creative commons unless otherwise stated. You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
All Text copyright Lakelands Academy & Mr T Purslow 2020.  All images copyright free / creative commons unless otherwise stated. You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
Back to content