Close Menu
    Trending
    • STOP Building Useless ML Projects – What Actually Works
    • Credit Risk Scoring for BNPL Customers at Bati Bank | by Sumeya sirmula | Jul, 2025
    • The New Career Crisis: AI Is Breaking the Entry-Level Path for Gen Z
    • Musk’s X appoints ‘king of virality’ in bid to boost growth
    • Why Entrepreneurs Should Stop Obsessing Over Growth
    • Implementing IBCS rules in Power BI
    • What comes next for AI copyright lawsuits?
    • Why PDF Extraction Still Feels LikeHack
    AIBS News
    • Home
    • Artificial Intelligence
    • Machine Learning
    • AI Technology
    • Data Science
    • More
      • Technology
      • Business
    AIBS News
    Home»Machine Learning»Codes That Can Be Written More Correctly | by AI With Lil Bro | Apr, 2025
    Machine Learning

    Codes That Can Be Written More Correctly | by AI With Lil Bro | Apr, 2025

    Team_AIBS NewsBy Team_AIBS NewsApril 26, 2025No Comments5 Mins Read
    Share Facebook Twitter Pinterest LinkedIn Tumblr Reddit Telegram Email
    Share
    Facebook Twitter LinkedIn Pinterest Email


    Made with Canon 5d Mark III and loved analog lens, Leica APO Macro Elmarit-R 2.8 / 100mm (Year: 1993)
    by markus spiske on unplash

    Python is among the most liked and beginner-friendly programming languages on the market. Its clear syntax and readability have made it a favourite alternative for builders in fields starting from internet growth to information science and AI. However whereas Python is simple to study, writing appropriate, clear, and Pythonic code is a talent that takes observe and consciousness.

    Poorly written Python code may nonetheless run — however it may be troublesome to learn, tougher to take care of, and inefficient. Clear, appropriate code not solely reduces the possibility of bugs but additionally makes it simpler for others (and your future self) to grasp what’s taking place.

    On this weblog, we’ll stroll by 8 frequent examples of Python code which might be typically written poorly, together with corrected variations and explanations of why the improved code is best. Should you’re a newbie or an skilled developer trying to brush up on finest practices, this information shall be precious for leveling up your Python expertise.

    —

    1. Utilizing Loops As a substitute of Listing Comprehensions

    unhealthy Code:

    squares = []
    for i in vary(10):
    squares.append(i * i)

    What’s the Downside?
    Whereas this code works positive, it’s unnecessarily verbose. Python affords a extra readable and concise method to create lists based mostly on sequences.

    professional Code:

    squares = [i * i for i in range(10)]

    Why Is This Higher?
    Listing comprehensions are extra Pythonic, compact, and sometimes sooner than conventional loops for easy checklist constructions. They make your intention instantly clear to anybody studying the code.

    —

    2. Utilizing Mutable Default Arguments

    unhealthy Code:

    def add_item(merchandise, item_list=[]):
    item_list.append(merchandise)
    return item_list

    What’s the Downside?
    The default checklist is created solely as soon as when the perform is outlined, so it persists throughout a number of calls.

    higher Code:

    def add_item(merchandise, item_list=None):
    if item_list is None:
    item_list = []
    item_list.append(merchandise)
    return item_list

    Why Is This Higher?
    This avoids unintended unwanted side effects the place a number of perform calls share the identical mutable default argument. It’s a standard Python gotcha that journeys up many newbies.

    —

    3. Not Utilizing Context Managers for File Operations

    newbie Code:

    file = open('information.txt', 'r')
    content material = file.learn()
    file.shut()

    What’s the Downside?
    If an error happens between opening and shutting the file, it’d stay open, resulting in useful resource leaks.

    professional Code:

    with open('information.txt', 'r') as file:
    content material = file.learn()

    Why Is This Higher?
    Utilizing a with assertion ensures that the file is robotically closed, even when an exception happens. It’s safer, cleaner, and extra Pythonic.

    —

    4. Utilizing World Variables Unnecessarily

    unhealthy Code:

    depend = 0
    def increment():
    world depend
    depend += 1

    What’s the Downside?
    Counting on world variables makes code tougher to trace, take a look at, and debug. It additionally reduces modularity.

    good Code:

    def increment(depend):
    return depend + 1

    Why Is This Higher?
    By passing variables as parameters and returning outcomes, you make your code extra modular, predictable, and simpler to check. Keep away from world variables at any time when attainable.

    —

    5. Utilizing Imprecise or Unhelpful Variable Names

    your Code:

    a = 5
    b = 10
    c = a + b
    print(c)

    What’s the Downside?
    Single-letter variable names (besides in loop counters or very brief code blocks) make it arduous to grasp the code’s objective.

    my Code:

    worth = 5
    tax = 10
    total_price = worth + tax
    print(total_price)

    Why Is This Higher?
    Significant variable names enhance readability and make your code self-documenting. Anybody studying your code can shortly grasp its intent.

    —

    6. Writing Capabilities That Do Too A lot

    your code:

    def process_data(information):
    cleaned = [d.strip() for d in data]
    sorted_data = sorted(cleaned)
    print(sorted_data)

    What’s the Downside?
    This perform cleans information, types it, and prints it — too many tasks for one perform.

    it’s higher model:

    def clean_data(information):
    return [d.strip() for d in data]def sort_data(information):
    return sorted(information)def print_data(information):
    print(information)

    Why Is This Higher?
    Capabilities ought to do one factor and do it effectively. This improves code modularity, reusability, and testability.

    —

    7. Ignoring PEP 8 Styling Tips

    your code:

    def add (a,b):return a+b

    What’s the Downside?
    The shortage of areas and compactness makes the code tougher to learn. PEP 8 is Python’s official fashion information that promotes readability.

    good Code:

    def add(a, b):
    return a + b

    Why Is This Higher?
    Following PEP 8 ensures consistency throughout your codebase and makes your code extra readable and maintainable.

    —

    8. Not Utilizing Constructed-In Capabilities Successfully

    your code:

    numbers = [3, 7, 2, 9, 4]
    most = numbers[0]
    for num in numbers:
    if num > most:
    most = num
    print(most)

    What’s the Downside?
    Reinventing the wheel by manually discovering the utmost worth, when Python already offers a built-in perform for this.

    my recommended code :

    numbers = [3, 7, 2, 9, 4]
    print(max(numbers))

    Why Is This Higher?
    Constructed-in features like max() are optimized, readable, and cut back the probabilities of errors. All the time favor them when obtainable.

    —

    Conclusion

    Writing clear, appropriate, and Pythonic code isn’t nearly making issues look fairly — it impacts the reliability, efficiency, and maintainability of your initiatives. Poorly written code can result in hidden bugs, efficiency points, and future complications once you or another person revisits it.

    By making use of the practices we lined at this time — like utilizing checklist comprehensions, avoiding mutable default arguments, leveraging context managers, naming variables meaningfully, and following PEP 8 — you’ll not solely enhance the standard of your code but additionally your expertise as a developer.

    Nice builders aren’t those that write code that works, however those that write code that others can perceive, preserve, and construct upon.

    So, the following time you write Python code, take a second to assessment it. Is it clear? Right? Pythonic? Small enhancements now can save loads of hassle later.

    Maintain training, continue to learn, and joyful coding!

    Earlier than you go:



    Source link

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleAce This Tricky Interview Question
    Next Article This Is the One Question AI Can’t Answer For You
    Team_AIBS News
    • Website

    Related Posts

    Machine Learning

    Credit Risk Scoring for BNPL Customers at Bati Bank | by Sumeya sirmula | Jul, 2025

    July 1, 2025
    Machine Learning

    Why PDF Extraction Still Feels LikeHack

    July 1, 2025
    Machine Learning

    🚗 Predicting Car Purchase Amounts with Neural Networks in Keras (with Code & Dataset) | by Smruti Ranjan Nayak | Jul, 2025

    July 1, 2025
    Add A Comment
    Leave A Reply Cancel Reply

    Top Posts

    STOP Building Useless ML Projects – What Actually Works

    July 1, 2025

    I Tried Buying a Car Through Amazon: Here Are the Pros, Cons

    December 10, 2024

    Amazon and eBay to pay ‘fair share’ for e-waste recycling

    December 10, 2024

    Artificial Intelligence Concerns & Predictions For 2025

    December 10, 2024

    Barbara Corcoran: Entrepreneurs Must ‘Embrace Change’

    December 10, 2024
    Categories
    • AI Technology
    • Artificial Intelligence
    • Business
    • Data Science
    • Machine Learning
    • Technology
    Most Popular

    Machine Learning in Wireless Communications: Innovation, Hype, and Engineering Reality | by Dr Mehran Behjati | May, 2025

    May 29, 2025

    Can Virtual Medical Assistants Handle Insurance Verification & Billing?

    March 6, 2025

    The First AI Movie Is Coming from Bollywood in 2025

    December 25, 2024
    Our Picks

    STOP Building Useless ML Projects – What Actually Works

    July 1, 2025

    Credit Risk Scoring for BNPL Customers at Bati Bank | by Sumeya sirmula | Jul, 2025

    July 1, 2025

    The New Career Crisis: AI Is Breaking the Entry-Level Path for Gen Z

    July 1, 2025
    Categories
    • AI Technology
    • Artificial Intelligence
    • Business
    • Data Science
    • Machine Learning
    • Technology
    • Privacy Policy
    • Disclaimer
    • Terms and Conditions
    • About us
    • Contact us
    Copyright © 2024 Aibsnews.comAll Rights Reserved.

    Type above and press Enter to search. Press Esc to cancel.