Learn Python Coding
38.7K subscribers
1.06K photos
37 videos
24 files
853 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
✨ few-shot learning | AI Coding Glossary ✨

πŸ“– A setting where a model adapts to a new task using only a small number of labeled examples.

🏷️ #Python
Learning Common Algorithms with Python

β€’ This lesson covers fundamental algorithms implemented in Python. Understanding these concepts is crucial for building efficient software. We will explore searching, sorting, and recursion.

β€’ Linear Search: This is the simplest search algorithm. It sequentially checks each element of the list until a match is found or the whole list has been searched. Its time complexity is O(n).

def linear_search(data, target):
for i in range(len(data)):
if data[i] == target:
return i # Return the index of the found element
return -1 # Return -1 if the element is not found

# Example
my_list = [4, 2, 7, 1, 9, 5]
print(f"Linear Search: Element 7 found at index {linear_search(my_list, 7)}")


β€’ Binary Search: A much more efficient search algorithm, but it requires the list to be sorted first. It works by repeatedly dividing the search interval in half. Its time complexity is O(log n).

def binary_search(sorted_data, target):
low = 0
high = len(sorted_data) - 1

while low <= high:
mid = (low + high) // 2
if sorted_data[mid] < target:
low = mid + 1
elif sorted_data[mid] > target:
high = mid - 1
else:
return mid # Element found
return -1 # Element not found

# Example
my_sorted_list = [1, 2, 4, 5, 7, 9]
print(f"Binary Search: Element 7 found at index {binary_search(my_sorted_list, 7)}")


β€’ Bubble Sort: A simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The process is repeated until the list is sorted. Its time complexity is O(n^2).

def bubble_sort(data):
n = len(data)
for i in range(n):
# Last i elements are already in place
for j in range(0, n-i-1):
if data[j] > data[j+1]:
# Swap the elements
data[j], data[j+1] = data[j+1], data[j]
return data

# Example
my_list_to_sort = [4, 2, 7, 1, 9, 5]
print(f"Bubble Sort: Sorted list is {bubble_sort(my_list_to_sort)}")


β€’ Recursion (Factorial): Recursion is a method where a function calls itself to solve a problem. A classic example is calculating the factorial of a number (n!). It must have a base case to stop the recursion.

def factorial(n):
# Base case: if n is 1 or 0, factorial is 1
if n == 0 or n == 1:
return 1
# Recursive step: n * factorial of (n-1)
else:
return n * factorial(n - 1)

# Example
num = 5
print(f"Recursion: Factorial of {num} is {factorial(num)}")


#Python #Algorithms #DataStructures #Coding #Programming #LearnToCode

━━━━━━━━━━━━━━━
By: @DataScience4 ✨
❀1
✨ Quiz: Python MarkItDown: Convert Documents Into LLM-Ready Markdown ✨

πŸ“– Practice MarkItDown basics. Convert PDFs, Word documents, Excel documents, and HTML documents to Markdown. Try the quiz.

🏷️ #intermediate #ai #tools
Core Python Cheatsheet.pdf
173.3 KB
Python is a high-level, interpreted programming language known for its simplicity, readability, and
 versatility. It was first released in 1991 by Guido van Rossum and has since become one of the most
 popular programming languages in the world.
 Python’s syntax emphasizes readability, with code written in a clear and concise manner using whitespace and indentation to define blocks of code. It is an interpreted language, meaning that
 code is executed line-by-line rather than compiled into machine code. This makes it easy to write and test code quickly, without needing to worry about the details of low-level hardware.
 Python is a general-purpose language, meaning that it can be used for a wide variety of applications, from web development to scientific computing to artificial intelligence and machine learning. Its simplicity and ease of use make it a popular choice for beginners, while its power and flexibility make it a favorite of experienced developers.
 Python’s standard library contains a wide range of modules and packages, providing support for
 everything from basic data types and control structures to advanced data manipulation and visualization. Additionally, there are countless third-party packages available through Python’s package manager, pip, allowing developers to easily extend Python’s capabilities to suit their needs.
 Overall, Python’s combination of simplicity, power, and flexibility makes it an ideal language for a wide range of applications and skill levels.


https://t.me/CodeProgrammer ⚑️
Please open Telegram to view this post
VIEW IN TELEGRAM
❀2
✨ Python 3.14 Released and Other Python News for November 2025 ✨

πŸ“– Python 3.14 is officially out, Python 3.15 begins, and Python 3.9 reaches end of life. Plus, Django 6.0 first beta released, new PEPs, and more Python news.

🏷️ #community #news
πŸ‘1
✨ reasoning model | AI Coding Glossary ✨

πŸ“– A generative model tuned to solve multi-step problems.

🏷️ #Python
✨ chain of thought (CoT) | AI Coding Glossary ✨

πŸ“– A prompting technique that asks models to show intermediate steps, often improving multi-step reasoning but not guaranteeing accurate explanations.

🏷️ #Python
πŸ† Mastering Python Clean Code: 150 Key Principles

πŸ“’ Elevate your Python skills! Dive into 150 Clean Code principles to write truly readable and maintainable code for any project.

⚑ Tap to unlock the complete answer and gain instant insight.

━━━━━━━━━━━━━━━
By: @DataScience4 ✨
❀2
❔ Interview Question

What is the potential pitfall of using a mutable object (like a list or dictionary) as a default argument in a Python function?

Answer: A common pitfall is that the default argument is evaluated only once, when the function is defined, not each time it is called. If that default object is mutable, any modifications made to it in one call will persist and be visible in subsequent calls.

This can lead to unexpected and buggy behavior.

Incorrect Example (The Pitfall):

def add_to_list(item, my_list=[]):
my_list.append(item)
return my_list

# First call seems to work fine
print(add_to_list(1)) # Output: [1]

# Second call has unexpected behavior
print(add_to_list(2)) # Output: [1, 2] -- The list from the first call was reused!

# Third call continues the trend
print(add_to_list(3)) # Output: [1, 2, 3]


The Correct, Idiomatic Solution:

The standard practice is to use None as the default and create a new mutable object inside the function if one isn't provided.

def add_to_list_safe(item, my_list=None):
if my_list is None:
my_list = [] # Create a new list for each call
my_list.append(item)
return my_list

# Each call now works independently
print(add_to_list_safe(1)) # Output: [1]
print(add_to_list_safe(2)) # Output: [2]
print(add_to_list_safe(3)) # Output: [3]


tags: #Python #Interview #CodingInterview #PythonTips #Developer #SoftwareEngineering #TechInterview

━━━━━━━━━━━━━━━
By: @DataScience4 ✨
❀4
Media is too big
VIEW IN TELEGRAM
Channel owners rise up!

"I want to monetize my telegram channel". It is definitely possible!


Check our website, register your channel today!


Our community homeπŸ‘‡
https://t.me/waybien









Sponsored By WaybienAds
✨ How to Properly Indent Python Code ✨

πŸ“– Learn how to properly indent Python code in IDEs, Python-aware editors, and plain text editorsβ€”plus explore PEP 8 formatters like Black and Ruff.

🏷️ #basics #best-practices #python
❀1
😰 80 pages with problems, solutions, and code from a Python developer interview, ranging from simple to complex

⬇️ Save the PDF, it will come in handy!

#python #job
Please open Telegram to view this post
VIEW IN TELEGRAM
❀1
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
✨ Editorial Guidelines ✨

πŸ“– See how Real Python's editorial guidelines shape comprehensive, up-to-date resources, with Python experts, educators, and editors refining all learning content.

🏷️ #Python
✨ Topic: Python Basics ✨

πŸ“– Begin your Python journey with these beginner-friendly tutorials. Learn fundamental Python concepts to kickstart your career. This foundation will equip you with the necessary skills to further advance your budding Python programming skills.

🏷️ #357_resources
✨ Send Feedback ✨

πŸ“– We welcome ideas, suggestions, feedback, and the occasional rant. Did you find a topic confusing? Or did you find an error in the text or code? Send us your feedback via this page.

🏷️ #Python
πŸŽ‰ SPOTO Double 11 Mega Sale – Free IT Kits + Your Chance to Win!

πŸ”₯ IT Certs Have Never Been This Affordable β€” Don't Wait, Claim Your Spot!
πŸ’Ό Whether you're targeting #CCNA, #CCNP, #CCIE, #PMP, or other top #IT certifications,SPOTO offers the YEAR'S LOWEST PRICES on real exam dumps + 1-on-1 exam support!

πŸ‘‡ Grab Your Free Resources Now:
πŸ”— IT Certs E-book:https://bit.ly/49zHfxI
πŸ”—Test Your IT Skills for Free: https://bit.ly/49fI7Yu
πŸ”— AI & Machine Learning Kit: https://bit.ly/4p8BITr
πŸ”— Cloud Study Guide: https://bit.ly/43mtpen

🎁 Join SPOTO 11.11 Lucky Draw:
πŸ“± iPhone 17
πŸ›’ Amazon Gift Card $100
πŸ“˜ CCNA/PMP Course Training + Study Material + eBook
Enter the Draw πŸ‘‰: https://bit.ly/47HkoxV

πŸ‘₯ Join Study Group for Free Tips & Materials:
https://chat.whatsapp.com/LPxNVIb3qvF7NXOveLCvup

πŸŽ“ Get 1-on-1 Exam Help Now:
wa.link/88qwta

⏰ Limited Time Offer – Don't Miss Out! Act Now!

πŸ”” Subscribe now: Today, one gold trade changed everything. Find out how inside. | InsideAds
❔ Interview question

How do you create a new directory using the os module in Python, and what is the recommended way to handle cases where the directory might already exist?

Answer: The primary function to create a new directory (and any necessary parent directories) is os.makedirs(). To gracefully manage situations where the target directory might already exist without causing a FileExistsError, the recommended approach is to set the exist_ok parameter to True. This ensures that if the directory already exists, no exception is raised, allowing your program to continue execution smoothly. An example usage would be os.makedirs('path/to/my/new_directory', exist_ok=True).

tags: #interview #os #PythonBasics #FileSystem

━━━━━━━━━━━━━━━
By: @DataScience4 ✨
🐍 Python: Unobvious and Probable

Python, for all its readability and clear syntax, holds a treasury of less-trodden paths and nuanced behaviors that can catch even seasoned developers off guard. Understanding these intricacies deepens one's mastery and illuminates the language's design philosophy.

The Enigma of the ~ Operator: Bitwise NOT

Often overlooked outside of bit manipulation contexts, the unary ~ operator performs a bitwise NOT operation. For integers, its behavior can seem counter-intuitive at first glance.

Mathematically, ~x is equivalent to -(x+1).

x = 5
result = ~x
print(f"~{x} is {result}") # Output: ~5 is -6

y = -10
result = ~y
print(f"~{y} is {result}") # Output: ~-10 is 9


This behavior stems from how negative numbers are represented in two's complement form within computers. While its primary role is in low-level bitwise operations, it finds practical use in libraries like NumPy for inverting boolean arrays or selections, where ~ acts as a logical NOT.

import numpy as np

arr = np.array([True, False, True])
inverted_arr = ~arr
print(f"Original: {arr}, Inverted: {inverted_arr}") # Output: Original: [ True False True], Inverted: [False True False]

Its unobvious integer arithmetic hides a powerful, foundational operation.

all() and any() with Empty Sequences

The built-in functions all() and any() are crucial for evaluating the truthiness of elements within an iterable. Their behavior when faced with an empty sequence, however, is a classic source of mild confusion.

β€’ all(iterable) returns True if all elements of the iterable are truthy (or if the iterable is empty).
β€’ any(iterable) returns True if any element of the iterable is truthy (and False if the iterable is empty).

empty_list = []
print(f"all({empty_list}) is {all(empty_list)}") # Output: all([]) is True
print(f"any({empty_list}) is {any(empty_list)}") # Output: any([]) is False

truthy_list = [1, True, 'hello']
print(f"all({truthy_list}) is {all(truthy_list)}") # Output: all([1, True, 'hello']) is True
print(f"any({truthy_list}) is {any(truthy_list)}") # Output: any([1, True, 'hello']) is True

mixed_list = [0, 1, '', True]
print(f"all({mixed_list}) is {all(mixed_list)}") # Output: all([0, 1, '', True]) is False
print(f"any({mixed_list}) is {any(mixed_list)}") # Output: any([0, 1, '', True]) is True


The result all([]) being True is an example of a "vacuously true" statement: there are no falsy elements in an empty list, so the condition "all elements are truthy" holds. This design prevents unexpected errors in loops or conditional checks where an empty sequence might otherwise break logic. any([]) being False is straightforward: there are no elements to be truthy.

The is vs. == for Small Integers and Strings

Python has two primary ways to check for equality: == (value equality) and is (identity equality, checking if two variables refer to the exact same object in memory). While is is generally reserved for None or specific memory optimizations, CPython exhibits an unobvious caching behavior for certain immutable objects.
❀3