First, let's talk about assignment!
You can assign a value to a variable using the = operator.
Thus, the content of the expression on the right of the = operator will be assigned to the variable located on the left.
variable = "castle"
print('I live in a', variable)
I live in a castle
A variable, in programming, is comparable to a box in which we can store a value. We can then look at the value inside (function print), modify the value or perform a test on it.
Below, three code examples that you can copy to observe the obtained result.
variable1 = 42
print(variable1)
variable1 = variable1 * 2
print(variable1)
variable1 = 42
variable1 = "cat"
print(variable1)
variable1 = "cat"
variable2 = variable1
print(variable2)
There are four so-called "native" value types.
You can access the type of a value using the type(value) function.
| Type | Description | Example |
|---|---|---|
INT | An integer is a numeric value without decimal part. | -1, 2, 10, 20 |
STR | A string is a sequence of characters. This can include letters, numbers, special characters, etc. It is always between single or double quotes. | "the cat", "812", "@1234!xyz" |
FLOAT | A floating-point number is a numeric value with an integer part and a decimal part. | 123.4, -0.12, 42.42 |
BOOL | A boolean can take two states: True or False, meaning respectively true or false. | True, False |
var = 42 will create an integer equal to 42. However, the expression var = "42" will create a string composed of the characters 4 and 2.While it's important to be aware of the type of values we manipulate, it's sometimes necessary to transform the type of a value according to the operations we may need to perform.
| Function | Description | Example |
|---|---|---|
int() | Converts a value to integer. If the value is a string representing a number or a floating-point number, it is converted to integer. | int('3') returns 3 |
float() | Converts a value to floating-point number. This can be useful for converting integers or strings to decimal values. | float('3.14') returns 3.14 |
str() | Converts a value to string. Useful for transforming numbers, lists or other types to strings. | str(123) returns '123' |