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 Programming Course & Exercises
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.
1 | #!/usr/bin/python |
Run the program from terminal or with an IDE.1
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:
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.
1 | Python 3.5.3 (default, Jan 19 2017, 14:11:04) |
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 casing1
2
3daysInYear = 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.
If you are a beginner, then I highly recommend this book.
Exercises
Try the exercises below
- Make a program that displays several numbers.
- Make a program that solves and shows the summation of 64 + 32.
- Do the same as in 2, but make it sum x + y.
After completing these continue with the next exercise.