Course Content
Introduction to Python
Introduction to Python
Numbers
Let's dive into numbers first. Python has the following numerical types:
int
- for integer numbers (e.g.,3
,-1
,1003
);float
- for decimal numbers (e.g.,2.8
,3.333
,-3.0
);complex
- for complex numbers (e.g.,3+2j
).
We'll focus on the first two types since the complex
type is typically reserved for scientific applications. Let's say we want to determine how many days are in 792 hours and how many seconds are in an hour. We'll crunch these numbers and identify their types.
# Calculating respective numbers days = 792/24 sec_in_hour = 60*60 # Displaying numbers and their types print("Numbers:", days, sec_in_hour) print("Types:", type(days), type(sec_in_hour))
Here's a quirky outcome! Even though both numbers were integers (of type int
), their division resulted in a float
type (yielding 33.0
). But why? Isn't 33.0
essentially an integer? Well, in math, it is. But Python, being cautious, recognizes that dividing two integers won't always give an integer result (unlike multiplication, subtraction, or addition).
Note
If you need to switch between numerical types, use
int()
to convert to integer,float()
for decimal, andcomplex()
for complex number. When you convert a decimal to an integer, Python drops the decimal portion without rounding.
# Numbers int_num = 11 real_num = 16.83 # Displaying original and converted numbers (integer - to float, and vice versa) print(int_num, float(int_num)) print(real_num, int(real_num))
Note
When converting a floating-point number to an integer, the process truncates the number by removing the decimal portion, rather than rounding it mathematically.
Thanks for your feedback!