Beginner Python Tutorial Series - Chapter 3 - Variables
Beginner Python Tutorial Series
Chapter 3 - Variables
Hi! SirBilby here!
Sorry this is being released so late. I have been really busy with exams etc lately and haven't got round to writing this. So, here it is!
(about time too)
Arguably one of the most important parts of Python, variables can be used to store numbers, letters and much more.
So, how do we create a variable?
Well, first we give it a name. To do this, we simply write
The variable can be called anything, and the bit that comes after the equals sign can be any value you wish, not just the word 'value'.
But it isn't quite as simple as that. There are a set of rules about variable names. These are:
Here is a simple example of a variable being used with print.
This code will give us the output:
So, that is how you create and give a value to a variable.
Variables can be in a number of different data types. Here is a (quite confusing to beginners) image illustrating these:
However, the main data types you will generally use are string, integer, float and boolean. I will explain these, along with lists.
So perhaps this would be a better image for today
An integer is a whole number such as 1, 5, or 9573637586847362. In python, an integer is written into any code like this:
(P.S. 'print' is used here simply as an easy example)
Integers cannot, however, be anything with a decimal place. So great for simple sums and tasks, but not great for precise work.
So, what can we use for decimal places?
Floating points (floats)
A floating point (more commonly known as a float) is a number with a decimal place. For example:
1.3, 7.45 and even 58696834.409598674637489607067385868472586958372626481
This means that you can create really precise programs, such as a currency converter (psst...I made one, check it out here!)
ok shameless self promotion over
We could create a variable that is a float in much the same way to an integer:
We create a string in a very similar way as above. Notice the all important "" inside the brackets and around the text. Without these, Python cannot work out that this is a string.
You can cleary see here that anything can go inside the brackets.
A boolean can be one of two options - true or false. These can be very useful for checking whether something is greater or less or equal to something else:
A list is used to store multiple values. These can be really useful for printing random values instead of one set value, but aren't just limited to this.
You could print one of many values like this:
But what if we want to convert data types?
Say we have a number from a user input but want to convert it from a string to an integer?
Well, to convert data type, you simply write the data type (often shortened), and then the variable in brackets.
That's it. I will bring out another tutorial soon!