Table of contents
It has been a long time since my last post about Python, so this time I'm writing to explain what I learned about variables. Here we will learn about working with variables. I will speak about creating different variables and how to modify their value. Let's get on to business!
Variables
We use variables to store data. For example, we can create a variable to save a number and use it later in our code.
number=3
We can use any name we want for our variable. For example, we could have called this variable "sky" instead of "number", and it would be ok.
Another important fact is that Python differentiates between capital letters and non-capital letters.
number=3
print(number) #Will print 3
Number=5
print(Number) # Will print 5
To avoid having problems, we usually write the name of our variables starting with non-capital letters.
It is good to know that computers store variables in the RAM. This memory destroys all data when we shut off our computers, and that's why it's called working memory. So, if we write:
name="Jane"
We are telling the computer to save some data on its memory.
We must consider that a computer's memory is not infinite and that there are different types of variables using diverse spaces in memory. We don't use the same memory amount to store an integer and a text. But the good thing about Python is that it identifies the variable types depending on what we save, optimizing the memory space.
For now, we are going to see three main variables:
int: Variables storing integer numbers
float: Variables storing decimal numbers
str: Variables storing text (strings)
We can define more than one variable in different lines:
number=3
word="Hi"
decimal=6.14
Or we can define them in the same line, separating names and contents with commas:
number, word, decimal = 3, "Hi", 6.14
We can check the type of any variable with the type command:
name="Jane"
type(name) # Will print str
Challenge
Create different variables (int, str and float) and use the type command to check their type.
Modifying variables
In Python, we can change the content of any variable by declaring it again:
name="Jane"
name="Juan"
In this case, our variable "name" first has Jane stored. Then, we save the value Juan deleting Jane. Let's check it:
name="Jane"
print(name) # Will print Jane
name="Juan"
print(name) # Will print Juan
We can store different types of content as Python deletes the variable and it creates it again with the new content:
name="Jane"
type(name) # Will print str
name=6
type(name) # Will print int
Cheatsheet
name="Pedro" # Declare a variable
number=3 # Declare a variable
type(variable_name) # Check the variable type
Summing up
We have learned how to create and modify our variables, which is a crucial step for getting into coding, as we always work with different types of variables.
Now we should be able to create, modify and check their types. So practice a bit with what you've learned, and see you in the next post!