1. Variables: Your Program's Memory Labels
In Python, a variable is essentially a named location in memory that stores a value. Unlike C, where you declare a variable's type (e.g., `int x;`), Python uses dynamic typing. You don't specify the type; Python figures it out at runtime based on the value you assign.
Assigning Values to Variables:
The assignment operator `=` is used to give a value to a variable.
# Assigning an integer value
student_count = 50
# Assigning a string value
course_name = "Python for Beginners"
# Assigning a floating-point value
average_score = 92.5
# Re-assigning a variable (its type can change!)
lucky_number = 7
print("Original lucky number:", lucky_number)
lucky_number = "seven" # Now it's a string!
print("New lucky number:", lucky_number)
$ python -c 'student_count = 50; course_name = "Python for Beginners"; print(student_count); print(course_name)'
50
Python for Beginners
$ python -c 'lucky_number = 7; print("Original lucky number:", lucky_number); lucky_number = "seven"; print("New lucky number:", lucky_number)'
Original lucky number: 7
New lucky number: seven
Variable Naming Rules & Best Practices (PEP 8):
- Can contain letters (a-z, A-Z), numbers (0-9), and underscores (`_`).
- Must start with a letter or an underscore. Cannot start with a number.
- Are **case-sensitive** (`age` is different from `Age`).
- Cannot be Python keywords (e.g., `if`, `for`, `class`, `print`).
- Best Practice (PEP 8): Use `snake_case` (all lowercase, words separated by underscores) for variable names (e.g., `user_name`, `total_amount`).
Interview Tip: Be prepared to explain Python's dynamic typing and how it differs from statically-typed languages like C. Also, knowledge of PEP 8 (Python Enhancement Proposal 8) for naming conventions is a big plus!
2. Data Types: Categorizing Your Information
Every value in Python has a specific data type. Understanding these types is crucial because they determine what operations you can perform on the data. Python provides a built-in function `type()` to check the data type of any variable or value.
Common Built-in Data Types:
Numbers: For numerical values.
int
(Integers): Whole numbers, positive or negative (e.g., 10, -5, 0). Python integers have arbitrary precision (can be as large as your memory allows).
float
(Floating-point numbers): Numbers with a decimal point (e.g., 3.14, -0.001, 2.0).
num_students = 65
pi_value = 3.14159
temperature = -7.5
print(type(num_students))
print(type(pi_value))
print(type(temperature))
<class 'int'>
<class 'float'>
<class 'float'>
Strings: For textual data.
str
(String): A sequence of characters. Can be enclosed in single quotes (`'...'`), double quotes (`"..."`), or triple quotes for multi-line strings (`'''...'''` or `"""..."""`).
greeting = "Hello, UdaanPath!"
city = 'Jaipur'
multi_line_quote = """
"The only way to do great work is to love what you do."
- Steve Jobs
"""
print(type(greeting))
print(multi_line_quote)
<class 'str'>
"The only way to do great work is to love what you do."
- Steve Jobs
Booleans: For true/false logic.
bool
(Boolean): Represents truth values. Has only two possible values: `True` or `False` (note the capital T and F!). Essential for control flow.
is_active = True
has_permission = False
print(type(is_active))
print(is_active)
Note: Python has many other data types like lists, tuples, dictionaries, sets, etc., which we will explore in detail in future chapters. For now, focus on numbers, strings, and booleans!
3. Operators: Performing Actions on Data
Operators are special symbols that perform operations on values and variables. The values an operator acts on are called **operands**.
Arithmetic Operators: For Math Operations
These are used with numeric values to perform common mathematical operations.
- `+` (Addition)
- `-` (Subtraction)
- `*` (Multiplication)
- `/` (Division - always returns a float)
- `%` (Modulus - remainder of division)
- `**` (Exponentiation - power)
- `//` (Floor Division - division that rounds down to the nearest whole number)
a = 15
b = 4
print(f"a + b = {a + b}") # Addition
print(f"a - b = {a - b}") # Subtraction
print(f"a * b = {a * b}") # Multiplication
print(f"a / b = {a / b}") # Division (float result)
print(f"a % b = {a % b}") # Modulus (remainder)
print(f"a ** 2 = {a ** 2}") # Exponentiation (15*15)
print(f"a // b = {a // b}") # Floor Division (rounds down)
a + b = 19
a - b = 11
a * b = 60
a / b = 3.75
a % b = 3
a ** 2 = 225
a // b = 3
String Concatenation: The `+` operator can also be used to join strings!
first_part = "Hello, "
last_part = "UdaanPath!"
full_message = first_part + last_part
print(full_message)
Assignment Operators: Shorthands for Updates
Used to assign values to variables. Compound assignment operators (`+=`, `-=`, etc.) are shortcuts.
- `=` (Simple assignment)
- `+=` (Add AND assign: `x += y` is same as `x = x + y`)
- `-=` (Subtract AND assign)
- `*=` (Multiply AND assign)
- `/=` (Divide AND assign)
- `%=` (Modulus AND assign)
- `**=` (Exponent AND assign)
- `//=` (Floor Divide AND assign)
score = 100
print("Initial score:", score)
score += 20 # score = score + 20
print("Score after bonus:", score)
items_left = 50
items_left -= 5 # items_left = items_left - 5
print("Items left:", items_left)
Initial score: 100
Score after bonus: 120
Items left: 45
Comparison Operators: Making Decisions
These compare two values and return a Boolean result (`True` or `False`). Essential for control flow (like `if` statements, which we'll cover soon!).
- `==` (Equal to)
- `!=` (Not equal to)
- `>` (Greater than)
- `<` (Less than)
- `>=` (Greater than or equal to)
- `<=` (Less than or equal to)
x = 10
y = 12
print(f"x == y : {x == y}") # False
print(f"x != y : {x != y}") # True
print(f"x > y : {x > y}") # False
print(f"x < y : {x < y}") # True
print(f"x >= 10: {x >= 10}") # True
print(f"y <= 10: {y <= 10}") # False
x == y : False
x != y : True
x > y : False
x < y : True
x >= 10: True
y <= 10: False
Common Pitfall: Do NOT confuse `=` (assignment) with `==` (comparison)! This is a frequent mistake for beginners.
Logical Operators: Combining Conditions
Used to combine conditional statements (expressions that return `True` or `False`).
- `and`: Returns `True` if BOTH operands are `True`.
- `or`: Returns `True` if AT LEAST ONE operand is `True`.
- `not`: Reverses the logical state of the operand (turns `True` to `False`, `False` to `True`).
age = 25
is_student = True
has_job = False
print(f"age > 18 and is_student: {age > 18 and is_student}") # True and True -> True
print(f"is_student or has_job: {is_student or has_job}") # True or False -> True
print(f"not has_job: {not has_job}") # not False -> True
age > 18 and is_student: True
is_student or has_job: True
not has_job: True
Other Operators (Brief Mention):
- Identity Operators (`is`, `is not`): Compare if two variables actually point to the same object in memory, not just if their values are equal.
- Membership Operators (`in`, `not in`): Test if a sequence contains a specified value. (More useful when we cover collections like lists and strings).
4. Type Conversion (Casting): Changing Data's Form
Sometimes, you need to change a value from one data type to another. This is called **type conversion** or **casting**. Python provides built-in functions for this:
- `int()`: Converts to an integer.
- `float()`: Converts to a floating-point number.
- `str()`: Converts to a string.
# String to Integer
str_num = "123"
int_num = int(str_num)
print(f"'{str_num}' (type {type(str_num)}) converted to {int_num} (type {type(int_num)})")
# Float to Integer (truncates decimal part)
float_val = 9.81
int_val = int(float_val)
print(f"{float_val} (type {type(float_val)}) converted to {int_val} (type {type(int_val)})")
# Integer to Float
int_val_2 = 50
float_val_2 = float(int_val_2)
print(f"{int_val_2} (type {type(int_val_2)}) converted to {float_val_2} (type {type(float_val_2)})")
# Number to String
num_to_str = 789
str_from_num = str(num_to_str)
print(f"{num_to_str} (type {type(num_to_str)}) converted to '{str_from_num}' (type {type(str_from_num)})")
'123' (type <class 'str'>) converted to 123 (type <class 'int'>)
9.81 (type <class 'float'>) converted to 9 (type <class 'int'>)
50 (type <class 'int'>) converted to 50.0 (type <class 'float'>)
789 (type <class 'int'>) converted to '789' (type <class 'str'>)
Important: You can only convert strings to numbers if they contain valid numeric characters. Trying to convert `"hello"` to an `int` will result in a `ValueError`.