Python

Print with python f string format

We use make the python print more wonderful with f string (formatted string) x=1 y=2 z=x+y print(f’result {x}+{y}={z}’) Copy Code this will print We can make it more wonderful directly adding expression x=1 y=2 print(f'{x} times {y} is {x * y}’) Copy Code We can also set the decimal places in the print number = […]

Check if a key exist or not in a python dictionary

We can check it with “in” operator and “get()” method In operator here returns the value True or False For example dictionary={“one”:1, “two”:2} if “two” in dictionary: print(“two exist in the dictionary”) Copy Code The get() method returns the value if that key exists. If not exists it returns None dictionary_data={“one”:1, “two”:2} #Here the key […]

Find out median of a list with python

Python has wonderful built-in library “statistics” We can find out the median of a list with this library easily with less code import statistics List = [1,2,3,4,5,6,7,8,9,10] result= statistics.median(List) print(result) Copy Code We can also generate list randomly with random module List = [randint(1, 101) for _ in range(50)] this code create a list of […]

How to format JSON with python

We can format minified json with python. Python has built in JSON module. We will add indentation in the minified json to format it. First example format JSON add space import json minified_json_example = ‘{“text”:”Hi There”,”type”:”greeting”,”word”:”2″}’ #convert it to python dictonary python_dictionarty = json.loads(minified_json_example) #We will use 4 space indentation to format and convert it […]

How to run python file in terminal

Open the terminal from you script directory ( Go to the folder where your python script is or the script you want to run. [ after going to the folder, click right mouse button … you find open in terminal option]) and run python3 python_file_name.py Copy If you know your python file location you can […]

Zip and unzip files with python

Its easy to zip and unizip files with python built in zipfile module For this we have to get the file location list . which files we wan to zip. we can use python glob to get the path current example structure import glob files=glob.glob(“NewFolder/*”) print(files) Copy Code It will print the result like this […]

Flask session simplest example

Flask sessions are useful when we want to remember a specific user. For example to know the user already visited the website before. So we can generate dynamic content for that user. Or we can use login based system In this code we will use the simplest flask session example Run the code go the […]

Convert a String to uppercase or lowercase with python

If our string is “hello”we can make it upper with upper()s=”hello” s.upper() it will be HELLO And in the same way if we want to make it lowercase we will just use lower() s.lower() It will again hello The code x=”Hello” print(x.lower()) #hello print(x) #Hello x=x.lower() print(x) #hello Copy Code

How to replace a character in a string with python

We will use replace method. for example our string is “ABC” We want to replace the C with D x=”ABC” x.replace(the character we want to replace, the character we want to place in the replacement) so it will be x.replace(“C”, “D”) The code x=”ABC” x=x.replace(“C”,”D”) print(x) Copy Code More string methods x=”Hello” x=x.lower() print(x) #hello […]

Get the current script directory with python os module

Python os module is very helpful when need to go to a specific directory and create a directory. For example print out the current directory import os current_directory = os.getcwd() print(“Current Directory:”, current_directory) Copy Code More operating system-independent and navigate to a directory in a platform-independent way, mport os # Define the path relative to […]

How to find out perfect numbers with python

What is perfect Number?Perfect number is a positive integer number in which sum of divisors(proper divisors) is equal to itself Proper divisor the divisors of 10 is 1,2,5,10 Here 1,2,5 is proper divisor .. but 10 is not proper. because its the number we are divisioning There is a perfect number in 10 is 6 […]

Calculate time dilation with python

In this example imagine two object one is Earth And another object is traveling in the space \[ t_0 = t \sqrt{1 – \frac{v^2}{c^2}} \] t0: Represents the dilated time experienced by the object which is traveling or seems traveling from earth t: Time passed on earth v: Velocity of the traveling object. c: Speed […]

How to convert text to sentence with python and nltk

We can easily convert text to sentence in python with nltk by tokenize sentence.. First install nltk Download nltk data . NLTK requires data files for tokenization. run the code in a python program to download the data. import nltk nltk.download(‘punkt’) Copy Code After download the necessary data from nltk import tokenize text=”In the symphony […]

How to get all possible combinations with python

Python is rich with wonderful standard library so you do not have to write everything from the very beginning. With permutations from iterators we can get wonderful and useful result with less code >In this example code we get the user input as string > Get the user input length > Then run a for […]

Easy Temperature Conversions with Python: A Beginner’s Guide (Celsius, Fahrenheit, Kelvin)

Basic Temperature Conversion Program This program takes a temperature input from the user, identifies the scale (Celsius, Fahrenheit, Kelvin), and converts it to the other two scales. Let’s break down the code step-by-step. For higher accuracy in the Kelvin scale use 273.15 instead of 273 x = str(input(“Enter in which scale you measured temperature (Celsius, […]

Expiring Links Tutorial: Python Flask One-Time Link Generator

One time links are essential where users want to share resources with co-worker or friend’s effortlessly but at the same time restrict other from access. Its works best because the link automatically inactive if some one go to the link for the first time. That means the same link will not work for the second […]

Converting Between Python Dictionaries and JSON

We will use json.dums() function to convert to json from python dictionary and json.loads() to convert from json to python dictionary. In this example code we used flower details data in python dictionary and converted it to json. import json # flowers in python dictionary flowers = { “rose”: { “scientific_name”: “Rosa”, “grows_in”: [“gardens”, “wild”], […]

Storing and retrieving data from sqlite with python

For making everything simpler we will use peewee orm with python sqlite3…. First create and connect to our database from peewee import * # SQLite database setup with Peewee db = SqliteDatabase(‘cv_database.db’) class User(Model): username = CharField(unique=True) # Add more user details as needed class Meta: database = db class CV(Model): user = ForeignKeyField(User, backref=’cv’) […]

How to create or remove files or folders using python

The easiest way to create or remove file is using python os module To create file To create folder To remove file To remove folder The consideration. If file already exist when creating file it will show error so we can check if the file already exist or when deleting folder

Save wikipedia article in txt format with python and wikipedia API

For focus based study its essential to get rid of all unnecessary context like wonderful design, and other ui effect. Whats necessary only text like the text book. Wikipedia is one of my most visited website at this time. Though I love the content , i wll love more if its more minimalist.. So there […]

Create your first chat application with Flask and Socketio

We will use socketio for real-time messaging First install our dependency for this application pip install flask pip install flask-socketio Copy Code How it will work. Every user will get an unique key. If the the other user submit the other users key that will send the message. its like sending message to unique username […]

Ajax example with flask

One of the best ajax applied in real world is username checker. In this example we will check if there is existing username This is code /project we will Our first step: Check if username exists or not Imagine we have this existing username when the user enter a username we will check it from […]

Solve Math Problems Instantly: Python’s eval() for Speedy String-Based Calculations

For example we have math expression in string like “4+2+34+346-234”We can directly calculate from this text with eval() Directly calculate from string our_expression= “4+2+34+346-234” answer=eval(our_expression) print(answer) # 152 Copy Code More things we can do calculate from variables x = 7 y = 5 expression = “x * y” result = eval(expression) print(“Result:”, result) # […]

Flask testing environment ssl solution with “adhoc”

Why? When I started developing video calling application at one point I faced this situation. In single pc(on localhost 127.0.0.1) everything works very well but when I need to test another pc on the same network for example(wifi) . Before on public production environment I wanted to test my own private network which was established […]

Simulate Bird Flocking Behavior with pygame: Algorithm and Code Explained

Bird flocking is a wonderful example of how simple behaviors can lead to complex, beautiful patterns in nature. We’ll learn the key principles behind this flocking behavior and write a python program to simulate this wonderful phenomenon. The principles Bird Flocking Simulation Algorithm Setting Up the Simulation Each Frame of the Simulation The pygame example […]

MongoDB Indexing Basics with Python

MongoDB Improve performance Why you should use Indexing in Databases Faster Searches Indexes act as efficient lookup structures, enabling rapid retrieval of data matching query criteria. Optimized Query Execution By using indexes, databases can strategically navigate the data path, minimizing processing time for queries. Reduced Disk I/O Indexes allow the database to locate data directly, […]

How to implement json web token (jwt) in flask

What is json web token? JSON Web Token (JWT) is like a digital ID card for websites and apps. It’s often issued after a successful login and securely tells a website about the user and their accessibility Secure Cookies also do the same thing. but there is some core differences Feature JSON Web Token (JWT) […]

How to create, read and write csv file from python

First Lets talk about csv Its a plain text format which comes from (Comma Separated Values) Most spreadsheet application supports this. You can open and edit it from excl, Libra office cal , google sheets and other spread sheet application, also supported by most of the programming language. For simplicity and flexibility often used in […]

How to generate requirements.txt in python

A requirements.txt file is essential for managing Python project dependencies. It ensures everyone working on your project has the correct libraries installed for development and deployment. The simplest way or automatically generate requirements.txt is using piprequs library. It will generate requairements.txt file based on the imports of your project. First install the library pip install […]

How to use try except in python

Python’s exception handling system lets you write code that can deal with unexpected errors The structure Explanation of the structure: The try…except structure in Python aims to prevent programs from crashing by providing a way to handle exceptions. This allows you to continue execution or provide meaningful error messages instead of the program terminating unexpectedly. […]

Python for Beginners: Turning Numbers into Text (String Conversion)

Converting to Text with python built in str() Function Its simple and easy We can convert number to string like this . here x=10 , where the value of x is a number when we write x=str(x) it becomes a string. Thats all! x=10 x=str(x) So we can convert number to string with str() number […]

Building a Simple and Secure API with Python Flask

Server-Side: Flask API Development We will build a simple API that will tell the current time. And then add more feature. The explanation and the code The code from flask import Flask, request, jsonify from datetime import datetime app = Flask(__name__) # Define a route to get the current time @app.route(‘/get-current-time’, methods=[‘POST’]) def get_current_time(): # […]

Using Environment Variables in Python: Easy Quick Guide

What are environment variables? Think of them like secret notes your programs can read. These notes hold important information like: Why are environment variables important? Why Use Environment Variables for Application Security and Flexibility? Sensitive information like API keys and encryption keys are the essential for modern applications. Adding them directly within your code introduces […]

Flask File Handling Made Easy: Upload and Download Files

Very basic example code_features This is our first example… Run this code first. Then read the step by step explanation. That will be more effective. Because this tutorial is all about practice. In this article covers simple upload, upload to database, securing the upload by adding limiting file extension and adding download link… Run the […]

How to use python enumerate

Enumerate helps to track the index and element. Though we can gain the same feature using for loop but enumerate makes the code more readable Imagine we have a list of colors color_names = [‘Red’, ‘Orange’, ‘Yellow’, ‘Green’, ‘Blue’, ‘Purple’, ‘Pink’, ‘Brown’,’Cyan’] For tracking both the index and corresponding element we can write this simple […]

How To Generate URL And Route Dynamically In Flask

We can set route dynamically instead of fixed route. For example In the pre-determined route links generate like this example.com/users/profile In the dynamically gendered route will be like this example.com/users/custom_profile_name We will use @app.route(‘/<username>’) The code will be like this We can use anything in the <username> here So if we load page like example.com/anything_here […]

Python Flask : Starter Automated Template

When starting new project again, Some common structure needed to be written again and again. So I wrote a program nearly three years (2021) ago to Get Everything ready on one script. Here is the python script that makes everything ready Here is is the revised version of the code The Program Automatically generates basic […]

How to work with python pickle

Python pickle is an essential tool for serializing and de-serializing Python objects, such as lists, dictionaries, and custom objects, offering a seamless method to store and retrieve data with efficiency. So we can easily store python lists,dictionary and frequently used object which need to be stored. Pickle is fast is efficient. Evan I have made […]

How To Add Static Files And Templates Folder In Python Tornado

In this program example we will use template_path=os.path.join(os.path.dirname(__file__), “templates”) this code to set the templates folder location In the same way we will set the static path static_path=os.path.join(os.path.dirname(__file__), “static”) And we will add this in the tornado application tornado.web.Application() This is the full app.py where templates folder and static folder added import tornado.web from tornado.options […]

How To Set Background Color In Pygame

import pygame,sys from pygame.locals import* pygame.init() screen=pygame.display.set_mode((600,400)) game_running=True while game_running: for event in pygame.event.get(): if event.type==QUIT: pygame.quit() sys.exit() screen.fill((255,250,240)) pygame.display.update() Copy Lets write the step by step full code and explanation First import necessary library And then initiate the pygame Set the our game display resolution Set the game in a loop so it will […]