visit
Let's start learning about how we define variables. First, make a file called variables.py
, and let's start experimenting.
Unlike Javascript, or other languages, there is no need to use a keyword to define a variable. For example, if we want to define a variable x
with a value Hello World
(string) - then we just do the following to create the variable, and then print it:
x = "Hello World"
print(x)
We can test this out in our variables.py
file by saving this, and running python variables.py
from terminal, when we are in the directory where variables.py
is stored. If, for whatever reason, the python
command cannot be found, .
w = "Hello World" # String
x = 1 # Int
y = 2.5 # Float
z = True # Boolean
print(w, x, y, z)
One difference from some other languages, is when defining a boolean, we use capital letters - so you have to write True
. We can find out the types of any variable using the type
function:
w = "Hello World" # String
x = 1 # Int
y = 2.5 # Float
z = True # Boolean
# Will return <class 'int'>
print(type(x))
We can also define multiple variables at once in Python using the comma notation. So, if we wanted to define w
, x
, y
, and z
on one line, we could do it like this:
w, x, y, z = ("Hello World", 1, 2.5, True);
print(w, x, y, z);
location = "World"
print("Hello " + location)
Note: as previously mentioned, we can only concatenate strings of the same type. So if we try to concatenate an int
instead, we'll get an error:
day = 6
# Throws an error: TypeError: can only concatenate str (not "int") to str
print("It is day " + day)
So, as mentioned, we can't concatenate variables of differing types. If we want to force an int
to be string
so we can concatenate it with another string
, we need to use casting. To do that, we use functions like str()
, which will force it's content to cast to a string.
day = 6
# Throws an error: TypeError: can only concatenate str (not "int") to str
print("It is day " + str(day))
As well as str()
, there are 2 other casting functions in Python:
int()
- creates an integer from a string, integer, or float.float()
- creates a float from a string, integer or float.
These can easily be used in your code just like we used str()
above. Here are some examples:
x = 5 # Int
y = 2.5 # Float
z = "Hi" # String
a = "5" # String
xFloat = float(x)
yInt = int(y)
aInt = int(a)
# Will return 5.0 2 5
print(xFloat, yInt, aInt)
Note: if you try to convert z
above to an int
or float
, it will throw an error - since the text "Hi"
cannot be interpreted as a float or integer. The error we'd get looks like this:
ValueError: invalid literal for int() with base 10: 'Hi'