Variables are used to store values that can be used later in your code. Think of a variable as a name that points to an object. You can give a variable any name you want, as long as it follows certain rules.
To assign a value to a variable, you use the equals sign (=
). Here's an example:
my_variable = 10 print(my_variable) # output: 10
In this example, we created a variable called my_variable
and assigned it the value of 10
. Now, whenever we refer to my_variable
in our code, it will have the value of 10
. The print function is used to display the variable on screen.
You can also assign different types of values to variables. For example, you can assign a string (a sequence of characters) to a variable:
my_name = "John" print(my_name) # output: John
In this case, my_name
is a variable that holds the value "John"
. You can use this variable later in your code to refer to the string "John"
.
You can also assign the result of an expression to a variable. For example:
x = 5 + 3 print(x) # output: 8
In this case, x
is a variable that holds the value 8
, which is the result of the expression 5 + 3
.
Variables can be changed or updated throughout your code. You can assign a new value to a variable by simply using the equals sign again:
x = 10 x = x + 5 print(x) # output: 15
In this example, we first assign the value 10
to x
. Then, we update x
by adding 5
to its current value. After this code runs, x
will have the value 15
.
Variables point to objects. Objects can be of various types, like numbers, strings, booleans, lists, etc.