Chapter: Variables and Data Types in Python
1. Variables in Python
1.1 What Are Variables?
Variables are names used to store data values. Think of a variable as a container for data. You can assign, modify, and use variables throughout your program.
1.2 Variable Naming Rules
Here are the official rules for naming variables:
Variable names can only contain letters, numbers, and underscores (
_).They must not start with a number.
Variable names are case-sensitive (
ageandAgeare different variables).Reserved words (like
if,else,while, etc.) cannot be used as variable names.
1.3 Good Practices for Naming Variables
Use descriptive names (e.g.,
user_nameinstead ofx).Use
snake_casefor variables (e.g.,first_name).Keep names consistent.
1.4 Assigning Values to Variables
You can assign values to variables using the = operator:
Multiple Assignments
You can assign multiple variables in one line:
Reassigning Variables
Variables in Python are dynamic, meaning their value and type can be reassigned.
2. Data Types in Python
Python has several built-in data types. These are broadly categorized into numeric, text, sequence, set, mapping, and boolean types.
2.1 Numeric Data Types
Integer (int)
Whole numbers, positive or negative, with no decimal points.
Unlimited precision (can store very large numbers).
Example:
Float (float)
Numbers with decimal points or in exponential form.
Example:
Complex (complex)
Numbers with a real and imaginary part.
Example:
int
42, -3
No decimal places.
float
3.14, -2.71
Has decimals.
complex
3 + 4j
Imaginary numbers.
2.2 Text Data Type
String (str)
A sequence of characters enclosed in single, double, or triple quotes.
Examples:
Tricks & Precautions:
Strings are immutable. You can’t change their contents directly.
Use escape sequences (, , etc.) to include special characters.
Common String Operations:
Concatenation
"Hello " + "World"
"Hello World"
Repetition
"A" * 5
"AAAAA"
Slicing
"Python"[0:3]
"Pyt"
Length
len("Hello")
5
2.3 Boolean Data Type
Boolean (bool)
Represents
TrueorFalse.
Example:
Booleans are often used in conditions:
2.4 Sequence Data Types
List
An ordered, mutable collection.
Example:
Key Methods:
append()
fruits.append("grape")
Add an item to the end.
remove()
fruits.remove("banana")
Remove an item.
sort()
fruits.sort()
Sort items.
Tuple
An ordered, immutable collection.
Example:
Range
Represents a sequence of numbers.
Example:
2.5 Mapping Data Type
Dictionary (dict)
Stores key-value pairs.
Example:
Access Value
user["name"]
"Alice"
Add Key-Value
user["city"] = "Paris"
Adds new key-value.
Delete Key
del user["age"]
Removes "age".
2.6 Set Data Type
Set
An unordered, unique collection.
Example:
Key Methods:
add()
numbers.add(5)
Add an element.
remove()
numbers.remove(3)
Remove an element.
2.7 NoneType
Represents a variable with no value.
3. Type Conversion
Convert between data types using built-in functions:
int(): Convert to integer.float(): Convert to float.str(): Convert to string.
Example:
4. Tricks and Precautions
Dynamic Typing: Be cautious with changing variable types, as it may lead to bugs.
Immutable vs. Mutable:
Immutable:
str,tuple.Mutable:
list,dict,set.
Copying Data:
Use
copy()for mutable types to avoid unintended changes.
Avoid Shadowing Built-ins: Don’t use names like
list,str, orinputas variable names.
Summary Table: Data Types in Python
Numeric
int
1, -3, 42
Whole numbers.
float
3.14, -0.01
Numbers with decimals.
complex
3 + 4j
Real + imaginary parts.
Text
str
"hello", 'world'
Immutable sequences of chars.
Sequence
list
[1, 2, 3]
Mutable, ordered collection.
tuple
(1, 2, 3)
Immutable collection.
range
range(5)
Sequence of numbers.
Set
set
{1, 2, 3}
Unordered, unique collection.
Mapping
dict
{"key": "value"}
Key-value pairs.
Boolean
bool
True, False
Logical values.
NoneType
None
None
Represents no value.
Last updated