Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Sunday 26 March 2023

5 awesome hidden features in Python

 Walrus operator (:=): This operator allows you to assign and return a value in the same expression. It can be particularly useful in list comprehensions or other situations where you need to assign a value to a variable and use it in a subsequent expression. Here's an example:

if (n := len(my_list)) > 10:

    print(f"List is too long ({n} elements, expected <= 10)")

Extended Iterable Unpacking: This feature allows you to unpack an iterable into multiple variables, including a "catch-all" variable that gets assigned any remaining items in the iterable. Here's an example:

first, *middle, last = my_list

In this example, first is assigned the first item in my_list, last is assigned the last item, and middle is assigned all the items in between.

Underscore as a placeholder: In interactive Python sessions, you can use the underscore (_) as a shorthand for the result of the last expression. This can be useful if you need to reuse the result of a previous command. Here's an example:

>>> 3 * 4
>>> _ + 5

slots attribute: The __slots__ attribute allows you to define the attributes of a class and their data types in advance, which can make the class more memory-efficient. Here's an example:

class MyClass:
    __slots__ = ("x", "y")
    def __init__(self, x, y):
        self.x = x
        self.y = y

In this example, we are defining a class with two attributes (x and y) and using the __slots__ attribute to define them in advance.

Callable instances: In Python, instances of classes can be made callable by defining a __call__ method. This can be useful if you want to create objects that behave like functions. Here's an example:

class Adder:
    def __init__(self, n):
        self.n = n
    def __call__(self, x):
        return self.n + x
add_five = Adder(5)
result = add_five(10)
print(result)  # Output: 15

In this example, we are defining a class Adder that takes a number n and defines a __call__ method that adds n to its argument. We then create an instance of Adder with n=5 and use it like a function to add 5 to 10, resulting in 15.

Monday 2 January 2023

Wednesday 28 December 2022

Sunday 25 December 2022

Python Quiz | Day 35 | What is the output of following code ?


Complete Playlist :


Answer: D. Explanation:

The list.pop method removes an element from the list, and returns the removed element.

When used without arguments, pop removes and returns the last element of the list.

When an argument index is specified, 

li.pop(index) removes the element li[index] from li, and returns the removed element.

When li.pop(1) is executed, li[1] is removed from li, and the removed value is returned.

Here li[1] is 3. Therefore, li is modified to [2,1], and the return value from li.pop(1) is 3

Sunday 2 October 2022

Lazy Operators 🥱 --- Python


Python is a great language to learn, but it can be hard to pick up if you’ve never programmed before. A lot of the syntax and functions are pretty weird when compared to other languages like JavaScript, Ruby or Java. Luckily, Python has some helpful built-in functions that make it easier for beginners to get started learning programming. In this blog post we will take a look at some of these functions and how they can help us become more efficient programmers in our daily lives!

#Guess the output in this case?

The following Python code is an example of lazy operators. This section shows how to use them in your own programs, but we will first use the examples provided by the python documentation:

  • print(all([])) - returns all items from a list (or other iterable), without necessarily creating any copies. It's like calling len() on a list and then getting its length.

  • print(any([])) - returns true if at least one item in a list satisfies some condition . For example, if you want to know whether there are any numbers greater than 10 inside [10], then it would be easier just to test each number one by one rather than doing this whole loop thingy....


You can use the all() function to print all of the elements in a list. For example, this will print all numbers in the range:

print(all([1, 2, 3]))

If you want to print only one element from the list, you can use an index:




The first line of code is the same as above, but in Python it looks for a false element. The algorithm looks for the first occurrence of a true element and, if none were found, returns False. Since the sequence is empty, there are no elements that can be true so this runs through and prints False

Explanation :

The first thing that you need to know about lazy operators is that they are lazy. This means that when we use them, we can only get the result at a later time. Here's an example:




```The first two lines print out all elements in their operands but do not return any values, because there are no true cases present in those expressions yet. If you were expecting a set or list of tuples as an answer from these expressions and wanted to see if an element existed before returning false, then it would work just fine with these operators -- but what if I told you there was another way?

"""Function all() is a little complicated,

"""Function all() is a little complicated, but you already know how it works.

It accepts one argument and returns a list containing the items in the reversed order. This can be useful for doing things like summing up numbers or sorting them by value. It's also useful for making sure that only unique values are present in your data structures (e.g., if you have an array of dictionaries and one of them contains duplicate keys).

The problem with this function is that it requires more memory than necessary because we don't need to keep track of what order our results will be returned in; they'll always be sorted automatically by Python when they come back from our function call! That means there's no reason not removing those extra elements from both sides before feeding them into any other operation such as filter().

since it represents the concept of vacuous truth.

Since it represents the concept of vacuous truth, the all() function returns True if all elements are true. The any() function returns True if any element is true.

Like with chained lazy logical operators,

If you're looking for the first non-false element, then all([]), like lazy operators, is a function that returns True when provided with any other value.

However, since there are no false elements in an empty sequence (and since Python doesn't have built-in logic to check for nulls), print(all([])) prints True:


the algorithm is to look for the first false element,

The algorithm is to look for the first false element and, if none were found, return True. If any element of the iterable is true, then return True.

The following code snippet demonstrates how this works in Python:

and if none were found then return True.

The if statement is one of the most useful features in Python. It allows you to check whether or not an element is true, and if none were found then return True.

The following code:

if x > 0 and y < 10:

yields this output: True

Since there are no false elements in an empty sequence, print(all([])) prints True.

Since there are no false elements in an empty sequence, print(all([])) prints True.

However, there is another way to achieve this effect: we can simply use the bool() function! The boolean value of x is true if x is equal to true or false (or any other value that Python determines as being truthy). Using this check for equality will return a boolean result when called on a list containing only one element.

In function any(), it will return True if any element of the iterable is true.

The function any() is the opposite of all(). It will return True if any element in the iterable is true.

If we pass an empty list, no elements will be returned by this function.

For example:

```python print(["Hello", "World"]) # [1] print([]).any() # True```

Logical operators in Python are lazy! The algorithm looks for the first

The first thing that you need to know about lazy operators in Python is that they are the ones that evaluate only when necessary.

The example above shows how logical operators work: the first one to be evaluated is any(), which evaluates to True and then all() evaluates to True, since there are no false elements in the list. If we had another list with three elements and processed it like this (using ** operator), we would have got an empty list back! You might have noticed another thing here—that's right, both operands must be lists!

occurrence of a true element and, if none were found, returns False,

The first true element is found, and if none were found, returns False.

If you have a list of lists , then this means that it's false for every single element in the list. This can be useful for testing whether a given value is true or false (or both). For example:

>>> L = [True, False] # create an empty list

>>> L[0].append(True) # append some values to the beginning of our original list

You'll get back True!

Since the sequence is empty, there are no elements that can be true,

Since the sequence is empty, there are no elements that can be true. So, all() evaluates its argument immediately and returns True.

On the other hand, any() evaluates its argument only when you call it. This means that if you call any() with a sequence containing an element that does not exist in your dataset (for example if we were to create an empty list), then it would return False since there is nothing else for it to consider as true or false.

therefore print(any([]))prints False."""

The truth is that print(any([]))prints False."""

The reason this works is because the equality operator == returns True if both operands are equal. Therefore, any() will return True only if all elements of the iterable are true. So when we pass an empty list to any(), it will return True and then print() will print out “False” in our console!


Python is a dynamic, interpreted language that encourages you to think as you code. It has an elegant syntax that is easy to learn, even for complete beginners. Although it has a reputation for being slow and complicated, Python’s simplicity and dynamic nature make it an ideal language for data science projects. You can use Python to explore machine learning techniques or build web apps from scratch without having any technical knowledge of programming languages like Java or C++!

Saturday 10 September 2022

Day 102 : Convert CSV to JSON


import pandas as pd

import csv,json



print("Converted JSON file below :")

print (json.dumps(list(csv.reader(open('Instagram.csv')))))

Impressions  Home  Hashtags  Explore  Other  Saves

0         3920  2586      1028      619     56     98

1         5394  2727      1838     1174     78    194

2         4021  2085      1188        0    533     41

3         4528  2700       621      932     73    172

Converted JSON file below :

[["Impressions", "Home", "Hashtags", "Explore", "Other", "Saves"], ["3920", "2586", "1028", "619", "56", "98"], ["5394", "2727", "1838", "1174", "78", "194"], ["4021", "2085", "1188", "0", "533", "41"], ["4528", "2700", "621", "932", "73", "172"]]

Day 100 : Python script that’ll keep you “online” all day


#import the library pyautogui

import pyautogui

#imports the time library

import time

#run the next lines of code while the state is set as “True”

while True:

    #move your cursor 10 pixels

    pyautogui.moveRel(0, 10)

    #pauses your code from running for 2 seconds


Day 99 : Word Art From an Image Using Python


#reading an Image

from PIL import Image"wolf.png")

import pywhatkit


#reading text file

read_file= open("MyArt.txt","r") 



Day 98 : Convert Decimal number into other number using Python


# Python program to convert decimal into other number systems

dec = int(input("Enter a Decimal Number: "))

#decimal to binary

print(bin(dec), "in Binary.")

#decimal to octal

print(oct(dec), "in Octal.")

#decimal to Hexadecimal

print(hex(dec), "in Hexadecimal.")

Enter a Decimal Number: 9999
0b10011100001111 in Binary.
0o23417 in Octal.
0x270f in Hexadecimal.

Friday 2 September 2022

Day 96 : Track phone number using Python


import phonenumbers

#import geocoder
from phonenumbers import geocoder

#specify then phone number
a = input("Enter the Phone Number: ")
phonenumber = phonenumbers.parse(a)

#display the location of phone number

Enter the Phone Number: +447894561236
United Kingdom

Tuesday 30 August 2022

Day 95 : Images To PDF conversion using Python


from PIL import Image

def Images_Pdf(filename, output):

    images = []

    for file in filename:

        im =

        im = im.convert('RGB')



        images[0].save(output, save_all=True, append_images=images[1:])

# Images Path , output pdf

Images_Pdf(["binod_mirror.png", "binod.png", "binod.jpg"], "output.pdf") 

Day 94 : Extract Text from Image using Python


pip install pytesseract

pip install pillow

from PIL import Image

from pytesseract import pytesseract

#Define path to tessaract.exe

path_to_tesseract = r'C:\Program Files\Tesseract-OCR\tesseract.exe'

#Define path to image

path_to_image = 'texttoimage.png'

#Point tessaract_cmd to tessaract.exe

pytesseract.tesseract_cmd = path_to_tesseract

#Open image with PIL

img =

#Extract text from image

text = pytesseract.image_to_string(img)


Day 93 : Generate Barcode using Python


pip install python-barcode

import barcode

from barcode.writer import ImageWriter


#Define content of the barcode as a string

number = input("Enter the code to generate barcode : ")

#Get the required barcode format

barcode_format = barcode.get_barcode_class('upc')

#Generate barcode and render as image

my_barcode = barcode_format(number, writer=ImageWriter())


#Save barcode as PNG"generated_barcode")

from PIL import Image #to open the barcde and show'generated_barcode.png')

Day 92 : Details about the Image in Python'binod.jpg') 

# The file format of the source file.

print(img.format) # Output: JPEG

# The pixel format used by the image. 

#Typical values are "1", "L", "RGB", or "CMYK."

print(img.mode) # Output: RGB

# Image size, in pixels.

print(img.size) # Output: (1920, 1280)

print(img.palette) # Output: None

(500, 271)

Friday 26 August 2022

Popular Posts


AI (27) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (120) C (77) C# (12) C++ (82) Course (64) Coursera (182) Cybersecurity (24) data management (11) Data Science (98) Data Strucures (6) Deep Learning (10) Django (6) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flutter (1) FPL (17) Google (19) Hadoop (3) HTML&CSS (46) IBM (25) IoT (1) IS (25) Java (92) Leet Code (4) Machine Learning (46) Meta (18) MICHIGAN (5) microsoft (4) Pandas (3) PHP (20) Projects (29) Python (772) Python Coding Challenge (256) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (40) UX Research (1) web application (8)


Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses