Variables

<< Previous: Python homeNext: Output >>

What are variables?

Variables are named storage locations for temporarily storing data while a program is executing.

There are rules about naming variables, 5 types of data you can store inside them and some terminology to know about.

Variable naming rules

Variable naming conventions

Naming conventions are used to ensure variable names in a program are standardised. The three most common naming conventions are:

Snake case: everything is lower case and spaces are shown as underscores e.g. snake_case

Camel case: the first word is lower case and all subsequent words start with a capital letter and spaces are ignored e.g. camelCase

Tall camels: this is the same as camel case except the first word also uses a capital letter e.g. CamelCase

Variable data types

There are 5 data types you need to be familiar with at GCSE level as shown below.

Data type Description
Character An individual character from the character set being used
String A group of characters
Integer A whole number
Float/Real A number with a decimal/fractional part
Boolean Can hold the value True or False

Declaring and assigning variables

Declaring a variable means telling the program the name of it and its data type. In many languages this must be done as a separate step on its own. In Python we can declare and assign a value to a variable at the same time. When you give a suitable variable name and use the assignment operator(=) to assign a new value Python accepts this name as a variable and sets its data type to the data type of the value you assign.

There are some differences in how assignment is carried out in python.

Data type Assignment example Details
Character grade = "A" A character must be surrounded by speech marks
String name = "Bob" A string must be surrounded by speech marks
Integer age = 42 Integers must not be in speech marks or they will be treated as strings
Float/Real length = 1.358 Float/real numbers must not be in speech marks or they will be treated as strings
Boolean member = True No speech marks and capital first letter in True or False

Casting

Casting is when we convert a variable from one data type to another. This will only work when the data in the variable is valid in the new data type. Whenever we get input, it is automatically stored as a string, so it must be cast if you want it stored as a different data type.

num = int(num) #Takes what is stored in num and converts it to an integer as long as there is a number stored in num

num = float(num) #Takes what is stored in num and converts it to a float as long as there is a number stored in num

num = str(num) #Takes what is stored in num and converts it to a string

Knowledge check


Questions:
Correct:

Question text


<< Previous: Python homeNext: Output >>

© All materials created by and copyright S.Goff