INTRO TO PYTHON VARIABLES AND DATA TYPES
WHAT IS A VARIABLE?
Variables are a way to store data in your program. A variable is given a simple name so that you are able to refer to the stored value later in your program. In order to give a variable a value you type the name of your new variable, an “=”, and then the data you are going to store. For example, in the picture, the variable message has the value 'Hello World'.
WHAT IS A DATA TYPE?
Data types are different types of data that you can use and store in a variable in your program. The data types we will learn about in Python include String, Integer, Float and Boolean.
STRINGS
Strings are anything between 2 quotes or between “ and ”. A string in Python can contain as many characters as you wish. A string can also be empty. In line 3 of the code we are combining different strings together. This action is called concatenation.
INTEGERS AND FLOATS
The integer data type consists of zero, positive, and negative whole numbers. The float data type in Python is a floating-point number, which are just like decimals, but with a fancy name. For example, in the picture, the variable x is an integer and the variable y is a float.
BOOLEAN
A Boolean is a data type that can have a value of True or False. Notice the code and the output in the picture shown. Line 1 prints out False, because 6 is not greater than 16. Line 2 prints out True because 16 is greater than 6. Feel free to further explore the Boolean data type.
CASTING
There may be times when you want to change the type of data a variable holds. This can be done with casting. Casting in Python can be done using the following code. There is more information on casting below.
int() turns the variable into an integer. If you cast a string into an integer, make sure that only numbers are in the string otherwise the casting will cause an error (which no one wants!). If you cast a float into an integer, it will always round down rather than up. This can be observed in line 1 and 2.
float() turns the variable into a float. In line 3, an int is being cast into a float.
str() turns a variable into a string. In line 5, a float and int are being added together and then that turns into a string.
GREAT JOB!
You have officially completed the second python activity!