Python supports different types of variables (datatypes) such as whole numbers, floating point numbers and text.

You do not need to specify the datatype of a variable, you can simply assign any value to a variable. Type the program below and start it.

Related course: Complete Python Bootcamp: Go from zero to hero in Python

Datatypes

Variables can be of several data types. Python supports integers (numbers), floating point numbers, booleans (true or false) and strings (text).

Python will determine the datatype based on the value you assign to the variable. If you create a variable x, x = 3, then Python assumes its an integer. But if you assign x = 1.5 then Python knows its not an integer but floating point number.

Example

The example below shows you several variables. These can be assigned as you wish. Once defined you can print them or use arithmetics.

#!/usr/bin/python

x = 3 # a whole number
f = 3.1415926 # a floating point number
name = "Python" # a string

print(x)
print(f)
print(name)

combination = name + " " + name
print(combination)

sum = f + f
print(sum)

Run the program from terminal or with an IDE.

python example.py

In the example we have several variables (x,f,name) which are of different data types. Later in the program we create more variables (combination, sum).

Variables can be defined anywhere in the program. Variable names can be one to n letters.

You should see several lines containing numbers and text:

python variables

Naming

A variable name must begin with a letter (upper or lower case) or an underscore. Variables cannot start with a number and are case sensitive.

If you create two variables x and X, they are different variables.

Python 3.5.3 (default, Jan 19 2017, 14:11:04)
[GCC 6.3.0 20170118] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> x = 3
>>> X = 4
>>> print(x)
3
>>> print(X)
4
>>>

Camel casing

By convention variables are often camel cased, meaning the first letter is small and the next words are all capital.

Some example variables that use camel casing

daysInYear = 365
daysInMonth = 30
numberFiles = 5

This is easier to read than having one long variable (dayinyear). But it’s not a strict requirement for Python.

Exercises

Try the exercises below

  1. Make a program that displays several numbers.
  2. Make a program that solves and shows the summation of 64 + 32.
  3. Do the same as in 2, but make it sum x + y.

After completing these continue with the next exercise.

Download answers