Learn Python Coding
40.5K subscribers
705 photos
36 videos
24 files
506 links
Learn Python through simple, practical examples and real coding ideas. Clear explanations, useful snippets, and hands-on learning for anyone starting or improving their programming skills.

Admin: @HusseinSheikho || @Hussein_Sheikho
Download Telegram
Forwarded from Udemy Free
🎓 New Free Course Alert!

Data Structures & Algorithms (Python): Practice Exams

Ace technical coding interviews with 200 questions on Big O, Graphs, Hash Maps, and Dynamic Programming.…

📁 Category: Development / Software Engineering
🎯 Level: Intermediate Level
🗣 Language: English
👨‍🎓 Enrolled: 317 students
⭐ Rating: 0/5.0
💵 Price: $49.99 ➜ FREE (100% OFF)
🎟 Coupon: BC7C61AF20F4AE188D90

⚡ Your free link unlocks automatically in a few seconds — no ad required.

💎 By: https://xn--r1a.website/Udemy26
#Programming #Coding #Development #Tech #Python #DataScience
❤2
Creating Nested Dictionary Values using `setdefault()` 🔥

When grouping data, it's often necessary to check if a key exists, create a container for it, and then add a value.

For example, distributing users by role. Without special methods, this usually involves a separate key check.

users = [
("admin", "alex"),
("user", "max"),
("admin", "kate"),
]

groups = {}

for role, name in users:
if role not in groups:
groups[role] = []

groups[role].append(name)


The setdefault() method allows you to perform this operation directly when accessing the dictionary. If the key exists, it returns its current value. If the key is missing, the provided value is written to the dictionary and then returned:

groups = {}

for role, name in users:
groups.setdefault(
role,
[],
).append(name)


The result is the same structure without a separate key existence check:

print(groups)

# {
# 'admin': ['alex', 'kate'],
# 'user': ['max']
# }


It's important to note that the expression of the second argument is evaluated every time setdefault() is called, even if the key already exists. Therefore, you should avoid creating expensive objects or performing functions with side effects there:

value = cache.setdefault(
key,
build_value(),
)


In this code, build_value() will be called before the method itself is executed. If the value creation should only happen when the key is missing, it's better to use an explicit check or a suitable data structure, such as defaultdict.

🔥 setdefault() is well-suited for compactly initializing simple mutable containers when grouping and aggregating data. However, it's important to remember that the provided value is evaluated regardless of whether the key exists.

#Python #Coding #Dicts #Programming #CodeTips #DevLife

✨ Join Best TG Channels https://xn--r1a.website/addlist/0f6vfFbEMdAwODBk

⭐️ Join Our WhatsApp Channel https://whatsapp.com/channel/0029VaC7Weq29753hpcggW2A
Please open Telegram to view this post
VIEW IN TELEGRAM
❤2
Here's a small fact about Python 🐍

The := operator is called the "walrus" because the symbols resemble the eyes and tusks of a walrus 🦭

It was introduced in Python 3.8 and allows you to assign a value to a variable and use it directly within the expression at the same time.

For example:

while (line := input("Say something: ")) != "quit":
print(f"You said: {line}")


Without it, you would have to retrieve the value separately using input(), and then check it.

Have you ever used the := operator in your code?

#Python #Programming #WalrusOperator #Coding #TechFacts #Python3

✨ Join Best TG Channels https://xn--r1a.website/addlist/0f6vfFbEMdAwODBk

⭐️ Join Our WhatsApp Channel https://whatsapp.com/channel/0029VaC7Weq29753hpcggW2A
❤4👍1
Do not violate the Single Responsibility Principle 🎯

A function should do one thing, and do it well.

This function does too much:

def calculate_final_total(
price: float,
quantity: int,
discount_rate: float,
tax_rate: float
) -> float:
# Calculate the subtotal
subtotal = price * quantity

# Apply the discount
discounted_amount = subtotal * (1 - discount_rate)

# Calculate the tax
final_total = discounted_amount * (1 + tax_rate)

return final_total


The problem here is that the calculation of the subtotal, discount, and tax are all combined into one function. Any change to one of these steps can affect the entire calculation.

It's better to break down the logic into smaller, more specialized functions:

def calculate_subtotal(price: float, quantity: int) -> float:
return price * quantity

def apply_discount(subtotal: float, discount: float) -> float:
return subtotal * (1 - discount)

def calculate_tax(amount: float, tax_rate: float) -> float:
return amount * (1 + tax_rate)


This is much better. ✅

Smaller functions with a single task are easier to test with unit tests because they have fewer dependencies and require less mocking.

Furthermore, isolated components are easier to reuse in different parts of the application or pipeline without bringing in unnecessary dependencies.

Therefore, keep your functions simple and focused.

One function – one responsibility. 📝

#Python #Coding #SoftwareDevelopment #CleanCode #Programming #BestPractices

✨ Join Best TG Channels https://xn--r1a.website/addlist/0f6vfFbEMdAwODBk

⭐️ Join Our WhatsApp Channel https://whatsapp.com/channel/0029VaC7Weq29753hpcggW2A
❤5
The tell() function in Python 🐍

The tell() function returns the current position of the file pointer within the data stream. It is most often used when working with files. 📂

The function does not accept any arguments and returns an integer – the position in bytes from the beginning of the stream. 🔢

with open("file.txt", "rb") as f:
print(f.tell())

#Python #Programming #Coding #FileHandling #DevTips #Tech

✨ Join Best TG Channels https://xn--r1a.website/addlist/0f6vfFbEMdAwODBk

⭐️ Join Our WhatsApp Channel https://whatsapp.com/channel/0029VaC7Weq29753hpcggW2A
❤3
📌 Marking Deprecated Code in Python: deprecated()

In large projects, old functions are not always immediately removed. They are often left for compatibility, but it's important to warn developers that they should no longer be used.

Previously,
warnings.warn()
was often used for this purpose:

import warnings

def old_api():
warnings.warn(
"Use new_api()",
DeprecationWarning
)

In Python 3.13, a
deprecated()
decorator has been introduced:

from warnings import deprecated

@deprecated("Use new_api()")
def old_api():
return "old"

Now, the information about deprecation is part of the API itself. It can be recognized not only during runtime, but also by editors and static analysis tools.

This also works for classes:

@deprecated("Use NewClient")
class OldClient:
pass

This is convenient for libraries, SDKs, and large projects where the API is gradually changing.

#Python #Python313 #Deprecated #Coding #Programming #SoftwareDevelopment

✨ Join Best TG Channels https://xn--r1a.website/addlist/0f6vfFbEMdAwODBk

⭐️ Join Our WhatsApp Channel https://whatsapp.com/channel/0029VaC7Weq29753hpcggW2A
❤2