Numeric Types
Python has several numeric types to represent different kinds of numbers. The most commonly used numeric types are:
- int: Represents whole numbers (integers) without a decimal point.
- float: Represents real numbers (floating-point numbers) with a decimal point.
- complex: Represents complex numbers, which have a real and an imaginary part.
For the most part you will be using int and float types in this class.
Integer (int)
An int is a whole number without a decimal point. You can create an integer variable like this:
# Example of an integer variable
age = 30In this example, age is an integer variable that stores the value 30.
Float (float)
A float is a number that has a decimal point. You can create a float variable like this:
# Example of a float variable
height = 5.9In this example, height is a float variable that stores the value 5.9.
Performing operations with numeric types
In Python, you can perform various arithmetic operations with numeric types. Here are some examples:
# Addition
a = 10
b = 5
sum = a + b # sum will be 15
# Subtraction
difference = a - b # difference will be 5
# Multiplication
product = a * b # product will be 50
# Division
quotient = a / b # quotient will be 2.0
# Modulus
remainder = a % b # remainder will be 0Combining Operators/Order of Operations
Just like you would do with real math equations, you can combine as many numbers, variables, and operators as you’d like.
You can use parentheses if you want to change the order of operations or make your equations easier to understand.
a = 30
b = 4
result = 10 + a - (b / 2)What is the result of this equation?
Combining numeric types in an equation
You can also combine different numeric types in operations. For example, adding an int and a float will result in a float:
# Combining int and float
x = 10 # int
y = 2.5 # float
result = x + y # result will be 12.5 (float)We’ll learn more about how this works in the section on Type Conversions
That’s a brief overview of numeric types in Python! Next, we’ll explore other variable types such as strings and booleans.