1.2 Python building block
Python, like any programming language, has fundamental elements that
form the foundation of its programs. These building blocks include basic
syntax, data types, control structures, and functions, among others.
Understanding these is key to writing efficient and effective Python code.
1. Indentation
:-
Why Is
Indentation Important?
- Defines Code Blocks:
Indentation indicates a block of code, such as within loops, functions, or
conditionals.
- Improves Readability:
Indented code is easier to read and understand.
- Mandatory: Python will throw an error if the
indentation is incorrect.
Rules of
Indentation in Python
1.
Consistent Indentation: Use the same number of spaces or tabs throughout a block of code.
2.
Preferred Style: Use 4 spaces for each level of indentation (as recommended by
PEP 8, Python's style guide).
3. No Mixing: Do not mix tabs and spaces in the same file, as this can cause errors.
2. Identifiers in Python
Identifiers in Python are the names used to
identify variables, functions, classes, modules, and other objects. They are
user-defined names that must follow specific rules and conventions.
Rules for Naming Identifiers
1.
Allowed
Characters:
o
Can contain
letters (a-z, A-Z), digits (0-9), and underscores (_).
o
Must not start with a digit.
valid_name = 10 # Valid2nd_name = 20 # Invalid
2.
Case
Sensitivity:
o
Identifiers are
case-sensitive, meaning Name and name are different.
Name = "Alice"name = "Bob"print(Name) # Outputs: Aliceprint(name) # Outputs: Bob
3.
No
Reserved Words:
o Keywords (reserved words) cannot be used as identifiers.
def = 5 # Invalid: 'def' is a reserved word in Python
4.
Special
Characters:
o
Cannot contain
special characters like @, $, %, etc.
my$name = 50 # Invalid
5.
No Spaces:
o
Spaces are not
allowed in identifiers. Use underscores _ instead.
first_name = "Alice" # Validfirst name = "Bob" # Invalid
Examples of Valid
and Invalid Identifiers
|
Valid
Identifiers |
Invalid
Identifiers |
|
|
|
|
|
|
|
|
|
|
|
|
Conventions for
Naming Identifiers
Although Python does not enforce these,
following conventions improves code readability and maintainability:
1.
Variable
Names:
o
Use lowercase
letters, and separate words with underscores (snake_case).
max_value = 100user_name = "Alice"
2.
Function
Names:
o Use lowercase letters with underscores between words.
def calculate_area(radius): return 3.14 * `radius * radius
3.
Class
Names:
o
Use PascalCase
(capitalize the first letter of each word).
class Circle: pass
4.
Constant
Names:
o Use all uppercase letters with underscores.
PI = 3.14159MAX_LIMIT = 100
5.
Private
Identifiers:
o
Prefix with a
single underscore (_) to indicate a non-public identifier.
_internal_data = 42
6.
Special
Identifiers:
o
Prefix and suffix
with double underscores (__) for special methods.
def __init__(self): pass
Built-in
Functions and Identifiers
Python provides many built-in functions like print(), len(), etc. Avoid
using their names for your identifiers, as it can overwrite these functions.
Example:
print = 5 # Avoid doing thisprint("Hello") # This will raise an error
Good Practices
· Choose meaningful names:
# Badx = 50# Goodmax_speed = 50
·
Follow
conventions for consistent and readable code.
·
Avoid overly long
names.
Example: Identifiers in a Program
# Valid identifiersuser_name = "Alice"age = 25# Function with a proper identifierdef calculate_age_in_days(age): return age * 365# Calling the functionprint(f"{user_name} is {calculate_age_in_days(age)} days old.")
Variable
- Variables: Used to store data.
x = 10 # Integer
y =
3.14 # Float
name =
"Python" # String
is_active =
True # Boolean
- Data Types:
- Numeric: int, float, complex
- Sequence: str, list, tuple
- Set: set, frozenset
- Mapping: dict
- Boolean: True, False
- NoneType: None
2.
Operators
- Arithmetic Operators: +, -, *, /, %, //, **
Used to
perform basic mathematical operations.
|
Operator |
Description |
Example |
|
+ |
Addition |
5 + 3 = 8 |
|
- |
Subtraction |
5 - 3 = 2 |
|
* |
Multiplication |
5 * 3 = 15 |
|
/ |
Division |
5 / 2 = 2.5 |
|
% |
Modulus (remainder) |
5 % 2 = 1 |
|
** |
Exponentiation (power) |
5 ** 3 = 125 |
|
// |
Floor division(integer value) |
5 // 2 = 2 |
- Comparison Operators: ==, !=, >, <, >=, <=
Relational (Comparison Operator): Used to compare two values and return a Boolean result (True or False).
|
Operator |
Description |
Example |
|
== |
Equal to |
5 == 3 → False |
|
!= |
Not equal to |
5 != 3 → True |
|
> |
Greater than |
5 > 3 → True |
|
< |
Less than |
5 < 3 → False |
|
>= |
Greater than or equal to |
5 >= 3 → True |
|
<= |
Less than or equal to |
5 <= 3 → False |
- Logical Operators: and, or, not
Logical Operator are used to combine conditional statements.
|
Operator |
Description |
Example |
|
and |
Returns True if both
conditions are True |
(5 > 3 and 2 > 1) → True |
|
or |
Returns True if at
least one condition is True |
(5 > 3 or 2 < 1) → True |
|
not |
Reverses the result |
not(5 > 3) → False |
- Bitwise Operator:
Operate at the binary level.
|
Operator |
Description |
Example |
|
& |
AND |
5 & 3 → 1 |
|
` |
` |
OR |
|
^ |
XOR |
5 ^ 3 → 6 |
|
~ |
Complement |
~5 → -6 |
|
<< |
Left shift |
5 << 1 → 10 |
|
>> |
Right shift |
5 >> 1 → 2 |
- Assignment Operators: =, +=, -=, *=, /=, etc.
|
Operator |
Description |
Example |
|
= |
Assign |
x = 5 |
|
+= |
Add and assign |
x += 3 → x = x + 3 |
|
-= |
Subtract and assign |
x -= 3 → x = x - 3 |
|
*= |
Multiply and assign |
x *= 3 → x = x * 3 |
|
/= |
Divide and assign |
x /= 3 → x = x / 3 |
|
%= |
Modulus and assign |
x %= 3 → x = x % 3 |
|
**= |
Exponentiate and assign |
x **= 3 → x = x ** 3 |
|
//= |
Floor divide and assign |
x //= 3 → x = x // 3 |
- Membership Operators: in, not in,range
Membership
Operator: Used to test if a value is in a sequence (like a list, string, or
tuple).
|
Operator |
Description |
Example |
|
in |
Returns True if the
value is present in the sequence |
"a" in "apple" → True |
|
not in |
Returns True if the
value is not present in the sequence |
"b" not in "apple" → True |
- Identity Operators: is, is not
Identity Operator
used to compare the memory locations of two objects.
|
Operator |
Description |
Example |
|
is |
Returns True if both
variables point to the same object |
x is y → True |
|
is not |
Returns True if both
variables point to different objects |
x is not y → True |
# Arithmetic Operators
a, b = 5, 3
print("Addition:", a + b) # 8
print("Exponentiation:", a **
b) # 125
# Comparison Operators
print("Is a greater than b?", a > b) # True
# Logical Operators
print("Logical AND:", a > 2 and
b < 5) # True
# Membership Operators
lst = [1, 2, 3, 4, 5]
print("Is 3 in the list?", 3 in
lst) # True
# Identity Operators
x = [1, 2, 3]
y = [1, 2, 3]
print("x is y:", x is y) # False (different objects in memory)
No comments:
Post a Comment