Lesson #4: Numbers
There are three numeric types in Python. Integers, floating-point numbers, and complex numbers fall under the Python numbers category. They are defined as int
, float
, and complex
classes in Python.
Int
āļø Reminder: Int, or integer, is a whole number, without decimals, and can be either positive or negative.
In the previous lesson, we learned how to define an integer.
Examples:
number_of_products = 3240
available_products = 45343
products_in_stock = 89
files_uploaded = 88430
y = -10
x = -1032342342312
Float
āļø Reminder: Float or floating-number is a number, positive or negative, containing one or more decimals, and can be either positive or negative.
In the previous lesson, we learned how to define a float.
Examples:
total_cost = 109.99
height_cm = 45.5
km = 90.4
temperature_in_celsius = 19.1
y = -10.65
Complex
āļø Reminder: In python, you can put ājā or āJā after a number to make it imaginary, so you can write complex literal easily.
In the previous lesson, we learned how to define a complex.
Examples
b = 47j
c = 10 + 5j
Casting
Casting is the process of changing the data type of an object by using the following constructor functions:
int()
float()
str()
int()
The int()
converts string and float to an integer number.
b = int(5.6) # b will be 5
c = int(“4532”) # c will be 4532
float()
The float()
converts string and integer to a float number.
b = float(32.5) # b will be 32.5
c = float(“1”) # c will be 1.0
str()
The str()
converts a variety of data types to string.
b = str(52) # b will be ’52’
c = str(5.0) # c will be ‘5.0’
Random
Python provides several functions for generating random numbers in the random module.
š” Note: A module is a collection of pre-made code that you can import into your code to add extra functionalities.
To import the random module use the following syntax:
The following code produces and displays a random integer between 1 and 10:
print(random.randint(1, 10))