Python | Algorithms | Data Structures | Cyber ​​Security | Networks
38.6K subscribers
777 photos
23 videos
21 files
711 links
This channel is for Programmers, Coders, Software Engineers.

1) Python
2) django
3) python frameworks
4) Data Structures
5) Algorithms
6) DSA

Admin: @Hussein_Sheikho

Ad & Earn money form your channel:
https://telega.io/?r=nikapsOH
Download Telegram
💡 Python Tips Part 1

A collection of essential Python tricks to make your code more efficient, readable, and "Pythonic." This part covers list comprehensions, f-strings, tuple unpacking, and using enumerate.

# Create a list of squares from 0 to 9
squares = [x**2 for x in range(10)]

print(squares)
# Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

List Comprehensions: A concise and often faster way to create lists. The syntax is [expression for item in iterable].

name = "Alex"
score = 95.5

# Using an f-string for easy formatting
message = f"Congratulations {name}, you scored {score:.1f}!"

print(message)
# Output: Congratulations Alex, you scored 95.5!

F-Strings: The modern, readable way to format strings. Simply prefix the string with f and place variables or expressions directly inside curly braces {}.

numbers = (1, 2, 3, 4, 5)

# Unpack the first, last, and middle elements
first, *middle, last = numbers

print(f"First: {first}") # 1
print(f"Middle: {middle}") # [2, 3, 4]
print(f"Last: {last}") # 5

Extended Unpacking: Use the asterisk * operator to capture multiple items from an iterable into a list during assignment. It's perfect for separating the "head" and "tail" from the rest.

items = ['keyboard', 'mouse', 'monitor']

for index, item in enumerate(items):
print(f"Item #{index}: {item}")

# Output:
# Item #0: keyboard
# Item #1: mouse
# Item #2: monitor

Using enumerate: The Pythonic way to get both the index and the value of an item when looping. It's much cleaner than using range(len(items)).

#Python #Programming #CodeTips #PythonTricks

━━━━━━━━━━━━━━━
By: @DataScience4
2
💡 Python Tips Part 2

More essential Python tricks to improve your code. This part covers dictionary comprehensions, the zip function, ternary operators, and using underscores for unused variables.

# Create a dictionary of numbers and their squares
squared_dict = {x: x**2 for x in range(1, 6)}

print(squared_dict)
# Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Dictionary Comprehensions: A concise way to create dictionaries, similar to list comprehensions. The syntax is {key_expr: value_expr for item in iterable}.

students = ["Alice", "Bob", "Charlie"]
scores = [88, 92, 79]

for student, score in zip(students, scores):
print(f"{student}: {score}")

# Output:
# Alice: 88
# Bob: 92
# Charlie: 79

Using zip: The zip function combines multiple iterables (like lists or tuples) into a single iterator of tuples. It's perfect for looping over related lists in parallel.

age = 20

# Assign a value based on a condition in one line
status = "Adult" if age >= 18 else "Minor"

print(status)
# Output: Adult

Ternary Operator: A shorthand for a simple if-else statement, useful for conditional assignments. The syntax is value_if_true if condition else value_if_false.

# Looping 3 times without needing the loop variable
for _ in range(3):
print("Hello, Python!")

# Unpacking, but only needing the last value
_, _, last_item = (10, 20, 30)
print(last_item) # 30

Using Underscore _: By convention, the underscore _ is used as a variable name when you need a placeholder but don't intend to use its value. This signals to other developers that the variable is intentionally ignored.

#Python #Programming #CodeTips #PythonTricks

━━━━━━━━━━━━━━━
By: @DataScience4
1
💡 Python Tips Part 3

Advancing your Python skills with more powerful techniques. This part covers safe dictionary access with .get(), flexible function arguments with *args and **kwargs, and context managers using the with statement.

user_data = {"name": "Alice", "age": 30}

# Safely get a key that exists
name = user_data.get("name")

# Safely get a key that doesn't exist by providing a default
city = user_data.get("city", "Not Specified")

print(f"Name: {name}, City: {city}")
# Output: Name: Alice, City: Not Specified

Dictionary .get() Method: Access dictionary keys safely. .get(key, default) returns the value for a key if it exists, otherwise it returns the default value (which is None if not specified) without raising a KeyError.

def dynamic_function(*args, **kwargs):
print("Positional args (tuple):", args)
print("Keyword args (dict):", kwargs)

dynamic_function(1, 'go', True, user="admin", status="active")
# Output:
# Positional args (tuple): (1, 'go', True)
# Keyword args (dict): {'user': 'admin', 'status': 'active'}

*args and **kwargs: Use these in function definitions to accept a variable number of arguments. *args collects positional arguments into a tuple, and **kwargs collects keyword arguments into a dictionary.

# The 'with' statement ensures the file is closed automatically
try:
with open("notes.txt", "w") as f:
f.write("Context managers are great!")
# No need to call f.close()
print("File written and closed.")
except Exception as e:
print(f"An error occurred: {e}")

The with Statement: The with statement creates a context manager, which is the standard way to handle resources like files or network connections. It guarantees that cleanup code is executed, even if errors occur inside the block.

#Python #Programming #CodeTips #PythonTricks

━━━━━━━━━━━━━━━
By: @DataScience4
Python tip:
Use f-strings for easy and readable string formatting.

name = "Alice"
age = 30
message = f"Hello, my name is {name} and I am {age} years old."
print(message)


Python tip:
Utilize list comprehensions for concise and efficient list creation.

numbers = [1, 2, 3, 4, 5]
squares = [x * x for x in numbers if x % 2 == 0]
print(squares)


Python tip:
Use enumerate() to iterate over a sequence while also getting the index of each item.

fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")


Python tip:
Use zip() to iterate over multiple iterables in parallel.

names = ["Alice", "Bob"]
ages = [25, 30]
for name, age in zip(names, ages):
print(f"{name} is {age} years old.")


Python tip:
Always use the with statement when working with files to ensure they are properly closed, even if errors occur.

with open("example.txt", "w") as f:
f.write("Hello, world!\n")
f.write("This is a test.")
# File is automatically closed here


Python tip:
Use *args to allow a function to accept a variable number of positional arguments.

def sum_all(*args):
total = 0
for num in args:
total += num
return total

print(sum_all(1, 2, 3))
print(sum_all(10, 20, 30, 40))


Python tip:
Use **kwargs to allow a function to accept a variable number of keyword arguments (as a dictionary).

def display_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")

display_info(name="Bob", age=40, city="New York")


Python tip:
Employ defaultdict from the collections module to simplify handling missing keys in dictionaries by providing a default factory.

from collections import defaultdict

data = [("fruit", "apple"), ("vegetable", "carrot"), ("fruit", "banana")]
categorized = defaultdict(list)
for category, item in data:
categorized[category].append(item)
print(categorized)


Python tip:
Use if __name__ == "__main__": to define code that only runs when the script is executed directly, not when imported as a module.

def greet(name):
return f"Hello, {name}!"

if __name__ == "__main__":
print("Running directly as a script.")
print(greet("World"))
else:
print("This module was imported.")


Python tip:
Apply type hints to your code for improved readability, maintainability, and to enable static analysis tools.

def add(a: int, b: int) -> int:
return a + b

result: int = add(5, 3)
print(result)


#PythonTips #PythonProgramming #PythonForBeginners #PythonTricks #CodeQuality #Pythonic #BestPractices #LearnPython

━━━━━━━━━━━━━━━
By: @DataScience4
4