Python is a dynamically typed language, meaning you don’t need to declare the type of a variable when defining it. Python automatically assigns the data type based on the value. This article explains variables and the most common data types in Python: int
, float
, string
, and boolean
.
Variables in Python are used to store data values. A variable is created as soon as a value is assigned to it.
# Example 1: Variable assignment
x = 10 # Integer
name = "Alice" # String
pi = 3.14 # Float
print(x)
print(name)
print(pi)
Output:
10 Alice 3.14
Python provides several built-in data types. Let’s discuss the most common ones.
int
)The int
data type is used to represent whole numbers.
# Example 2: Working with integers
a = 5
b = 10
sum = a + b
print("Sum of integers:", sum)
Output:
Sum of integers: 15
float
)The float
data type is used to represent decimal or floating-point numbers.
# Example 3: Working with floats
c = 2.5
d = 4.8
result = c * d
print("Product of floats:", result)
Output:
Product of floats: 12.0
str
)The string
data type is used to represent text. Strings are enclosed in single, double, or triple quotes.
# Example 4: Working with strings
greeting = "Hello"
name = "Bob"
message = greeting + ", " + name + "!"
print(message)
Output:
Hello, Bob!
bool
)The boolean
data type represents two values: True
or False
.
# Example 5: Working with booleans
is_python_fun = True
is_java_fun = False
print("Is Python fun?", is_python_fun)
print("Is Java fun?", is_java_fun)
Output:
Is Python fun? True Is Java fun? False
In Python, you can check the type of a variable using the type()
function.
# Example 6: Checking variable types
print(type(10)) # int
print(type(3.14)) # float
print(type("Python")) # str
print(type(True)) # bool
Output:
Python allows variables to change their data type during runtime because it is dynamically typed.
# Example 7: Dynamic typing
var = 10 # int
print("Before:", var, type(var))
var = "Now I'm a string" # str
print("After:", var, type(var))
Output:
Before: 10After: Now I'm a string
Python's support for multiple data types and its dynamic nature make it a powerful and flexible language. Understanding variables and data types is essential for writing efficient Python programs.