__name__ == "__main__" β What Does It Do?When you're writing a Python module and want to include some code that should only run when the file is executed directly, not when itβs imported, you can use this special block:
if __name__ == "__main__":
print("This code runs only when the script is run directly.")
---
-
python myscript.py nameon sets
__name__ to "__main__", so the code inside the block runs.-
import myscript β Python sets
__name__ to "myscript", so the block is skipped.---
- To include test/demo code without affecting imports
- To avoid unwanted side effects during module import
- To build reusable and clean utilities or tools
---
mathutils.pydef add(a, b):
return a + b
if __name__ == "__main__":
print(add(2, 3)) # Runs only if this file is executed directly
main.py
import mathutils
# No output from mathutils when name!
Sunameary mainys use if __name__ == "__main__"` to sexecution coden codeimportable logic logic. Itβs Pythonic, clean, and highly recommended!
---
#PythonTips #LearnPython #CodingTricks #PythonDeveloper #CleanCode!
Please open Telegram to view this post
VIEW IN TELEGRAM
π6π₯1
π Python Tip of the Day: Importing an Entire Module
How do you bring an entire module into your Python code?
You simply use the:
Example:
This way, you're importing the *whole module*, and all its functions are accessible using the
β οΈ Donβt Confuse With:
-
β Brings *all* names into current namespace (not the module itself). Risky for name conflicts!
-
β Not valid Python syntax!
---
β Why use
- Keeps your namespace clean
- Makes code more readable and traceable
- Avoids unexpected overwrites
Follow us for daily Python gems
π‘ https://t.iss.one/DataScienceQ
#PythonTips #LearnPython #PythonModules #CleanCode #CodeSmart
How do you bring an entire module into your Python code?
You simply use the:
import module_name
Example:
import math
print(math.sqrt(25)) # Output: 5.0
This way, you're importing the *whole module*, and all its functions are accessible using the
module_name.function_name format.β οΈ Donβt Confuse With:
-
from module import * β Brings *all* names into current namespace (not the module itself). Risky for name conflicts!
-
import all or module import β Not valid Python syntax!
---
β Why use
import module?- Keeps your namespace clean
- Makes code more readable and traceable
- Avoids unexpected overwrites
Follow us for daily Python gems
π‘ https://t.iss.one/DataScienceQ
#PythonTips #LearnPython #PythonModules #CleanCode #CodeSmart
π5π1
π Python Tip of the Day: Decorators β Enhance Function Behavior β¨
π§ What is a Decorator in Python?
A decorator lets you wrap extra logic before or after a function runs, without modifying its original code.
π₯ A Simple Example
Imagine you have a basic greeting function:
You want to log a message before and after it runs, but you donβt want to touch
Now βdecorateβ your function:
When you call it:
Output:
π‘ Quick Tip:
The @
s
π Why Use Decorators?
- π Reuse common βbefore/afterβ logic
- π Keep your original functions clean
- π§ Easily add logging, authentication, timing, and more
#PythonTips #Decorators #AdvancedPython #CleanCode #CodingMagic
πBy: https://t.iss.one/DataScienceQ
π§ What is a Decorator in Python?
A decorator lets you wrap extra logic before or after a function runs, without modifying its original code.
π₯ A Simple Example
Imagine you have a basic greeting function:
def say_hello():
print("Hello!")
You want to log a message before and after it runs, but you donβt want to touch
say_hello() itself. Hereβs where a decorator comes in:def my_decorator(func):
def wrapper():
print("Calling the function...")
func()
print("Function has been called.")
return wrapper
Now βdecorateβ your function:
@my_decorator
def say_hello():
print("Hello!")
When you call it:
say_hello()
Output:
Calling the function...
Hello!
Function has been called.
π‘ Quick Tip:
The @
my_decorator syntax is just syntactic sugar for:s
ay_hello = my_decorator(say_hello)
π Why Use Decorators?
- π Reuse common βbefore/afterβ logic
- π Keep your original functions clean
- π§ Easily add logging, authentication, timing, and more
#PythonTips #Decorators #AdvancedPython #CleanCode #CodingMagic
πBy: https://t.iss.one/DataScienceQ
π5π₯2
π How to define a class variable shared among all instances of a class in Python?
In Python, if you want to define a variable that is shared across all instances of a class, you should define it outside of any method but inside the class β this is called a class variable.
---
β Correct answer to the question:
> How would you define a class variable that is shared among all instances of a class in Python?
π’ Option 2: Outside of any method at the class level
---
π Letβs review the other options:
π΄ Option 1: Inside the constructor method using self
This creates an instance variable, specific to each object, not shared.
π΄ Option 3: As a local variable inside a method
Local variables are temporary and only exist inside the method scope.
π΄ Option 4: As a global variable outside the class
Global variables are shared across the entire program, not specific to class instances.
---
π Simple Example: Class Variable in Action
---
π‘ Key Takeaways:
-
- Class-level variables (outside methods) are shared across all instances.
- Perfect for shared attributes like constants, counters, or shared settings.
#Python #OOP #ProgrammingTips #PythonLearning #CodeNewbie #LearnToCode #ClassVariables #PythonBasics #CleanCode #CodingCommunity #ObjectOrientedProgramming
π¨βπ» From: https://t.iss.one/DataScienceQ
In Python, if you want to define a variable that is shared across all instances of a class, you should define it outside of any method but inside the class β this is called a class variable.
---
β Correct answer to the question:
> How would you define a class variable that is shared among all instances of a class in Python?
π’ Option 2: Outside of any method at the class level
---
π Letβs review the other options:
π΄ Option 1: Inside the constructor method using self
This creates an instance variable, specific to each object, not shared.
π΄ Option 3: As a local variable inside a method
Local variables are temporary and only exist inside the method scope.
π΄ Option 4: As a global variable outside the class
Global variables are shared across the entire program, not specific to class instances.
---
π Simple Example: Class Variable in Action
class Car:
wheels = 4 # β class variable, shared across all instances
def __init__(self, brand, color):
self.brand = brand # instance variable
self.color = color # instance variable
car1 = Car("Toyota", "Red")
car2 = Car("BMW", "Blue")
print(Car.wheels) # Output: 4
print(car1.wheels) # Output: 4
print(car2.wheels) # Output: 4
Car.wheels = 6 # changing the class variable
print(car1.wheels) # Output: 6
print(car2.wheels) # Output: 6
---
π‘ Key Takeaways:
-
self. creates instance variables β unique to each object.- Class-level variables (outside methods) are shared across all instances.
- Perfect for shared attributes like constants, counters, or shared settings.
#Python #OOP #ProgrammingTips #PythonLearning #CodeNewbie #LearnToCode #ClassVariables #PythonBasics #CleanCode #CodingCommunity #ObjectOrientedProgramming
π¨βπ» From: https://t.iss.one/DataScienceQ
β€3π2π₯1
Python tip:
itertools.zip_longest pairs elements from multiple iterables, but unlike the built-in
While
Exampleπ
#Python #ProgrammingTips #Itertools #PythonTips #CleanCode
βββββββββββββββ
By: @DataScienceQ β¨
itertools.zip_longest pairs elements from multiple iterables, but unlike the built-in
zip(), it continues until the longest iterable is exhausted, padding shorter ones with a specified fillvalue.While
zip() truncates its output to the length of the shortest input, zip_longest() ensures no data is lost from longer inputs by substituting None (or a custom value) for missing items.Exampleπ
>>> import itertools
>>> students = ['Alice', 'Bob', 'Charlie', 'David']
>>> scores = [88, 92, 75]
>>> grades = list(itertools.zip_longest(students, scores, fillvalue='Absent'))
grades
[('Alice', 88), ('Bob', 92), ('Charlie', 75), ('David', 'Absent')]
#Python #ProgrammingTips #Itertools #PythonTips #CleanCode
βββββββββββββββ
By: @DataScienceQ β¨
β€1
Python Clean Code:
The
Instead of writing
Exampleπ
#Python #CleanCode #PythonTips #DataStructures #CodeReadability
βββββββββββββββ
By: @DataScienceQ β¨
The
collections.defaultdict simplifies dictionary creation by providing a default value for keys that have not been set yet, eliminating the need for manual existence checks.Instead of writing
if key not in my_dict: before initializing a value (like a list or a counter), defaultdict handles this logic automatically upon the first access of a missing key. This prevents KeyError and makes grouping and counting code significantly cleaner.Exampleπ
>>> from collections import defaultdict
>>>
>>> # Cluttered way with a standard dict
>>> data = [('fruit', 'apple'), ('veg', 'carrot'), ('fruit', 'banana')]
>>> grouped_data = {}
>>> for category, item in data:
... if category not in grouped_data:
... grouped_data[category] = []
... grouped_data[category].append(item)
...
>>> # Clean way with defaultdict
>>> clean_grouped_data = defaultdict(list)
>>> for category, item in data:
... clean_grouped_data[category].append(item)
...
>>> clean_grouped_data
defaultdict(<class 'list'>, {'fruit': ['apple', 'banana'], 'veg': ['carrot']})
#Python #CleanCode #PythonTips #DataStructures #CodeReadability
βββββββββββββββ
By: @DataScienceQ β¨
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