Data Types
Data Types
Strings
Integers
Floats
Booleans
# Subscripting
print("Hello"[0])
# String
print("123" + "345")
# Large Integers
print(123_456_789)
# Boolean
print(True)
print(False)
TypeError
These errors occur when you are using the wrong data type. e.g. len(12345)
Because you can only give the len() function Strings, it will refuse to work and
give you a TypeError if you give it a number (Integer).
Type Conversion
You can convert data into different data types using special functions. e.g.
float()
int()
str()
# TypeError
# len(123)
# No TypeError
len("Hello")
# Type Checking
print(type("abc"))
print(type(123))
print(type(3.14))
print(type(True))
# Type Conversion
str()
int()
float()
bool()
Mathematical Operations
Basic Operators
Learn to use the basic mathematical operators, +, -, *, /, // and **
PEMDAS
Parentheses, Exponents, Multiplication/Division, Addition/Subtraction
# PEMDASLR Order
# ()
# **
# * OR /
# + OR -
# Outputs 7
print(3 * 3 + 3 / 3 - 3)
# Outputs 3
print(3 * 3 + 3 / 3 - 3)
Number Manipulation
Flooring a Number
You can floor a number or remove all decimal places using the int() function which
converts a floating point number (with decimal places) into an integer (whole
number).
int(3.738492) # Becomes 3
Rounding a Number
However, if you want to round a decimal number to the nearest whole number using
the traditional mathematical way, where anything over .5 rounds up and anything
below rounds down. Then you can use the python round() function.
round(3.738492) # Becomes 4
round(3.14159) # Becomes 3
Assignment Operators
Assignment operators such as the addition assignment operator += will add the
number on the right to the original value of the variable on the left and assign
the new value to the variable.
+=
-=
*=
/=
f-Strings
In Python, we can use f-strings to insert a variable or an expression into a
string.
age = 12
bmi = 84 / 1.65 ** 2
## Accumulate
score = 0
#Also
score -= 1
score *= 2
score /= 2
score = 0
height = 1.8
is_winning = True
If the bill was $150.00, split between 5 people, with 12% tip.