Python Code Snippets

Python is a versatile language that you can use on the backend, frontend, or full stack of a web application. It’s also used in data science and machine learning applications. Python is a high-level, interpreted, general-purpose programming language with a focus on code readability.

Python is one of the most popular programming languages in the world. It’s used in a variety of applications, from web development to data science. Python is easy to learn for beginners and has many resources available online.

If you’re looking for a roundup of some useful Python code snippets, you’ve come to the right place. In this post, we’ll share some handy code examples that will help you get up and running with Python. Whether you’re a beginner or an experienced developer, these snippets will come in handy.

Curated List of Python Code Snippets

Array & List

Find the Sum of all Elements in an Array —
arr = [1111, 212, 3333, 44, 5344541, 68913, 10, 100, 20234]
print(sum(arr)) # Output: 5438498 
Create an Array of Numbers 0 to N —
integer_list = list(range(0, 10))
print(integer_list)
#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Sum a Column's Values in a List —
sales = [
    {'product': 'CHINESE Burning Blue', 'price': 152.25}, 
    {'product': 'CHINESE Burning Charms', 'price': 100.00}, 
    {'product': 'Crystal BEADED', 'price': 16.75}, 
    {'product': 'Crystal Ring', 'price': 78.00}, 
]
total_price = sum([sale['price'] for sale in sales])
print(total_price)
# output: 347.0
Extract a Column From a List —
keyboards = [['q', 'w', 'r'],
            ['a', 's', 'd'],
            ['z', 'x', 'c']]
first_col = [row[0] for row in keyboards]
print(first_col) #output: ['q', 'a', 'z']

brands = [{'label': 'Samsung', 'model': '121312412'}, {'label': 'Apple', 'model': '789615'}]
labels = [brand['label'] for brand in brands]
print(labels ) #output: ['Samsung', 'Apple']

Class & Object

Create Static Variables —
//use staticmethod()
class Student:
    def showAge(birthdate):
        print(birthdate)
Student.showAge = staticmethod(Student.showAge)
Student.showAge("1980-01-01")

//use @staticmethod decorator
class Student:
    @staticmethod
    def showAge(birthdate):
        print(birthdate)

Student.showAge("2000-05-26")

Datetime

Get Day Month Year from Date Object —
import datetime
date = datetime.date(2022, 5, 15)
print(date.strftime('%d %b %Y')) #15 May 2022
print(date.strftime('%d')) #15
print(date.strftime('%m')) #5
print(date.strftime('%Y')) #2022
Last Day of a Month —
import calendar

month_range = calendar.monthrange(2022, 1)
print(month_range) # (5, 31)
month_range = calendar.monthrange(2022, 2)
print(month_range) # (1, 28)
month_range = calendar.monthrange(2022, 5)
print(month_range) # (6, 31)

last_day = month_range[1]
month_range = calendar.monthrange(2022, 8)
print(month_range) # (0, 31)
Calculate Age from Birthday —
from datetime import date

today = date.today()
age = today.year - born.year - ((today.month, today.day) < (born.month, born.day))
Subtract Dates and Times —
start_date = datetime.date(2022, 5, 1)
end_date = datetime.date(2022, 5, 14)

result = end_date - start_date

Troubleshoot

Add Python to Windows PATH —
#In my case, I install Python 3 via Odoo installation, so I use it as my default python.
C:\Program Files (x86)\Odoo 12.0\python
Free Up RAM —
import numpy as np
import gc
big_array = np.arange(1,700)
print(big_array)
del big_array
gc.collect()
print(big_array)

Variable

Fix "NameError: name is not defined" —
//remember to define the varable before using it
sheets = [
    {'label': 'Trade Receivable Account', 'items': []},
    {'label': 'Trade Payable Account', 'items': []},
    {'label': 'GST Payable', 'items': []},
]
print(sheets)
Assigning Multiple Values —
x, y, z = 14, [1, 2, 3], 'New data'
first_name = last_name = middle_name = 'Tom'

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close