Home Artificial Intelligence 5 Awesome Python Hidden Features Hidden Feature 1: Using ELSE with FOR and WHILE loops Hidden Feature 2: The Walrus Operator Hidden Feature 3: Ellipsis Hidden Feature 4: Function Attributes Hidden Feature 5: Ternary Operator Concluding Remarks Wish to Get in Touch?

5 Awesome Python Hidden Features Hidden Feature 1: Using ELSE with FOR and WHILE loops Hidden Feature 2: The Walrus Operator Hidden Feature 3: Ellipsis Hidden Feature 4: Function Attributes Hidden Feature 5: Ternary Operator Concluding Remarks Wish to Get in Touch?

2
5 Awesome Python Hidden Features
Hidden Feature 1: Using ELSE with FOR and WHILE loops
Hidden Feature 2: The Walrus Operator
Hidden Feature 3: Ellipsis
Hidden Feature 4: Function Attributes
Hidden Feature 5: Ternary Operator
Concluding Remarks
Wish to Get in Touch?

PYTHON | PROGRAMMING | FEATURES

Take your coding skills to the subsequent level with these cool hidden Python features

Photo by Emile Perron on Unsplash

Python is a marvellous programming language.

Stack Overflow’s Developer Survey 2022 placed Python in the number one spot for the preferred programming language in 2022.

Python is incredibly beginner-friendly. Its syntax is easy and simple to grasp — significantly smoothing the training curve.

Python is flexible. Due to the big and lively Python community, Python advantages from robust packages and frameworks tackling virtually any development needs.

W You need to use Python.

W Python has you covered.

W You bet. Python has the precise tools for you!

Python also has a bunch of tricks up its sleeve. I consistently find myself impressed by all of the Python one-liners that solve a fancy task beautifully!

In this text, we’ll go over 5 cool Python tricks which you can use to impress your co-workers 😜

Considered one of the primary things we learn when getting began with programming is conditional statements (i.e., if-else blocks). These conditional statements allow us to divert the code flow based on some variable value. Within the if block we check for some logic. If this logical condition shouldn’t be met, we execute the code defined within the else block. That is all common knowledge.

But, we can even use the else keyword with any for or while loop. The functionality of the else on this setting becomes simply to execute code if the loop finished successfully without hitting any break statements.

How is this convenient, you may ask?

Suppose now we have a listing of numbers. We would like to write down logic that determines whether or not any single number within the tuple is a fair number.

Traditionally, we’d write something like:

# we define our numbers list
numbers: list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# we also define a flag variable to point if a fair number was found
found_even: bool = False

for num in numbers:
# if number modulus 2 is 0, then it's even
if num % 2 == 0:
print(f"{num} is even")
# we set our flag to True because we found a fair number
found_even = True
# we are able to stop execution because we found a fair number
break

# if the flag is False, no even numbers where found
if not found_even:
print("No even numbers found")

This logic is comparatively straightforward. We use a flag (on this case, the found_even variable) to indicate whether or not we found a fair number. If through the iteration process we do find a fair number, we use the break keyword to stop loop execution.

The above may also be written as follows:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for num in numbers:
if num % 2 == 0:
print(f"{num} is even")
break
else:
print("No even numbers found")

We now not require the flag variable found_even. We are able to use the else keyword to only print “No even numbers found” if the break keyword is rarely reached through the loop iteration process.

The walrus operator (:=) was introduced in Python 3.8. We use the walrus operator to assign variables with values as an expression.

Consider the next example. We would like to implement logic that generates a sequence of random numbers until a particular number is generated. Suppose we’re after getting my favourite number: 10. We typically write something like:

import random

rand = None
while True:
# generate a random number between 1 and 100
rand = random.randint(1, 100)
# if the random number is 10, break the execution
if rand != 10:
print(rand)
else:
break

# this can only be executed if we get a ten and break the loop
print("We got a ten!")

In our loop, we’re generating a random number and storing it in a variable rand. The variety of iterations are based on the worth of the rand variable. The earlier that rand becomes equal to 10, the earlier we’ll break the loop.

Now, using the walrus operator, we are able to obtain the identical functionality using the below code:

import random

while (rand := random.randint(1, 100)) != 10:
print(rand)

print("We got a ten!")

Here, we tell Python that we wish our while loop to run while the worth of rand shouldn’t be equal to 10. We also tell it that the rand will get its value from random.randint(1, 100) with every recent iteration.

The ellipsis (i.e., ...) is an interesting keyword and somewhat useful through the early development stages. When coping with complex logic, the perfect strategy is to divide and conquer — split the complex logic into its smaller and easier to implement constituents. Often times, this requires us to start out implementing these smaller functions first after which tie the whole lot together.

Nevertheless, we sometimes (for various reasons) wish to define the function but write its code in a while. The ellipsis allows us to do exactly that!

Allow us to see how.

def some_function(x, y, z):
# do something with x, y, z
...

# we are able to use it anywhere we like
some_list = [1, 2, 3, ...]

The above code won’t fail although the function some_function defines no code. We are able to even call the function and it still wouldn’t fail (after all, it could not return anything either).

In Python, any function is stored as an object. Any object can have attributes. Due to this fact, in Python, functions can even have attributes.

We are able to use function attributes to define additional information concerning the function and other metadata. For instance, suppose we wish to maintain track of how again and again a particular function is named. We are able to set a counter attribute that we increment after every call.

def my_function(x):
return x * 2

my_function.counter = 0
my_function.counter += 1
print(my_function.counter)

One other interesting use-case of function attributes is to set an is_verbose attribute to change between printing extra information or not. This is usually done by passing an additional parameter to the function. With function attributes, we’d not require the additional parameter.

One other good example is to display the function’s docstring.

def my_function(x):
"""It is a docstring for my_function."""
return x * 2

print(my_function.__name__)
print(my_function.__doc__)

By calling the attribute __name__, we’re instructing Python to print the function’s name. The __doc__, in turn, prints the function’s docstring.

There are many uses for function attributes. You may read more about them here:

The ternary operator in Python is a option to define an if-else statement as a one-liner.

Consider the below example:

x = 5
y = 10

if x > y:
result: str = "x is larger than y"
else:
result: str = "y is larger than or equal to x"

print(result)

We are able to obtain the identical functionality using the ternary operator syntax as follows:

x = 5
y = 10

result = "x is larger than y" if x > y else "y is larger than or equal to x"

print(result)

2 COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here