Friday, 24 May 2024

5 Tricky Python code snippets


 1. Misleading Variable Scope

This snippet demonstrates the tricky nature of variable scope in Python, particularly with nested functions.

def outer_function():

    x = "outer"

    def inner_function():

        nonlocal x

        x = "inner"

        print("Inner x:", x)

    inner_function()

    print("Outer x:", x)

outer_function()

#clcoding.com

Inner x: inner

Outer x: inner

2. Mutable Default Arguments

This snippet shows the common pitfall of using mutable default arguments in function definitions.


def append_to_list(value, my_list=[]):

    my_list.append(value)

    return my_list

print(append_to_list(1))

print(append_to_list(2))

print(append_to_list(3))

#clcoding.com

[1]

[1, 2]

[1, 2, 3]


3. Unexpected Behavior with Floating Point Arithmetic

Floating-point arithmetic can be non-intuitive due to precision issues.


a = 0.1

b = 0.2

c = 0.3


print(a + b == c)  

print(f"{a + b:.17f}")  

#clcoding.com

False

0.30000000000000004


4. Changing a List While Iterating

This snippet demonstrates the pitfalls of modifying a list while iterating over it.


numbers = [1, 2, 3, 4, 5]

for i in numbers:

    if i % 2 == 0:

        numbers.remove(i)

print(numbers)


#clcoding.com

[1, 3, 5]


5. Unpacking and Extended Unpacking

Python allows for complex unpacking operations which can be tricky to understand at first glance.


a, b, *c, d = range(6)

print(a)  

print(b)  

print(c)  

print(d)  


# Nested unpacking

x, (y, z) = (1, (2, 3))

print(x)  

print(y) 

print(z)  


#clcoding.com

0

1

[2, 3, 4]

5

1

2

3

Python Coding challenge - Day 214 | What is the output of the following Python Code?

 

Code: 

a = 0.1

b = 0.2

c = 0.3

print(a + b == c) 

Solution and Explanation:

The code snippet:

a = 0.1
b = 0.2
c = 0.3

print(a + b == c)
produces False as output. This result can be surprising, but it stems from the way floating-point numbers are represented in computer hardware. Here’s a detailed explanation:

Floating-Point Representation

Binary Representation:

Computers represent floating-point numbers in binary (base-2) format, which can lead to precision issues because not all decimal fractions can be represented exactly as binary fractions.
For example, 0.1 in binary is an infinitely repeating sequence: 0.00011001100110011....

Precision Limitations:

When 0.1 and 0.2 are stored in a computer's memory, they are approximated to the nearest value that can be represented in the finite number of bits available.
The same approximation happens for 0.3.

Summation Inaccuracy:

When adding 0.1 and 0.2, the result is not exactly 0.3 due to these approximations. Instead, the result is a value very close to 0.3, but not exactly 0.3.
The actual value of a + b might be something like 0.30000000000000004.

Comparison:

When Python compares a + b to c, it is comparing 0.30000000000000004 (the result of a + b) to 0.3 (the stored value of c), and since these are not exactly equal, the comparison returns False.

Demonstration with More Precision

You can observe this behavior by printing the values with higher precision:

print(f"{a + b:.17f}")  # Shows the precision error
print(f"{c:.17f}")
This will output:
0.30000000000000004
0.29999999999999999
As you can see, the two numbers are very close but not exactly the same, which explains why the comparison a + b == c evaluates to False.


Best Practices

To avoid issues with floating-point comparisons:

Use a Tolerance:

Instead of direct comparison, use a small tolerance value to check if the numbers are "close enough":

tolerance = 1e-10
print(abs((a + b) - c) < tolerance)  # True

Decimal Module:

For financial and other high-precision calculations, use Python's decimal module which can handle decimal arithmetic more accurately.

from decimal import Decimal

a = Decimal('0.1')
b = Decimal('0.2')
c = Decimal('0.3')

print(a + b == c)  # True
This approach avoids the pitfalls of floating-point arithmetic by using a representation that can exactly represent decimal fractions.







Python 201: Intermediate Python


Python 201 is the sequel to my first book, Python 101. If you already know the basics of Python and now you want to go to the next level, then this is the book for you! This book is for intermediate level Python programmers only. There won't be any beginner chapters here. This book is based on Python 3.

The book will be broken up into five parts. Here's how:


Part I - Intermediate Modules

Chapter 1 - The argparse module

Chapter 2 - The collections module

Chapter 3 - The contextlib module (Context Managers)

Chapter 4 - The functools module (Function overloading, caching, etc)

Chapter 5 - All about imports

Chapter 6 - The importlib module

Chapter 7 - Iterators and Generators

Chapter 8 - The itertools module

Chapter 9 - The re module (An Intro to Regex in Python)

Chapter 10 - The typing module (Type Hinting)


Part II - Odds and Ends

Chapter 11 - map, filter and more

Chapter 12 - unicode

Chapter 13 - benchmarking

Chapter 14 - encryption

Chapter 15 - Connecting to databases

Chapter 16 - super

Chapter 17 - descriptors

Chapter 18 - Scope (local, global and the new non_local)


Part III - Web

Chapter 19 - Web scraping

Chapter 20 - Working with web APIs

Chapter 21 - ftplib

Chapter 22 - urllib


Part IV - Testing

Chapter 23 - Doctest

Chapter 24 - unittest

Chapter 25 - mock

Chapter 26 - coverage.py


Part V - Concurrency

Chapter 27 - The asyncio module

Chapter 28 - The threading module

Chapter 29 - The multiprocessing module

Chapter 30 - The concurrent.futures module


Join the course: Python 201: Intermediate Python





Thursday, 23 May 2024

Convert to mathematical symbols using Python ๐Ÿงต

 

import math
import latexify
@latexify.function
def quadratic_roots(a, b, c):
    discriminant = b ** 2 - 4 * a * c
    root1 = (-b + math.sqrt(discriminant)) / (2 * a)
    root2 = (-b - math.sqrt(discriminant)) / (2 * a)
    return root1, root2
quadratic_roots

#clcoding.com
import math
import latexify
@latexify.function
def pythagorean_theorem(a, b):
    return math.sqrt(a ** 2 + b ** 2)
pythagorean_theorem

#clcoding.com
import math
import latexify
@latexify.function
def compound_interest(P, r, n, t):
    return P * (1 + r/n) ** (n*t)
compound_interest

#clcoding.com

import math
import latexify
@latexify.function
def distance(x1, y1, x2, y2):
  return math.sqrt((x2-x1)**2 + (y2-y1)**2)
distance
import math
import latexify
@latexify.function
def factorial(n):
  if n == 0:
    return 1
  elif n == 1:
    return 1
  else:
    return n * factorial(n-1)
factorial

Python Coding challenge - Day 213 | What is the output of the following Python Code?

 

Code:

a = [1, 2, 3, 4]

b = [1, 2, 5]

if sorted(a) < sorted(b):

    print(True)

else:

    print(False)

Solution and Explanation: 

Let's break down the code step by step to understand what it does:

List Initialization:

a = [1, 2, 3, 4]
b = [1, 2, 5]
Here, two lists a and b are initialized with the values [1, 2, 3, 4] and [1, 2, 5], respectively.

Sorting the Lists:

sorted(a)
sorted(b)
The sorted() function is used to sort the lists a and b. However, since both lists are already sorted in ascending order, the sorted versions will be the same as the original:

sorted(a) results in [1, 2, 3, 4]
sorted(b) results in [1, 2, 5]
Comparison:

sorted(a) < sorted(b)
In Python, comparing lists using < compares them lexicographically (element by element from left to right, like in a dictionary). The comparison proceeds as follows:

Compare the first elements: 1 (from a) and 1 (from b). Since they are equal, move to the next element.
Compare the second elements: 2 (from a) and 2 (from b). Since they are equal, move to the next element.
Compare the third elements: 3 (from a) and 5 (from b). Since 3 is less than 5, the comparison sorted(a) < sorted(b) evaluates to True.
Conditional Statement:

if sorted(a) < sorted(b):
    print(True)
else:
    print(False)
Given that sorted(a) < sorted(b) is True, the code enters the if block and executes print(True).

Putting it all together, the code prints True because, when compared lexicographically, the sorted list a ([1, 2, 3, 4]) is indeed less than the sorted list b ([1, 2, 5]).






13 Powerful Python Features You're Probably Not Using Enough

Python is a versatile and powerful language, and while many developers use it extensively, there are numerous features that often go underutilized.

List Comprehensions

List comprehensions provide a concise way to create lists. This can replace the need for using loops to generate lists.

squares = [x**2 for x in range(10)]

Generator Expressions

Similar to list comprehensions but with parentheses, generator expressions are used for creating generators. These are memory-efficient and suitable for large data sets.

squares_gen = (x**2 for x in range(10))

Default Dictionary

The defaultdict from the collections module is a dictionary-like class that provides default values for missing keys.

from collections import defaultdict

dd = defaultdict(int)

dd['key'] += 1

Named Tuples

namedtuple creates tuple subclasses with named fields. This makes code more readable by accessing fields by name instead of position.

from collections import namedtuple

Point = namedtuple('Point', 'x y')

p = Point(10, 20)

Enumerate Function

The enumerate function adds a counter to an iterable and returns it as an enumerate object. This is useful for obtaining both the index and the value in a loop.

for index, value in enumerate(['a', 'b', 'c']):

    print(index, value)

Zip Function

The zip function combines multiple iterables into a single iterable of tuples. This is useful for iterating over multiple sequences simultaneously.

names = ['a', 'b', 'c']

ages = [20, 25, 30]

combined = list(zip(names, ages))


Set Comprehensions

Similar to list comprehensions, set comprehensions create sets in a concise way.

unique_squares = {x**2 for x in range(10)}

Frozenset

A frozenset is an immutable set. It's useful when you need a set that cannot be changed after creation.

fs = frozenset([1, 2, 3, 2, 1])



Counter

The Counter class from the collections module counts the occurrences of elements in a collection. It's useful for counting hashable objects.

from collections import Counter

counts = Counter(['a', 'b', 'c', 'a', 'b', 'b'])

Context Managers

Using the with statement, context managers handle resource management, like file I/O, efficiently and cleanly.

with open('file.txt', 'r') as file:

    contents = file.read()



dataclass

The dataclass decorator simplifies class creation by automatically adding special methods like init and repr.

from dataclasses import dataclass

@dataclass

class Point:

    x: int

    y: int



Decorators

Decorators are functions that modify the behavior of other functions. They are useful for logging, access control, memoization, and more.

def my_decorator(func):

    def wrapper():

        print("Something is happening before the function is called.")

        func()

        print("Something is happening after the function is called.")

    return wrapper

@my_decorator

def say_hello():

    print("Hello!")

Asyncio

The asyncio module provides a framework for asynchronous programming. This is useful for I/O-bound and high-level structured network code.

import asyncio

async def main():

    print('Hello')

    await asyncio.sleep(1)

    print('World')

asyncio.run(main())



Wednesday, 22 May 2024

50 Best Practices in Python

 


  1. Write Readable Code: Use descriptive variable names and write comments where necessary.
  2. Follow PEP 8: Adhere to Python's official style guide for formatting your code.
  3. Use Virtual Environments: Isolate project dependencies using virtualenv or venv.
  4. Keep Code DRY: Avoid duplication by creating reusable functions and modules.
  5. Write Modular Code: Break your code into modules and packages.
  6. Use List Comprehensions: For simple loops, prefer list comprehensions for readability and performance.
  7. Handle Exceptions: Use try-except blocks to handle exceptions gracefully.
  8. Use Context Managers: For resource management, use context managers (with statements).
  9. Test Your Code: Write unit tests to ensure your code works as expected.
  10. Leverage Built-in Functions: Python has a rich set of built-in functions; use them to simplify your code.
  11. Optimize Imports: Import only what you need and organize imports logically.
  12. Document Your Code: Write docstrings for modules, classes, and functions.
  13. Use Meaningful Docstrings: Provide useful information in docstrings, including parameters, return values, and examples.
  14. Adopt Version Control: Use git or another version control system to manage your code changes.
  15. Automate Testing: Use CI/CD tools to automate your testing and deployment.
  16. Use Type Hints: Add type hints to your function signatures to make your code more readable and maintainable.
  17. Avoid Global Variables: Limit the use of global variables to reduce complexity.
  18. Keep Functions Small: Write small, single-purpose functions.
  19. Optimize Performance: Profile your code to find bottlenecks and optimize them.
  20. Stay Updated: Keep your Python and library versions up to date.
  21. Use Pythonic Idioms: Write code that takes advantage of Python’s features, such as tuple unpacking and the else clause in loops.
  22. Practice Code Reviews: Regularly review code with peers to catch issues early and share knowledge.
  23. Avoid Mutable Default Arguments: Default argument values should be immutable to avoid unexpected behavior.
  24. Use Logging: Instead of print statements, use the logging module for better control over log output.
  25. Be Careful with Floating Point Arithmetic: Understand the limitations and potential inaccuracies.
  26. Leverage Generators: Use generators to handle large datasets efficiently.
  27. Understand Variable Scope: Be aware of local and global scope and use variables appropriately.
  28. Use Proper Indentation: Follow Python’s strict indentation rules to avoid syntax errors.
  29. Encapsulate Data: Use classes and objects to encapsulate data and functionality.
  30. Implement str and repr: Provide meaningful string representations for your classes.
  31. Avoid Premature Optimization: Focus on readability and maintainability first; optimize when necessary.
  32. Understand the GIL: Be aware of the Global Interpreter Lock and its impact on multithreading.
  33. Use Efficient Data Structures: Choose the right data structure for the task (e.g., lists, sets, dictionaries).
  34. Avoid Deep Nesting: Keep your code flat and avoid deep nesting of loops and conditionals.
  35. Adopt a Consistent Naming Convention: Follow naming conventions for variables, functions, classes, and modules.
  36. Use Enum for Constants: Use the Enum class to define constants.
  37. Prefer f-Strings: Use f-strings for string formatting in Python 3.6+.
  38. Leverage Dataclasses: Use dataclasses for simple data structures (Python 3.7+).
  39. Handle Resources Properly: Ensure files and other resources are closed properly using with statements.
  40. Understand List vs. Tuple: Use lists for mutable sequences and tuples for immutable sequences.
  41. Use Decorators Wisely: Understand and use decorators to extend the behavior of functions and methods.
  42. Optimize Memory Usage: Be mindful of memory usage, especially in large applications.
  43. Adopt a Code Formatter: Use tools like Black to format your code automatically.
  44. Use Static Analysis Tools: Employ tools like pylint, flake8, and mypy to catch potential issues early.
  45. Understand Slicing: Use slicing effectively for lists, tuples, and strings.
  46. Avoid Anti-patterns: Recognize and avoid common anti-patterns in Python programming.
  47. Keep Learning: Continuously learn and stay updated with the latest Python features and libraries.
  48. Contribute to Open Source: Contributing to open-source projects helps improve your skills and gives back to the community.
  49. Write Secure Code: Be aware of security best practices and write code that minimizes vulnerabilities.
  50. Refactor Regularly: Regularly refactor your code to improve its structure and readability.

Python Coding challenge - Day 212 | What is the output of the following Python Code?

 

let's break down and explain each part of this code:

my_dict = {1: 0, 0: [], True: False}

result = all(my_dict)

print(result)

Step-by-Step Explanation

Dictionary Creation:

my_dict = {1: 0, 0: [], True: False}

This line creates a dictionary my_dict with the following key-value pairs:

1: 0 - The key is 1 and the value is 0.

0: [] - The key is 0 (or (0) in another form) and the value is an empty list [].

True: False - The key is True and the value is False.

Note that in Python dictionaries, keys must be unique. If you try to define multiple key-value pairs with the same key, the last assignment will overwrite any previous ones. However, in this dictionary, the keys are unique even though 1 and True can be considered equivalent (True is essentially 1 in a boolean context).

Using the all Function:

result = all(my_dict)

The all function in Python checks if all elements in an iterable are True. When all is applied to a dictionary, it checks the truthiness of the dictionary's keys (not the values).

In this dictionary, the keys are 1, 0, and True.

The truthiness of the keys is evaluated as follows:

1 is True.

0 is False.

True is True.

Since one of the keys (0) is False, the all function will return False.

Printing the Result:

print(result)

This line prints the result of the all function. Given that the dictionary contains a False key (0), the output will be False.

Summary

Putting it all together, the code creates a dictionary and uses the all function to check if all the keys are true. Since one of the keys is 0 (which is False), the all function returns False, which is then printed.

So, when you run this code, the output will be:

False

Popular Posts

Categories

100 Python Programs for Beginner (119) AI (227) Android (25) AngularJS (1) Api (7) Assembly Language (2) aws (28) Azure (9) BI (10) Books (262) Bootcamp (1) C (78) C# (12) C++ (83) Course (86) Coursera (300) Cybersecurity (29) data (5) Data Analysis (28) Data Analytics (20) data management (15) Data Science (333) Data Strucures (16) Deep Learning (137) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (19) Finance (10) flask (4) flutter (1) FPL (17) Generative AI (68) Git (10) Google (50) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (41) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (267) Meta (24) MICHIGAN (5) microsoft (11) Nvidia (8) Pandas (13) PHP (20) Projects (32) pytho (1) Python (1267) Python Coding Challenge (1100) Python Mistakes (50) Python Quiz (455) Python Tips (5) Questions (3) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (19) SQL (46) Udemy (17) UX Research (1) web application (11) Web development (8) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)