Python Unit 1
Python Unit 1
Identifier
In Python, Identifiers are names used to identify variables, functions, classes, modules, or other objects.
They are an essential part of writing code, especially in data analytics, where you frequently work with
various datasets, functions, and algorithms.
Rules:
1. Naming Rules:
- The rest of the identifier can contain letters, digits (0-9), and underscores.
- Identifiers are case-sensitive (two words that appear or sound identical, but are using different letter
cases, are not considered equal.). For example, `myVariable` and `myvariable` are different identifiers.
2. Reserved Words: Python has reserved keywords that cannot be used as identifiers (e.g., `class`, `def`,
`if`, `for`). These are reserved for Python's syntax and functionality.v
Conventions:
1. Descriptive Names: Use meaningful names for identifiers to make your code more readable (e.g.,
`total_amount` instead of `ta`).
3. Avoiding Conflicts: Avoid using names that are too similar to built-in functions or standard library
module names to prevent confusion.
Examples:
Keywords
Keywords in Python are reserved words that have special meaning in the language. They can't be used as
identifiers (like variable names or function names). These keywords are part of the syntax and structure
of Python.
9. `continue` - Skips the rest of the code inside the enclosing loop for the current iteration and moves to
the next iteration.
12. `elif` - Used in conditional statements, it's short for "else if."
13. `else` - Used in conditional statements and loops to execute a block of code if the condition is not
met.
15. `finally` - Used to execute code regardless of whether an exception was raised or not.
18. `global` - Declares that a variable is global (outside the local scope).
24. `nonlocal` - Used to declare that a variable inside a nested function refers to a variable in the nearest
enclosing scope.
25. `not` - A logical operator used to invert the value of a boolean expression.
27. `pass` - A null statement used as a placeholder in loops, functions, classes, etc.
Indentation
In Python, Indentation is crucial because it defines the structure and flow of your code. Unlike many
other programming languages that use curly braces `{}` or keywords to define code blocks, Python relies
on indentation to determine which lines of code are part of which block. This makes Python code visually
clean and easy to read but also means that incorrect indentation will lead to errors.
1. Defining Code Blocks: Indentation is used to define code blocks such as those in loops, conditionals,
functions, and classes. All lines of code within a block must be indented at the same level. For example:
2. Consistency: You must use consistent indentation throughout your code. You can use either spaces or
tabs, but you should not mix them. The Python community strongly recommends using 4 spaces per
indentation level.
3. IndentationError: If your code is not properly indented, Python will raise an `IndentationError`. For
example:
4. Nested Indentation: When you have nested code blocks, each nested block should be indented
further. For example:
Here, the `for` loop is inside the `if` block, so it is indented further.
5. Functions and Classes: Indentation is also used to define the bodies of functions and classes:
Each line inside a function or class definition is indented to show it belongs to that block.
Comments
Comments are used to add notes or explanations within the code. Comments help make the code more
readable and easier to understand for anyone reading it, including yourself in the future. They are not
executed by the Python interpreter and are purely for the benefit of the programmer.
1. Single-line Comments: Single-line comments start with the hash symbol (`#`). Anything written after
the `#` on that line is considered a comment and is ignored by Python. Example:
2. Multi-line Comments: Python does not have a specific syntax for multi-line comments like some other
languages (e.g., `/* ... */` in C/C++). However, you can create multi-line comments by using consecutive
single-line comments or by using triple-quoted strings (`'''` or `"""`), although the latter is actually a
multi-line string, not a comment.
Note: While triple-quoted strings are not technically comments, they can be used like comments.
However, they are stored in memory as a string object, so use them wisely.
Operators
Python operators are symbols that perform operations on variables and values. Operators are used to
manipulate data and variables in Python, allowing you to perform computations, make comparisons, and
perform logical operations.
1. Arithmetic Operators: Arithmetic operators are used to perform mathematical operations like
addition, subtraction, multiplication, etc.
- `%` : Modulus (`a % b` gives the remainder when `a` is divided by `b`)
- `//` : Floor division (`a // b` gives the quotient of `a` divided by `b` and rounds down to the nearest
integer)
- `!=` : Not equal to (`a != b` returns `True` if `a` is not equal to `b`)
- `>` : Greater than (`a > b` returns `True` if `a` is greater than `b`)
- `<` : Less than (`a < b` returns `True` if `a` is less than `b`)
- `>=` : Greater than or equal to (`a >= b` returns `True` if `a` is greater than or equal to `b`)
- `<=` : Less than or equal to (`a <= b` returns `True` if `a` is less than or equal to `b`)
- `and` : Returns `True` if both statements are true (`a and b`)
- `or` : Returns `True` if one of the statements is true (`a or b`)
- `not` : Reverses the result, returns `True` if the statement is false (`not a`)
4. Bitwise Operators: Bitwise operators perform operations on binary digits of integer values.
- `|` : Bitwise OR
- `=` : Assigns the value on the right to the variable on the left (`a = b`)
- `+=` : Adds the right operand to the left operand and assigns the result to the left operand
- `-=` : Subtracts the right operand from the left operand and assigns the result to the left operand
- `*=` : Multiplies the right operand with the left operand and assigns the result to the left operand
- `/=` : Divides the left operand by the right operand and assigns the result to the left operand
- `%=` : Takes the modulus using the two operands and assigns the result to the left operand
- `**=` : Raises the left operand to the power of the right operand and assigns the result to the left
- `is` : Returns `True` if both variables are the same object (`a is b`)
- `is not` : Returns `True` if both variables are not the same object (`a is not b`)
- `not in` : Returns `True` if a value is not found in the sequence (`a not in b`)
String
String is a data type used to represent text. A string is essentially a sequence of characters enclosed in
single quotes (`'...'`), double quotes (`"..."`), triple single quotes (`'''...'''`), or triple double quotes
(`"""..."""`). This allows you to store and manipulate textual data.
1. Immutable:- Once a string is created, it cannot be changed. This immutability means that any
operations on a string that alter its content will always produce a new string, rather than modifying the
original string.
2. Indexing:- Each character in a string has a position or index, starting from `0` for the first character up
to `n-1` for the last character, where `n` is the length of the string. Python also supports negative
indexing, where `-1` is the last character, `-2` is the second last, and so on.
3. Slicing:- Slicing allows you to extract a portion of a string using a colon (`:`) to separate the start and
end indices. The slice includes characters from the start index up to, but not including, the end index.
6. Length:- You can find out how many characters are in a string using the `len()` function.
7. String Methods:- Python provides many built-in methods to manipulate strings. Some common
methods include:
8. Multiline Strings:- Multiline strings can be created using triple quotes (`'''...'''` or `"""..."""`). This is
useful for strings that span multiple lines, like long text or documentation.
Tuples
Tuples in Python are a type of data structure that are very similar to lists but have a key difference: they
are immutable, meaning once you create a tuple, you can't change its contents. This can make tuples
useful for storing data that shouldn't be modified.
Creating a Tuple:- You create a tuple by placing values inside parentheses, separated by commas:
Accessing Tuple Elements:-You can access elements in a tuple using indexing, just like with lists:
Tuple Immutability:- Since tuples are immutable, you can't change their values once they are created:
Tuple Operations
- Length: You can get the number of elements in a tuple using the `len()` function.
- Unpacking: You can unpack tuple values into separate variables.
Tuple Methods
- `count(value)`: Returns the number of times a specified value occurs in the tuple.
- `index(value)`: Returns the index of the first occurrence of a specified value. If the value is not found, it
raises a `ValueError`.
Example Program
List
A list in Python is a versatile and widely used data structure that allows you to store a collection of items
in a single variable. Lists can contain items of different data types, such as integers, strings, floats, and
even other lists.
1. Ordered: Lists maintain the order of elements. The order in which you add items to the list is the order
in which they will be stored.
2. Mutable: You can change the items in a list after it has been created. This means you can add, remove,
or modify elements.
3. Heterogeneous: A single list can store different data types. For example, you can have a list with
integers, strings, and floats all together.
1. Creating a List: You can create a list by placing items inside square brackets `[]`, separated by commas.
2. Accessing Elements: You can access elements in a list using their index. Python uses zero-based
indexing, so the first element is at index `0`.
3. Modifying Elements: Since lists are mutable, you can change an element by accessing it through its
index and assigning a new value.
4. Adding Elements:
- Pop: Removes and returns the element at a specific index. If no index is provided, it removes the last
item.
6. Slicing: You can get a subset of a list by using slicing. The syntax is `list[start:stop]`, which returns
elements from the `start` index to `stop - 1`.
Example Program:
Set
Set is a built-in data type that is used to store unique elements. It is similar to a list or dictionary but with
some key differences.
1. Unique Elements: Sets do not allow duplicate values. If you try to add a duplicate element to a set, it
will be ignored.
2. Unordered: Sets do not maintain any order for the elements. This means that the elements do not
have a fixed position or index.
3. Mutable: Sets are mutable, meaning you can add or remove elements after the set has been created.
4. No Indexing: Because sets are unordered, you cannot access elements by index, like you can with lists.
Creating a Set
You can create a set using curly braces `{}` or the `set()` function.
You can remove elements from a set using the `remove()` or `discard()` method.
Common Set Operations
Sets support various operations like union, intersection, difference, and symmetric difference.
- Difference (`-`): Elements present in the first set but not in the second.
- Symmetric Difference (`^`): Elements that are in either set, but not in both.
Example Program
Dictionary
A dictionary is a built-in data structure that stores data in key-value pairs. It is one of the most commonly
used data structures because it allows for fast data retrieval.
Features of a Dictionary:
1. Unordered: Dictionaries are unordered collections, meaning that the items are not stored in a specific
sequence. The order of the items might change as you add or remove items.
2. Mutable: Dictionaries are mutable, which means you can modify them after they are created. You can
add, remove, or change items.
3. Key-Value Pair: Each item in a dictionary consists of a key and a value. The key is used to access the
corresponding value. Keys must be unique, while values can be duplicated.
4. Heterogeneous: Keys and values in a dictionary can be of any data type—strings, integers, lists, etc.
Creating a Dictionary:
Dictionaries are defined using curly braces `{}`, and the key-value pairs are separated by a colon `:`.
You can add new key-value pairs to an existing dictionary or update the value of an existing key.
Removing Items from a Dictionary:
Dictionary Methods:
You can loop through the key-value pairs in a dictionary using a `for` loop.
Example Program:
Output:
Key Takeaways:
- Dictionaries are highly versatile and allow for efficient data storage and retrieval based on unique keys.
- They support various operations like addition, update, deletion, and iteration, making them useful for
numerous applications in Python programming.