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

python 3

The document covers essential Python concepts including list comprehensions, generators, string manipulation, nested lists and dictionaries, decorators, and the PEP 8 style guide. It emphasizes efficient coding practices, memory management, and readability through structured data and formatting techniques. Understanding these concepts enhances coding skills and promotes better collaboration among programmers.

Uploaded by

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

python 3

The document covers essential Python concepts including list comprehensions, generators, string manipulation, nested lists and dictionaries, decorators, and the PEP 8 style guide. It emphasizes efficient coding practices, memory management, and readability through structured data and formatting techniques. Understanding these concepts enhances coding skills and promotes better collaboration among programmers.

Uploaded by

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

INTERNPE INTERNSHIP/TRAINING PROGRAM

PYTHON 3 (NOTES CONTENT)

PE
**Chapter 11: List Comprehensions and Generators**
**Introduction to List Comprehensions and Generators:**
RN
Imagine you have to paint a fence. You could paint each plank one by one, or you could use
a roller to cover a lot of ground quickly. List comprehensions and generators in Python are
like those efficient tools. They help you create and work with lists in a more concise and
resource-friendly way.

**List Comprehensions:**
List comprehensions are a way to create lists using a compact and readable syntax. It's like
telling Python, "Make a list by applying this operation to each item in another list."
TE
```python
numbers = [1, 2, 3, 4, 5]
squared_numbers = [x ** 2 for x in numbers]
print(squared_numbers) # Outputs: [1, 4, 9, 16, 25]
```

**List Comprehensions with Conditionals:**


You can also add conditions to list comprehensions, like filtering out certain elements.
IN

```python
even_numbers = [x for x in numbers if x % 2 == 0]
print(even_numbers) # Outputs: [2, 4]
```

**Generators:**
Generators are like a conveyor belt that produces items one by one, rather than creating a
whole list upfront. This is especially useful when dealing with large datasets, as generators
use less memory.

**Creating a Generator:**
To create a generator, you use parentheses instead of square brackets in a list
comprehension.

```python
squared_generator = (x ** 2 for x in numbers)
print(squared_generator) # Outputs: <generator object ...>
```

**Using Generators:**

PE
You can use generators in loops or convert them to lists if needed.

```python
for squared_number in squared_generator:
print(squared_number)

squared_list = list(squared_generator)
```

RN
**Advantages of Generators:**
- **Memory Efficiency:** Generators produce items one by one, saving memory.
- **Lazy Evaluation:** Items are generated as needed, reducing processing time.
- **Infinite Sequences:** Generators can produce an infinite stream of data.

**Conclusion:**
List comprehensions and generators are like specialized tools for creating and working with
lists. List comprehensions allow you to create lists with concise syntax, while generators
provide a memory-efficient way to generate and work with sequences of data. By using
TE
these tools, you can write more efficient, readable, and resource-friendly code.
IN

**Chapter 12: String Manipulation**


**Introduction to String Manipulation:**
Strings in programming are like a series of characters, just like words in a sentence. String
manipulation involves changing, combining, or analyzing these characters to perform various
tasks. Think of it as editing and arranging text in a document.
**Accessing Characters in a String:**
Strings are made up of individual characters, each with its own position (index). You can
access these characters using their index.

```python
text = "Hello, Python!"
print(text[0]) # Outputs: H
print(text[7]) # Outputs: P
```

PE
**String Length:**
The length of a string is the count of its characters. You can find it using the `len()` function.

```python
length = len(text) # Gets the length of the string
print(length) # Outputs: 14
```

RN
**String Concatenation:**
Concatenation means combining strings together. It's like putting puzzle pieces together to
form a bigger picture.

```python
greeting = "Hello"
name = "Alice"
message = greeting + ", " + name
print(message) # Outputs: Hello, Alice
TE
```

**String Methods:**
Strings come with a variety of built-in functions called methods. Methods are like tools that
perform specific actions on strings.

- `upper()`: Converts the string to uppercase.


- `lower()`: Converts the string to lowercase.
IN

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


- `find()`: Finds the index of a substring.
- `split()`: Splits the string into a list of substrings.

```python
text = "Hello, World!"
upper_text = text.upper() # Converts to uppercase
print(upper_text) # Outputs: HELLO, WORLD!
```

**Formatting Strings:**
Formatting means inserting values into a string in a specific format. It's like filling in the
blanks.

```python
name = "Bob"
age = 30
message = f"My name is {name} and I am {age} years old."
print(message) # Outputs: My name is Bob and I am 30 years old.
```

PE
**String Slicing:**
Slicing is like cutting a cake into pieces. You can extract specific portions of a string using
slicing.

```python
text = "Python Programming"
substring = text[7:16] # Gets "Programming"

RN
print(substring)
```

**Conclusion:**
String manipulation is all about working with text. By understanding how to access
characters, concatenate, format, and use string methods, you can perform a wide range of
text-related tasks. String manipulation is an essential skill for working with textual data in
your Python programs.
TE
IN

**Chapter 13: Nested Lists and Dictionaries**


**Introduction to Nested Lists and Dictionaries:**
Imagine you have a drawer with compartments, and in each compartment, there's another
drawer with more compartments. Nested lists and dictionaries in Python are similar. They
allow you to store structured data within other structured data, creating layers of information.

**Nested Lists:**
A nested list is a list that contains other lists as its elements. Each inner list can have its own
elements, creating a hierarchical structure.
```python
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
```

**Accessing Elements in Nested Lists:**


You use multiple indices to access elements in nested lists. Think of it like opening drawers
within drawers.

PE
```python
element = matrix[1][2] # Accessing the element 6
```

**Nested Dictionaries:**
A nested dictionary is a dictionary where the values can be dictionaries themselves. It's like
having dictionaries within dictionaries.

RN
```python
person = {
"name": "Alice",
"age": 30,
"address": {
"street": "123 Main St",
"city": "New York"
}
}
TE
```

**Accessing Elements in Nested Dictionaries:**


To access values in nested dictionaries, you chain keys together using multiple indices. It's
like finding a specific room in a house within a neighborhood.

```python
city = person["address"]["city"] # Accessing the city "New York"
```
IN

**Using Nested Structures:**


Nested structures are useful for representing more complex data relationships. For example,
you can use a nested list to represent a grid, and a nested dictionary to model a more
detailed person's profile.

**Modifying and Adding Elements:**


You can modify and add elements to nested lists and dictionaries just like regular lists and
dictionaries.

```python
matrix[0][1] = 10 # Modifying element in the nested list
person["address"]["country"] = "USA" # Adding a new key-value pair to the nested dictionary
```

**Conclusion:**
Nested lists and dictionaries allow you to organize and represent complex data in a
structured way. They let you create layers of information, like compartments within
compartments. By understanding how to access, modify, and work with nested structures,
you can build more sophisticated and detailed data structures in your Python programs.

PE
**Chapter 14: Decorators**

RN
**Introduction to Decorators:**
Imagine you're throwing a party, and you want to make sure everyone follows certain rules
before they enter. Decorators in Python work similarly – they're functions that modify or
enhance other functions. They allow you to add extra behavior to functions without changing
their code.

**Understanding Functions:**
Before diving into decorators, let's remember functions. Functions are like recipes. You give
them inputs (ingredients), they process them, and give you an output (dish).
TE
**Defining Functions:**
```python
def greet(name):
return f"Hello, {name}!"
```

**Introducing Decorators:**
Decorators are functions that take another function as input, modify it, and return the
IN

modified function.

**Creating a Decorator:**
Imagine you're checking party invitations. A decorator is like the bouncer at the entrance
who ensures everyone follows the rules.

```python
def bouncer(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
if "Alice" in result:
return "Sorry, Alice. You're not allowed!"
return result
return wrapper
```

**Applying a Decorator:**
You use the `@` symbol to apply a decorator to a function. It's like telling the bouncer to
check invitations before allowing someone into the party.

```python

PE
@bouncer
def invite(name):
return f"Welcome, {name}!"
```

**Using the Decorated Function:**


Now, when you call the `invite()` function, it goes through the decorator first, just like guests
go through the bouncer before entering the party.

RN
```python
print(invite("Bob")) # Outputs: Welcome, Bob!
print(invite("Alice")) # Outputs: Sorry, Alice. You're not allowed!
```

**Decorators for Various Purposes:**


Decorators can be used for logging, authorization, performance measurement, and more.
Just like you might have different rules for different types of parties.
TE
**Conclusion:**
Decorators are like party planners – they add special touches to functions without changing
their core. By understanding and using decorators, you can enhance your code's behavior,
making it more flexible and powerful. They're an advanced concept, but once you grasp
them, they can simplify complex tasks and make your code more elegant.
IN

**Chapter 15: PEP 8 Style Guide**


**Introduction to PEP 8:**
Imagine you're writing a book. To make it easy to read, you follow certain rules like using
consistent font sizes and spacing. Similarly, in programming, there's a style guide called PEP
8 that helps make your code more readable and consistent. PEP stands for "Python
Enhancement Proposal," and PEP 8 is the style guide for writing clean and understandable
Python code.

**Why Follow PEP 8:**


When you write code, you're not just communicating with the computer, but also with other
programmers (including future you). Following a consistent style guide like PEP 8 ensures

PE
that everyone can understand and work with your code easily.

**Key PEP 8 Guidelines:**

1. **Indentation:** Use 4 spaces for indentation, not tabs. This makes your code consistent
and helps with readability.

2. **Maximum Line Length:** Keep lines under 79 characters. If a line is too long, you can

RN
break it into multiple lines.

3. **Import Formatting:** Imports should be on separate lines, and each import should be on
its own line.

4. **Whitespace in Expressions and Statements:** Use whitespace around operators, after


commas, and before colons.

5. **Comments:** Write meaningful comments that explain your code. Use comments
sparingly and avoid unnecessary comments.
TE
6. **Function and Variable Naming:** Use descriptive names for functions, variables, and
classes. Use lowercase with underscores for variable names (`my_variable`), and use
CamelCase for class names (`MyClass`).

7. **Whitespace in Function Calls:** Put one space after commas in function calls and
definitions.

8. **Blank Lines:** Use blank lines to separate logical sections of your code for better
IN

readability.

9. **Avoid Trailing Whitespace:** Remove any extra whitespace at the end of lines.

10. **Imports Order:** First import standard library modules, then third-party modules, and
finally your own modules. Each section should be separated by a blank line.

**Example:**

```python
def calculate_area(length, width):
return length * width

if age > 18:


print("You're an adult")

import math
import os
from my_module import my_function

PE
class MyClassName:
def __init__(self):
pass

# Use consistent naming and indentation throughout your code.


```

**Conclusion:**

RN
PEP 8 is like a guidebook for writing clean and well-organized Python code. By following its
guidelines, you can make your code more readable and understandable to yourself and
others. Consistency in coding style helps create a more enjoyable and collaborative coding
experience, making your codebase more maintainable in the long run.
TE
IN

You might also like