Course Content
Introduction to Python
Introduction to Python
Data Types in Python
In Python, as in many other programming languages, you can work with objects of different types. Understanding the distinctions between them is crucial, especially in terms of how they are stored in computer memory. Below are the various data types available in Python.
You don’t need to memorize all these data types right away, as you won’t be using all of them immediately. Instead, we’ll explore each one in detail in upcoming chapters as needed. If you're curious about the type of a specific variable, you can use the type()
function. And to see the result, always use the print()
function.
# Create some variable var = 12 # Check variable type print(type(var))
Let's start by exploring numbers in Python. The language provides the following numerical types:
int
– Represents whole numbers (e.g.,3
,-1
,1003
).float
– Represents decimal (floating-point) numbers (e.g.,2.8
,3.333
,-3.0
).complex
– Represents complex numbers, typically used in scientific applications (e.g.,3+2j
).
Since complex numbers are rarely used in everyday programming, we'll focus on integers and
# Calculating respective numbers days = 792 / 24 seconds_in_hour = 60 * 60 # Displaying numbers and their types print("Numbers:", days, seconds_in_hour) print("Types:", type(days), type(seconds_in_hour))
Even though both numbers were int
, their division resulted in a float
(33.0
). This is because Python ensures division (/
) always returns a float, even when the result is a whole number, to maintain consistency.
If you need to switch between numerical types, use int()
to convert to integer, float()
for decimal, and complex()
for complex number. When you convert a decimal to an integer, Python drops the decimal portion without rounding.
# Variables 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))
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!