Friday, June 18, 2021
Home Technology Features of Python

Features of Python

These days I was reading Python documentation just in my free time for fun and information. While you examine something for enjoyment, you have a tendency to observe thrilling tidbits that you could have overlooked otherwise. So, right here is some of the info that made me pass after reading this your expression should be “can I do that in python?”->Features of Python.

1. For-else loop

In Features of Python, you could add an else clause to a for loop. The else clause might be triggered simplest if no break statement was encountered in the body of the loop throughout execution.

my_list = ['this', 'list', 'consist', 'five', 'elements']

min_len = 3

for element in my_list:
    if len(element) < min_len:
        print(f'Find an element less than {min_len} characters')
    print(f'All elements at least {min_len} letters long').
All elements at least 3 letters long

Note that the else is indented at the extent of for and not at the extent of if. here, no element has length shorter than three. So, the break statement will in no way be encountered. For this reason, the else clause gets triggered (after the for loop is accomplished) and prints the output shown above.

One could argue that this will be accomplished through the use of a separate variable that maintains track of whether or not the break statement turned into encountered. And possibly it’d additionally be less complicated for the next character reading the code. Nonetheless, it’s good to realize, I guess.

2.Separators for “int”

It’s difficult to differentiate visually between integers like 10000000 and 100000000 (are they even extraordinary numbers?). We will use commas here in Python as we use them in English due to the fact Python will interpret it as a tuple of a couple of integers.

Features of Python has a completely handy way of handling this: we can use underscore as a separator to enhance clarity. As a result, 1_000_000 may be interpreted as a single int.

a = 3250
b = 67_543_423_778

<class 'int'>
<class 'int'>

3. Function Attributes

Much like how you can set attributes of classes and objects, you may additionally set attributes to features.

def func(x):
    intermediate_var = x**2 + x + 1

    if intermediate_var % 2:
        y = intermediate_var ** 3
        y = intermediate_var **3 + 1

    # setting attributes here
    func.optional_return = intermediate_var
    func.is_wow = 'Yes, my function is Wow.'

    return y

y = func(3)
print('Final answer is', y)

# Accessing function attributes
print('Show calculated -->', func.optional_return)
print('Is my function wow? -->', func.is_wow)

We have set the attributes ‘optional_return’ and ‘is_awesome’. We’ve got access to the attributes of the one outside of the function later. The output of the code might be:

Final answer is 2197
Show calculated --> 13
Is my function wow? --> Yes, my function is wow.

This is available in reachable while you need the option to retrieve a few intermediate variables, however, no longer explicitly go back it with the return declaration every time the function is called. Additionally, notice that attributes may be set from within the characteristic definition or from out of doors the function definition.

4. eval() and exec() Functions

Features of Python has the potential to dynamically study a string and deal with it like a piece of Python code. this is achieved using eval() and exec() capabilities (‘eval’ is for comparing expressions and ‘exec’ is for executing statements).

a = 3

b = eval('a + 2')
print('b =', b)

exec('c = a ** 2')
print('c is', c)
b = 5
c is 9

The eval() function will study the entered string as a Python expression, evaluate it, and assign the end result to the variable ‘b’. The exec() function will read the input string as a Python statement and execute it.

You may even bypass dynamically created strings to these functions. You may, for example, create 1000 variables with names x_0, x_1, …, x_999 while not having to put in writing each of these variable declarations manually for your code. This could seem like it’s a very pointless function, however, it’s not.

  • In the broader context of programming in popular, now not just Python, using eval/exec is particularly effective because it permits you to put in writing dynamic code that makes use of data to be had at runtime to solve troubles that cannot even be expressed at compile time. […] exec is actually a Python interpreter embedded inside Python, so if you have a particularly difficult problem to resolve, one of the methods you can resolve it is to put in writing a program to write a program to resolve it, then use exec to run that 2d program.

You can read more of this beautiful explanation by Steven D’Aprano.

5. Ellipsis

Ellipsis or ‘…’ is a consistent of Python just like constants like None, authentic, fake, etc. It is able to be used in special ways together with, but now not limited to:

5.1 Placeholder for unwritten code

Much like pass, Ellipsis can be used as a placeholder when the code isn’t always fully written but calls for a few placeholders for syntactic accuracy.

def some_function():
def another_function():

5.2 alternative to ‘None’

None is the standard desire while one desires to denote an empty input or go back. But sometimes None may be one of the anticipated built puts or returns of a function. Built-in so Ellipsis can function as the placeholder.

# calculate nth odd number
def nth_odd(n):
    if isinstance(n, int):
        return 2 * n - 1
        return None

# calculate the original n of nth odd number
def original_num(m=...):
    if m is ...:
        print('This function needs some input')
    elif m is None:
        print('Non integer input provided to nth_odd() function')
    elif isinstance(m, int):
        if m % 2:
            print(f'{m} is {int((m + 1)/2)}th odd number')
            print(f'{m} is not an odd number')


a = nth_odd(n='some string')

b = nth_odd(5)


The characteristic nth_odd() calculates the nth odd wide variety, given n. The function original_num() calculates the unique variety n, given the nth odd number. right here, None is one of the anticipated built puts to the function original_num() so we are able to use it because of the default placeholder for the argument m. The output of the code could be:

This function needs some input
Non integer input provided to nth_odd() function
9 is 5th odd number
16 is not an odd number

5.3 Array slicing built-in NumPy

NumPy makes use of Ellipsis to slice an array. Integrated code shows built equal methods of built-integrated a NumPy array:

import numpy as np

a = np.arange(16).reshape(2,2,2,2)

print(a[..., 0].flatten())
print(a[:, :, :, 0].flatten())
[ 0 2 4 6 8 10 12 14]
[ 0 2 4 6 8 10 12 14]

Thus, ‘…’ signifies that there are as many ‘:’s as needed.

Boolean cost of Ellipsis

In contrast to None (whose Boolean values are fake), the Boolean price of Ellipsis is taken to be true. Features of Python


Sign In with Apple is a must for iPhone users. Here’s how to SignIn

If you have an iPhone, you will be acquainted with sign up with Apple -- a privateness tool that gives iOS customers...

11 Visual Studio Code Extensions Every Web Developer Should Use

Almost every web developer is aware of what Visual Studio Code Extensions is and why is it so important to apply for...

How to change your IP address: 4 easy ways

Do not worry. How to change your IP address is easy, even if you've never executed it earlier than. It's also perfectly...

What is the Fastest best VPNs of 2021

You're binging Netflix. you're working from domestic, you're listening to Spotify, you are gaming -- and chances are in case you're analyzing...

7 hidden gmail tips and trick features that help you to get inbox 0

Get a better handle on your Gmail inbox with these must-have tips and tricks that will turn you into an email...


Please enter your comment!
Please enter your name here

Most Popular

Is Skipping Breakfast Bad for You? The Surprising Truth

Breakfast is perceived as healthy, even more, vital than different food. Even these days’ respectable nutrients tips recommend that...

Reasons Why You’re Not Hungry in the Morning

We’ve all heard that breakfast is the maximum essential meal of the day. But simply because this is a popular announcing doesn’t...

20 Easy Ways to Reduce Your Food Waste

In reality, almost 1/3 of all food produced within the international is discarded or wasted for various motives. Food waste equates to...

Sign In with Apple is a must for iPhone users. Here’s how to SignIn

If you have an iPhone, you will be acquainted with sign up with Apple -- a privateness tool that gives iOS customers...