Basic types in python#
Variables in python can hold different types of numbers and also other things such as text, images and more complex objects.
We can also print out the type of a variable.
See also
This is an integer number:
a = 2023
type(a)
int
And this is a floating point variable:
b = 3.5
type(b)
float
When combining variables of different types, Python makes a decision which type the new variable should have
c = a + b
c
2026.5
type(c)
float
Strings#
Variables can also hold text. We call them a “string” in this case, and define them by surrounding the value with either single quotes ' '
or double quotes " "
:
workshop_name = "napari LatAm Workshop"
workshop_year = '2023'
Strings can be concatenated using the +
operator:
workshop_name + workshop_year
'napari LatAm Workshop2023'
You can add a ‘space’ between strings like this:
workshop_name + " " + workshop_year
'napari LatAm Workshop 2023'
If we want to have single and double quotation marks within our text, we can put them in like this:
text = "He asked 'How can Voldemort be so good with computers?'."
print(text)
He asked 'How can Voldemort be so good with computers?'.
text = 'She answered "Because he is fluent in Python".'
print(text)
She answered "Because he is fluent in Python".
Combining strings and numbers#
When combining variables of numeric types and string types, errors may appear:
workshop_name + a
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[12], line 1
----> 1 workshop_name + a
TypeError: can only concatenate str (not "int") to str
Those can be prevented by converting the numeric variable to a string type using the str()
function:
workshop_name + str(a)
'napari LatAm Workshop2023'
You can also convert strings to numbers in case they contain numbers:
d = "5"
int(d)
5
a + int(d)
2028
int("5")
5
f-strings#
Instead of having to manually convert numbers to strings in order to assemble them with other strings, we can resort to f-strings which are defined by simply adding an f
before the opening quote of a regular string:
f"This is an f-string"
'This is an f-string'
We can now add variables directly in this text by surrounding them with curly brackets:
f"This is an f-string. a's value is {a}. Doubling the value of a gives {2*a}."
"This is an f-string. a's value is 2023. Doubling the value of a gives 4046."
As you can see above, f-strings can contain as many variables as needed and curly brackets can contain more than just a variable. We can even execute functions inside them:
f"The workshop_name variable contains {workshop_name.lower().count('r')} r letters."
'The workshop_name variable contains 2 r letters.'
Exercise#
Marie Curie’s name and birthdate are stored in variables. Concatenate them in one string variable and print it out. The output should be “Marie Curie, * 7 November 1867”
first_name = "Marie"
last_name = "Curie"
birthday_day = 7
birthday_month = "November"
birthday_year = 1867