
- Main
- Catalog
- Computer science
- Python Learning
Channel statistics
lambda keyword. They can take any number of arguments but can only have one expression.
🔹 1. What is a Lambda Function?
A compact way to write simple functions without def. They are essentially a shortcut for defining simple, inline functions.
Syntax:
lambda arguments: expression
Example:python
add_ten = lambda x: x + 10
print(add_ten(5))
{}
Output: 15
🔹 2. Why Use Lambda?
• Conciseness: Shorter syntax for simple operations.
• Anonymity: No need to name a function that will only be used once.
• Readability: Can make code cleaner when used appropriately in specific contexts.
🔹 3. Lambda with Multiple Arguments
Lambdas can take multiple arguments, just like regular functions.
Example:
multiply = lambda a, b: a × b
print(multiply(4, 7))
{}
Output: 28
🔹 4. Common Use Case 1: filter()
The filter() function constructs an iterator from elements of an iterable for which a function returns True. Lambdas are often used as this function.
Example:
numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)
{}
Output: [2, 4, 6]
🔹 5. Common Use Case 2: map()
The map() function applies a given function to each item of an iterable and returns an iterator of the results.
Example:
numbers = [1, 2, 3]
squared_numbers = list(map(lambda x: x × x, numbers))
print(squared_numbers)
{}
Output: [1, 4, 9]
🔹 6. Common Use Case 3: sorted() (Custom Sort Key)
Lambdas are frequently used with sorted() as the key argument to define custom sorting logic.
Example:
students = [('Alice', 25), ('Bob', 20), ('Charlie', 30)]
# Sort by age (the second element of each tuple)
sorted_students = sorted(students, key=lambda student: student[1])
print(sorted_students)
{}
Output: [('Bob', 20), ('Alice', 25), ('Charlie', 30)]
🎯 Today's Goal
✔️ Understand what lambda functions are
✔️ Write short, single-expression functions
✔️ Use lambdas effectively with filter(), map(), and sorted()open())
The open() function is used to open a file. It returns a file object.
Syntax:
file_object = open("filename.txt", "mode")
{}
Common modes:
• "r": Read (default) - file must exist.
• "w": Write - creates a new file or overwrites an existing one.
• "a": Append - creates a new file or adds to the end of an existing one.
• "x": Exclusive creation - creates a new file, fails if it exists.
🔹 2. Reading from Files
Once opened in read mode, you can read content:
• .read(): Reads the entire file content as a single string.
• .readline(): Reads one line at a time.
• .readlines(): Reads all lines into a list of strings.
Example:
# Assuming 'data.txt' contains "Line 1\nLine 2\n"
file = open("data.txt", "r")
content = file.read()
print(content)
file.close() # Always close the file!
{}
Output:
Line 1
Line 2
🔹 3. Writing to Files
Once opened in write ("w") or append ("a") mode, you can write content:
• .write(string): Writes a string to the file. Remember to add \n for new lines.
Example:
file = open("output.txt", "w")
file.write("Hello from Python!\n")
file.write("This is a new line.")
file.close()
{}
(Creates/overwrites output.txt with the text.)
🔹 4. The with Statement (Best Practice!)
The with statement ensures files are automatically closed even if errors occur. This is the recommended way.
Syntax:
with open("filename.txt", "mode") as file_object:
# perform file operations here
# File is automatically closed after this block
Example:python
with open("names.txt", "w") as f:
f.write("Alice\nBob\n")
with open("names.txt", "r") as f:
for line in f:
print(line.strip()) # .strip() removes newline characters
{}
Output:
Alice
Bob
🔹 5. File Modes (Binary vs. Text)
• Text mode (default): "r", "w", "a" - handles text encoding/decoding.
• Binary mode: "rb", "wb", "ab" - handles raw bytes, useful for images, executables, etc.
Example (Binary Write):
with open("data.bin", "wb") as f:
f.write(b'\x01\x02\x03') # Writing bytes
{}
🎯 Today's Goal
✔️ Understand how to open files in different modes
✔️ Read and write data to files
✔️ Master the with statement for safe file handling.py extension) containing Python code (functions, classes, variables).
Example:
If you have my_math.py:
# my_math.py
def add(a, b):
return a + b
{}
🔹 2. Importing Modules
You use the import statement to bring functionality from one module into another.
Syntax:
import module_name
from module_name import specific_item
from module_name import * # Avoid this in large projects
import module_name as alias
Example:python
import my_math
print(my_math.add(5, 3)) # Access function using module_name.function
from my_math import add
print(add(10, 2)) # Access function directly
import math as m # Using an alias for built-in 'math' module
print(m.sqrt(16))
{}
Output:
8
12
4.0
🔹 3. What are Packages?
A package is a way to organize related modules into a directory hierarchy. A directory becomes a Python package if it contains an __init__.py file (even if empty).
Example:
my_project/
├── main.py
└── my_package/
├── __init__.py
├── graphics.py
└── sound.py{}
🔹 4. Importing from Packages
You import modules or specific items from modules within a package using dot notation.
Example (assuming my_package above):
# In main.py
from my_package import graphics
# Now you can use functions/classes from graphics.py like: graphics.draw_circle()
from my_package.sound import play_effect
# Now you can use play_effect() directly
{}
🔹 5. Benefits of Modules & Packages
• Reusability: Write code once, use everywhere.
• Organization: Keeps related code together.
• Readability: Easier to understand structured code.
• Namespace management: Prevents variable/function name clashes.
🎯 Today's Goal (What you should do)
✔️ Understand what modules and packages are
✔️ Learn how to import functionality
✔️ Appreciate the benefits of code organizationReviews channel
9 total reviews
- Added: Newest first
- Added: Oldest first
- Rating: High to low
- Rating: Low to high
Catalog of Telegram Channels for Native Placements
Python Learning is a Telegram channel in the category «Интернет технологии», offering effective formats for placing advertising posts on TG. The channel has 5.9K subscribers and provides quality content. The advertising posts on the channel help brands attract audience attention and increase reach. The channel's rating is 28.0, with 9 reviews and an average score of 5.0.
You can launch an advertising campaign through the Telega.in service, choosing a convenient format for placement. The Platform provides transparent cooperation conditions and offers detailed analytics. The placement cost is 8.4 ₽, and with 22 completed requests, the channel has established itself as a reliable partner for advertising on Telegram. Place integrations today and attract new clients!
You will be able to add channels from the catalog to the cart again.
Комментарий