The Walrus Operator
Introduced in Python 3.8, the "walrus operator"
It solves the common problem where you need to compute a value, check it, and then use it again.
---
#### The Old Way: Repetitive Code
Consider a loop that repeatedly prompts a user for input and stops when the user enters "quit".
Notice how
---
#### The Pythonic Way: Using the Walrus Operator
The walrus operator lets you capture the value and test it in a single, elegant line.
Here,
• Calls
• The entire expression evaluates to that same value, which is then compared to
This eliminates redundant code, making your logic cleaner and more direct.
#Python #PythonTips #PythonTricks #WalrusOperator #Python3 #CleanCode #Programming #Developer #CodingTips
━━━━━━━━━━━━━━━
By: @DataScienceQ ✨
:= (Assignment Expressions)Introduced in Python 3.8, the "walrus operator"
:= allows you to assign a value to a variable as part of a larger expression. It's a powerful tool for writing more concise and readable code, especially in while loops and comprehensions.It solves the common problem where you need to compute a value, check it, and then use it again.
---
#### The Old Way: Repetitive Code
Consider a loop that repeatedly prompts a user for input and stops when the user enters "quit".
# We have to get the input once before the loop,
# and then again inside the loop.
command = input("Enter command: ")
while command != "quit":
print(f"Executing: {command}")
command = input("Enter command: ")
print("Exiting program.")
Notice how
input("Enter command: ") is written twice.---
#### The Pythonic Way: Using the Walrus Operator
:=The walrus operator lets you capture the value and test it in a single, elegant line.
while (command := input("Enter command: ")) != "quit":
print(f"Executing: {command}")
print("Exiting program.")Here,
(command := input(...)) does two things:• Calls
input() and assigns its value to the command variable.• The entire expression evaluates to that same value, which is then compared to
"quit".This eliminates redundant code, making your logic cleaner and more direct.
#Python #PythonTips #PythonTricks #WalrusOperator #Python3 #CleanCode #Programming #Developer #CodingTips
━━━━━━━━━━━━━━━
By: @DataScienceQ ✨
❤2
How to view an object's methods?
Answer:
tags: #interview
Please open Telegram to view this post
VIEW IN TELEGRAM
❤2🔥1
❔ Interview Question
What is the GIL (Global Interpreter Lock) in Python, and how does it impact the execution of multi-threaded programs?
Answer: The Global Interpreter Lock (GIL) is a mutex (or a lock) that allows only one thread to hold the control of the Python interpreter at any one time. This means that in a CPython process, only one thread can be executing Python bytecode at any given moment, even on a multi-core processor.
This has a significant impact on performance:
• For CPU-bound tasks: Multi-threaded Python programs see no performance gain from multiple CPU cores. If you have a task that performs heavy calculations (e.g., image processing, complex math), creating multiple threads will not make it run faster. The threads will execute sequentially, not in parallel, because they have to take turns acquiring the GIL.
• For I/O-bound tasks: The GIL is less of a problem. When a thread is waiting for Input/Output (I/O) operations (like waiting for a network response, reading from a file, or querying a database), it releases the GIL. This allows another thread to run. Therefore, the
How to achieve true parallelism?
To bypass the GIL and leverage multiple CPU cores for CPU-bound tasks, you must use the
tags: #Python #Interview #CodingInterview #GIL #Concurrency #Threading #Multiprocessing #SoftwareEngineering
━━━━━━━━━━━━━━━
By: @DataScienceQ ✨
What is the GIL (Global Interpreter Lock) in Python, and how does it impact the execution of multi-threaded programs?
Answer: The Global Interpreter Lock (GIL) is a mutex (or a lock) that allows only one thread to hold the control of the Python interpreter at any one time. This means that in a CPython process, only one thread can be executing Python bytecode at any given moment, even on a multi-core processor.
This has a significant impact on performance:
• For CPU-bound tasks: Multi-threaded Python programs see no performance gain from multiple CPU cores. If you have a task that performs heavy calculations (e.g., image processing, complex math), creating multiple threads will not make it run faster. The threads will execute sequentially, not in parallel, because they have to take turns acquiring the GIL.
• For I/O-bound tasks: The GIL is less of a problem. When a thread is waiting for Input/Output (I/O) operations (like waiting for a network response, reading from a file, or querying a database), it releases the GIL. This allows another thread to run. Therefore, the
threading module is still highly effective for tasks that spend most of their time waiting, as it allows for concurrency.How to achieve true parallelism?
To bypass the GIL and leverage multiple CPU cores for CPU-bound tasks, you must use the
multiprocessing module. It creates separate processes, each with its own Python interpreter and memory space, so the GIL of one process does not affect the others.tags: #Python #Interview #CodingInterview #GIL #Concurrency #Threading #Multiprocessing #SoftwareEngineering
━━━━━━━━━━━━━━━
By: @DataScienceQ ✨
❤1
What objects can be put into a set?
Answer:
Objects like list, dict, set, and other mutable structures cannot be put in: they do not have a hash function (hash) and will cause a TypeError.
ta
Please open Telegram to view this post
VIEW IN TELEGRAM
❤1
Python tip:
Use the Path class from the pathlib module to work with file paths cross-platform.
👉 @DataScienceQ
Use the Path class from the pathlib module to work with file paths cross-platform.
from pathlib import Path
p = Path('/usr/local/bin')
Please open Telegram to view this post
VIEW IN TELEGRAM
❤3
🏆 NumPy Python Tips
📢 Boost your Python skills with NumPy! Learn quick tips for efficient array creation and manipulation to level up your data handling.
⚡ Tap to unlock the complete answer and gain instant insight.
━━━━━━━━━━━━━━━
By: @DataScienceQ ✨
📢 Boost your Python skills with NumPy! Learn quick tips for efficient array creation and manipulation to level up your data handling.
⚡ Tap to unlock the complete answer and gain instant insight.
━━━━━━━━━━━━━━━
By: @DataScienceQ ✨
Telegraph
NumPy Python Tips
Python tip:Create an uninitialized array (contents are arbitrary) for performance.import numpy as npempty_array = np.empty((2, 3))
❤1
Tired of missing perfect GOLD entries?
Last week alone: 1,740 pips profit, 10/12 trades won—all shared live in our channel.
Ready to catch the next move? Stay ahead with premium signals & real-time updates—don’t just watch, start profiting!
Join GOLD PIPS SIGNALS before the next trade drops!
#ad InsideAds
Last week alone: 1,740 pips profit, 10/12 trades won—all shared live in our channel.
Ready to catch the next move? Stay ahead with premium signals & real-time updates—don’t just watch, start profiting!
Join GOLD PIPS SIGNALS before the next trade drops!
#ad InsideAds
❤1
🌍 Remote Work — India Only 🇮🇳
💰 Earn $800–$2000/month
📆 Weekly payments — card or crypto
🕒 Work 3–4 hours/day
🏠 Fully remote — no office, no experience needed
🎓 Training provided
👉 Indian citizens aged 25+ only
📩 Message our HR manager to apply today!
#ad InsideAds
💰 Earn $800–$2000/month
📆 Weekly payments — card or crypto
🕒 Work 3–4 hours/day
🏠 Fully remote — no office, no experience needed
🎓 Training provided
👉 Indian citizens aged 25+ only
📩 Message our HR manager to apply today!
#ad InsideAds
❤2
What can be a key in a dictionary?
Answer:
tags: #interview
Please open Telegram to view this post
VIEW IN TELEGRAM
❤3
🏆 Master Vue.js for Modern UIs
📢 Master Vue.js, the intuitive JavaScript framework, and confidently build modern, reactive user interfaces. Your journey to dynamic web apps starts here!
⚡ Tap to unlock the complete answer and gain instant insight.
━━━━━━━━━━━━━━━
By: @DataScienceQ ✨
📢 Master Vue.js, the intuitive JavaScript framework, and confidently build modern, reactive user interfaces. Your journey to dynamic web apps starts here!
⚡ Tap to unlock the complete answer and gain instant insight.
━━━━━━━━━━━━━━━
By: @DataScienceQ ✨
Telegraph
Master Vue.js for Modern UIs
📌 Learn Vue.js – JavaScript Framework Course
🏆 Python MCP Server: Create & Learn
📢 Unlock Minecraft's secrets! Build your own custom Minecraft Protocol (MCP) server with Python for ultimate game customization and deep dives into mechanics.
⚡ Tap to unlock the complete answer and gain instant insight.
━━━━━━━━━━━━━━━
By: @DataScienceQ ✨
📢 Unlock Minecraft's secrets! Build your own custom Minecraft Protocol (MCP) server with Python for ultimate game customization and deep dives into mechanics.
⚡ Tap to unlock the complete answer and gain instant insight.
━━━━━━━━━━━━━━━
By: @DataScienceQ ✨
Telegraph
Python MCP Server: Create & Learn
🐍 Building Your Own Minecraft Protocol (MCP) Server with Python
❤1
When an attribute is defined both in the instance and in the class, Python always takes the value from the instance.
The class attribute is used only if it is not present in the instance.
👉 @DataScienceQ
The class attribute is used only if it is not present in the instance.
class Warehouse:
purpose = "storage"
region = "west"
w1 = Warehouse()
print(w1.purpose, w1.region) # storage west
w2 = Warehouse()
w2.region = "east"
print(w2.purpose, w2.region) # storage east
Please open Telegram to view this post
VIEW IN TELEGRAM
What is a deep copy?
Answer:
In Python, this is done using copy.deepcopy(), which creates a fully independent data structure, including nested lists, dictionaries, and other objects.
tags: #interview
Please open Telegram to view this post
VIEW IN TELEGRAM
👍4❤1
Tip for clean tests in Python:
Structure your tests with the Arrange-Act-Assert pattern to improve readability and maintainability.
• Arrange: Set up the test. Initialize objects, prepare data, and configure any mocks or stubs.
• Act: Execute the code being tested. Call the specific function or method.
• Assert: Check the outcome. Verify that the result of the action is what you expected.
#Python #Testing #CleanCode #SoftwareEngineering #Pytest #DeveloperTips #AAA
━━━━━━━━━━━━━━━
By: @DataScienceQ ✨
Structure your tests with the Arrange-Act-Assert pattern to improve readability and maintainability.
• Arrange: Set up the test. Initialize objects, prepare data, and configure any mocks or stubs.
• Act: Execute the code being tested. Call the specific function or method.
• Assert: Check the outcome. Verify that the result of the action is what you expected.
import pytest
from dataclasses import dataclass, field
# Code to be tested
@dataclass
class Product:
name: str
price: float
@dataclass
class ShoppingCart:
items: list[Product] = field(default_factory=list)
def add_item(self, product: Product):
if product.price < 0:
raise ValueError("Product price cannot be negative.")
self.items.append(product)
def get_total_price(self) -> float:
return sum(item.price for item in self.items)
# Tests using the Arrange-Act-Assert pattern
def test_get_total_price_for_multiple_items():
# Arrange
product1 = Product(name="Mouse", price=25.50)
product2 = Product(name="Keyboard", price=75.50)
cart = ShoppingCart()
cart.add_item(product1)
cart.add_item(product2)
# Act
total_price = cart.get_total_price()
# Assert
assert total_price == 101.00
def test_get_total_price_for_empty_cart():
# Arrange
cart = ShoppingCart()
# Act
total_price = cart.get_total_price()
# Assert
assert total_price == 0.0
def test_add_item_with_negative_price_raises_value_error():
# Arrange
cart = ShoppingCart()
product_with_negative_price = Product(name="Invalid Item", price=-50.0)
# Act & Assert
with pytest.raises(ValueError, match="Product price cannot be negative."):
cart.add_item(product_with_negative_price)
#Python #Testing #CleanCode #SoftwareEngineering #Pytest #DeveloperTips #AAA
━━━━━━━━━━━━━━━
By: @DataScienceQ ✨
Why does
list.sort() return None instead of the sorted list?Answer:
If a new sorted list is needed, the built-in sorted() function is used, which returns the result without changing the original.
tags: #interview
Please open Telegram to view this post
VIEW IN TELEGRAM
Are there generics in Python like in Java or C++?
Answer:
tags: #interview
Please open Telegram to view this post
VIEW IN TELEGRAM
300 Real Time SQL Interview.pdf
4.5 MB
300 Real Time SQL Interview practical Questions Asked at multiple companies
••••••••••••••••••••••••••••••••••••••••••••••••••••••
Anyone who's preparing for an interview just reading theoretical concept will not help definitely you need to have practical hands on in #sql so create table with some data and try this queries running by your self so can help you to understand the logic of similar kind of queries
If you're preparing for an interview this doc will help a lot in the perpetration If you're experienced also freshers can also get hands on by practicing these queries and get confidence.
••••••••••••••••••••••••••••••••••••••••••••••••••••••
Anyone who's preparing for an interview just reading theoretical concept will not help definitely you need to have practical hands on in #sql so create table with some data and try this queries running by your self so can help you to understand the logic of similar kind of queries
If you're preparing for an interview this doc will help a lot in the perpetration If you're experienced also freshers can also get hands on by practicing these queries and get confidence.
https://t.iss.one/DataScienceQ
❤3
Forwarded from Python | Machine Learning | Coding | R
🚀 THE 7-DAY PROFIT CHALLENGE! 🚀
Can you turn $100 into $5,000 in just 7 days?
Lisa can. And she’s challenging YOU to do the same. 👇
https://t.iss.one/+AOPQVJRWlJc5ZGRi
https://t.iss.one/+AOPQVJRWlJc5ZGRi
https://t.iss.one/+AOPQVJRWlJc5ZGRi
Can you turn $100 into $5,000 in just 7 days?
Lisa can. And she’s challenging YOU to do the same. 👇
https://t.iss.one/+AOPQVJRWlJc5ZGRi
https://t.iss.one/+AOPQVJRWlJc5ZGRi
https://t.iss.one/+AOPQVJRWlJc5ZGRi
❤2
What do you know about NoSQL databases?
Answer:
These databases scale well horizontally: data is distributed across cluster nodes, which helps handle high loads and large volumes. Different storage models are supported — key-value, document, columnar, and graph. This allows choosing the appropriate structure for a specific task.
Common systems include MongoDB (documents), Cassandra (columns), Redis (key-value), and Neo4j (graphs). They are used where scalability, speed, and data flexibility are important.
tags: #interview
Please open Telegram to view this post
VIEW IN TELEGRAM
Telegram
PyData Careers
Python Data Science jobs, interview tips, and career insights for aspiring professionals.