0% found this document useful (0 votes)
3 views

Python Unit 1

The document provides an overview of Python programming concepts, including identifiers, keywords, indentation, comments, operators, strings, tuples, lists, and sets. It outlines rules for naming identifiers, explains the significance of reserved keywords, and emphasizes the importance of indentation for code structure. Additionally, it details the characteristics and operations of various data types, highlighting their mutability and methods for manipulation.

Uploaded by

yeeshandas
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python Unit 1

The document provides an overview of Python programming concepts, including identifiers, keywords, indentation, comments, operators, strings, tuples, lists, and sets. It outlines rules for naming identifiers, explains the significance of reserved keywords, and emphasizes the importance of indentation for code structure. Additionally, it details the characteristics and operations of various data types, highlighting their mutability and methods for manipulation.

Uploaded by

yeeshandas
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

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:

- An identifier must start with a letter (A-Z or a-z) or an underscore (_).

- 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:

- Valid Identifiers: - Invalid Identifiers:


- `my_var` - `1variable` (cannot start with a digit)
- `_privateVar` - `my-variable` (cannot contain hyphens)
- `variable1` - `class` (reserved keyword)
- `MyClass`

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.

1. `False` - Represents a Boolean value of false.

2. `None` - Represents the absence of a value or a null value.

3. `True` - Represents a Boolean value of true.

4. `and` - A logical operator used to combine conditional statements.


5. `as` - Used to create an alias while importing a module.

6. `assert` - Used for debugging purposes to test if a condition is true.

7. `break` - Exits the nearest enclosing loop.

8. `class` - Used to define a new class.

9. `continue` - Skips the rest of the code inside the enclosing loop for the current iteration and moves to
the next iteration.

10. `def` - Used to define a function.

11. `del` - Deletes objects.

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.

14. `except` - Used with exceptions to handle errors.

15. `finally` - Used to execute code regardless of whether an exception was raised or not.

16. `for` - Used to create a for loop.

17. `from` - Used to import specific parts of a module.

18. `global` - Declares that a variable is global (outside the local scope).

19. `if` - Used to make decisions based on conditions.

20. `import` - Used to include the functionality of another module.

21. `in` - Used to check if a value exists within a sequence.

22. `is` - Used to test object identity.

23. `lambda` - Creates an anonymous function (a function with no name).

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.

26. `or` - A logical operator used to combine conditional statements.

27. `pass` - A null statement used as a placeholder in loops, functions, classes, etc.

28. `raise` - Used to raise an exception.

29. `return` - Exits a function and optionally returns a value.

30. `try` - Used to catch exceptions and handle errors.

31. `while` - Used to create a while loop.


32. `with` - Used to wrap the execution of a block of code within methods defined by a context manager.

33. `yield` - Used to make a function generator-based.

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.

Key Points about Indentation:

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.

Types of Comments in Python

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.

Using consecutive single-line comments:

Using triple-quoted strings:

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.

- `+` : Addition (`a + b` gives the sum of `a` and `b`)

- `-` : Subtraction (`a - b` gives the difference of `a` and `b`)

- `*` : Multiplication (`a * b` gives the product of `a` and `b`)

- `/` : Division (`a / b` gives the quotient of `a` and `b`)

- `%` : Modulus (`a % b` gives the remainder when `a` is divided by `b`)

- `**` : Exponentiation (`a ** b` raises `a` to the power of `b`)

- `//` : Floor division (`a // b` gives the quotient of `a` divided by `b` and rounds down to the nearest
integer)

2. Comparison Operators: Comparison operators are used to compare two values.

- `==` : Equal to (`a == b` returns `True` if `a` is equal to `b`)

- `!=` : 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`)

3. Logical Operators: Logical operators are used to combine conditional statements.

- `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 AND

- `|` : Bitwise OR

- `^` : Bitwise XOR

- `~` : Bitwise NOT

- `<<` : Left shift

- `>>` : Right shift

5. Assignment Operators: Assignment operators are used to assign values to variables.

- `=` : 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

(`a += b` is equivalent to `a = a + b`)

- `-=` : Subtracts the right operand from the left operand and assigns the result to the left operand

(`a -= b` is equivalent to `a = a - b`)

- `*=` : Multiplies the right operand with the left operand and assigns the result to the left operand

(`a *= b` is equivalent to `a = a * b`)

- `/=` : Divides the left operand by the right operand and assigns the result to the left operand

(`a /= b` is equivalent to `a = a / b`)

- `%=` : Takes the modulus using the two operands and assigns the result to the left operand

(`a %= b` is equivalent to `a = a % b`)

- `**=` : Raises the left operand to the power of the right operand and assigns the result to the left

operand (`a **= b` is equivalent to `a = a ** b`)


6. Identity Operators: Identity operators are used to compare the memory locations of two objects.

- `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`)

7. Membership Operators: Membership operators are used to test if a sequence is presented in an


object.

- `in` : Returns `True` if a value is found in the sequence (`a in 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.

Key Characteristics of Strings in Python

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.

4. Concatenation:- Strings can be combined or "concatenated" using the `+` operator.

5. Repetition:- Strings can be repeated using the `*` operator.

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:

- `upper()`: Converts all characters to uppercase.

- `lower()`: Converts all characters to lowercase.

- `strip()`: Removes any leading and trailing whitespace.

- `split()`: Splits the string into a list of substrings based on a delimiter.

- `replace()`: Replaces occurrences of a substring with another substring.

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.

Basic overview of tuples:

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

- Concatenation: You can combine tuples using the `+` operator.

- Repetition: You can repeat a tuple using the `*` operator.

- 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

Tuples have only two 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.

Key Features of 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.

Basic Operations with Lists:

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:

- Append: Adds an element to the end of the list.

- Insert: Adds an element at a specific position.


5. Removing Elements:

- Remove: Removes the first occurrence of a value.

- 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.

Key Features of Sets:

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.

Adding Elements to a Set

You can add elements to a set using the `add()` method.

Removing Elements from a Set

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.

- Union (`|`): Combines elements from both sets.

- Intersection (`&`): Elements that are common to both sets.

- 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 `:`.

Accessing Values in a Dictionary:

You can access values in a dictionary by using the key.

Adding or Updating Items in a Dictionary:

You can add new key-value pairs to an existing dictionary or update the value of an existing key.
Removing Items from a Dictionary:

There are several ways to remove items from a dictionary:

1. `pop(key)`: Removes the specified key and returns its value.

2. `del` keyword: Deletes the specified key from the dictionary.

3. `clear()`: Empties the entire dictionary.

4. `popitem()`: Removes and returns the last inserted key-value pair.

Dictionary Methods:

1. `keys()`: Returns all the keys in the dictionary.

2. `values()`: Returns all the values in the dictionary.

3. `items()`: Returns all the key-value pairs as tuples.

Looping Through a Dictionary:

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.

You might also like