Python for Beginners
Python Data Types
In Python, data types determine the kind of value a variable can hold. Python has 8 built-in
data types grouped into several categories.
1. Numeric Types
int (Integer)
- Whole numbers, positive or negative, without a decimal point.
Example:
x = 10
y = -5
print(type(x)) # <class 'int'>
float (Floating Point)
- Numbers with decimal points.
Example:
a = 3.14
b = -0.5
print(type(a)) # <class 'float'>
complex
- Used for complex numbers. The imaginary part uses j.
Example:
c = 2 + 3j
print(c.real) # 2.0
print(c.imag) # 3.0
2. Text Type - str (String)
Text enclosed in quotes. Supports indexing and length checking.
Example:
name = "Mg Mg"
message = 'Hello, Python!'
print(name[0]) # M
print(len(message)) # 13
3. Boolean Type - bool
Represents logical values: True or False.
Example:
is_active = True
print(5 > 3) # True
4. Sequence Types
list
- Mutable and ordered.
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits[1]) # banana
tuple
- Immutable and ordered.
colors = ("red", "green", "blue")
range
- Represents a sequence of numbers.
for num in range(5):
print(num)
5. Mapping Type - dict (Dictionary)
Key-value pairs enclosed in {}.
user = {"name": "Alice", "age": 30}
print(user["name"]) # Alice
6. Set Types
set
- Unordered collection of unique elements.
unique_numbers = {1, 2, 2, 3} # {1, 2, 3}
frozenset
- Immutable version of a set.
f_set = frozenset([1, 2, 3])
7. None Type - None
Represents a null or undefined value.
result = None
8. Type Checking and Conversion
type(): Shows the data type.
print(type(5)) # int
isinstance(): Checks type.
print(isinstance(3.14, float)) # True
Type Conversion:
num_str = "123"
num_int = int(num_str)
print(num_int + 5) # 128
9. Mutable vs Immutable
Mutable: list, dict, set
Immutable: int, float, str, tuple
Basic Calculations
Python uses arithmetic operators for calculations.
+ (Addition), - (Subtraction), * (Multiplication), / (Division), // (Floor Division), %
(Modulus), ** (Exponentiation)
Example:
a = 10
b=5
print('Addition:', a + b)
print('Subtraction:', a - b)
print('Multiplication:', a * b)
print('Division:', a / b)
print('Floor Division:', a // b)
print('Modulus:', a % b)
print('Exponentiation:', a ** b)