To start off our tutorial series, we will first learn about basic data types in Python.
Strings – Commonly used to represent text, but numbers can be strings as well.
Integers – If you remembered learning E Maths in secondary school, integers are just whole numbers.
Floats – Other real numbers which have demical places are floats. Do note that 3.0 is considered a float, while 3 is an integer.
Assigning strings to variables
In Python, assigning means storing or setting a value to a variable. For example, when I say “assign ‘apple’ to x”, I would store the string ‘apple’ to x, and x will return the string ‘apple’. In IDLE, you have to type print(x) to show an output in the complier.
Whenever you assign a string to a variable, do remember to include double apostrophes around your text!
x = "hello world!" print(x)
Assigning integers/floats to variables
Similarly, we can assign integers and floats to variables in Python. To assign an integer or a float, we do not include double apostrophes. This differentiates it from assigning strings.
# assigning an integer a = 1 print(a)
# assigning a string b = "1" print(b)
# assigning a float c = 1.0 print(c)
Checking the type of a variable
To check the type of a variable, we will use the function type(). You will learn more about functions in Chapter 6.
# Using type() function print(type(a)) print(type(b)) print(type(c))
class 'int' class 'str' class 'float'
Booleans are used to represent truth values in Python. They are either be True or False. You can assign a Boolean to a variable, but they are more commonly used as the output of logical (boolean) operations. Booleans are important as they can be used to perform filtering operations on data structures.
Comparison operations are a type of logical operations. The most commonly used ones are >, <=, =<, < and ==. In Python, the operator ‘==’ means equal to in Mathematics, as ‘=’ is reserved for assigning variables.
a = 10 b = 15 print(a > b)
c = 20 d = 20 print(c == d)
We can also check multiple comparison statements using ‘and’ and ‘or’.
print(a > b and c == d)
print(a > b or c == d)
The Boolean True has a value of 1 while False has a value of 0. You can also compare between booleans.
x = True y = False
# Checking the type of variables x and y print(type(x)) print(type(y))
class 'bool' class 'bool'
print(x == 1)
print(y == 0)
Note that when assigning booleans to variables, True or False need to be capitalised.
x = true y = false