Techno Blender
Digitally Yours.

5 Awesome Python Hidden Features. Take your coding skills to the next… | by David Farrugia | Mar, 2023

0 33


PYTHON | PROGRAMMING | FEATURES

Take your coding skills to the next 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 1 spot for the most popular programming language in 2022.

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

Python is versatile. Thanks to the large and active Python community, Python benefits from robust packages and frameworks tackling virtually any development needs.

Want to write up an API? You can use Python.

Want to build a game? Python has you covered.

Want to wrangle some data and train machine learning models? You bet. Python has the right tools for you!

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

In this article, we will go over 5 cool Python tricks that you can use to impress your co-workers 😜

One of the first things we learn when getting started 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. In the if block we check for some logic. If this logical condition is not met, we execute the code defined in the else block. This is all common knowledge.

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

How is this useful, you might ask?

Suppose we have a list of numbers. We want to write logic that determines whether or not any single number in the tuple is an even number.

Traditionally, we might 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 indicate if an even number was found
found_even: bool = False

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

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

This logic is relatively straightforward. We use a flag (in this case, the found_even variable) to signify whether or not we found an even number. If during the iteration process we do find an even number, we use the break keyword to stop loop execution.

The above can 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 no longer require the flag variable found_even. We can use the else keyword to only print “No even numbers found” if the break keyword is never reached during 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 following example. We want to implement logic that generates a sequence of random numbers until a specific number is generated. Suppose we are 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 will only be executed if we get a 10 and break the loop
print("We got a 10!")

In our loop, we are generating a random number and storing it in a variable rand. The number of iterations are based on the value of the rand variable. The sooner that rand becomes equal to 10, the sooner we will break the loop.

Now, using the walrus operator, we can obtain the same functionality using the below code:

import random

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

print("We got a 10!")

Here, we tell Python that we want our while loop to run while the value of rand is not equal to 10. We also tell it that the rand will get its value from random.randint(1, 100) with every new iteration.

The ellipsis (i.e., ...) is an interesting keyword and rather useful during the early development stages. When dealing with complex logic, the best 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 implementing these smaller functions first and then tie everything together.

However, we sometimes (for various reasons) want to define the function but write its code later on. The ellipsis allows us to do just that!

Let us see how.

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

# we can use it anywhere we like
some_list = [1, 2, 3, ...]

The above code won’t fail even though the function some_function defines no code. We can even call the function and it still would not fail (of course, it would not return anything either).

In Python, any function is stored as an object. Any object can have attributes. Therefore, in Python, functions can also have attributes.

We can use function attributes to define additional information about the function and other metadata. For example, suppose we want to keep track of how many times a specific function is called. We can 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)

Another interesting use-case of function attributes is to set an is_verbose attribute to switch between printing extra information or not. This is often done by passing an extra parameter to the function. With function attributes, we would no longer require the extra parameter.

Another good example is to display the function’s docstring.

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

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

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

There are numerous uses for function attributes. You can read more about them here:

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

Consider the below example:

x = 5
y = 10

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

print(result)

We can obtain the same functionality using the ternary operator syntax as follows:

x = 5
y = 10

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

print(result)


PYTHON | PROGRAMMING | FEATURES

Take your coding skills to the next 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 1 spot for the most popular programming language in 2022.

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

Python is versatile. Thanks to the large and active Python community, Python benefits from robust packages and frameworks tackling virtually any development needs.

Want to write up an API? You can use Python.

Want to build a game? Python has you covered.

Want to wrangle some data and train machine learning models? You bet. Python has the right tools for you!

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

In this article, we will go over 5 cool Python tricks that you can use to impress your co-workers 😜

One of the first things we learn when getting started 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. In the if block we check for some logic. If this logical condition is not met, we execute the code defined in the else block. This is all common knowledge.

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

How is this useful, you might ask?

Suppose we have a list of numbers. We want to write logic that determines whether or not any single number in the tuple is an even number.

Traditionally, we might 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 indicate if an even number was found
found_even: bool = False

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

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

This logic is relatively straightforward. We use a flag (in this case, the found_even variable) to signify whether or not we found an even number. If during the iteration process we do find an even number, we use the break keyword to stop loop execution.

The above can 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 no longer require the flag variable found_even. We can use the else keyword to only print “No even numbers found” if the break keyword is never reached during 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 following example. We want to implement logic that generates a sequence of random numbers until a specific number is generated. Suppose we are 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 will only be executed if we get a 10 and break the loop
print("We got a 10!")

In our loop, we are generating a random number and storing it in a variable rand. The number of iterations are based on the value of the rand variable. The sooner that rand becomes equal to 10, the sooner we will break the loop.

Now, using the walrus operator, we can obtain the same functionality using the below code:

import random

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

print("We got a 10!")

Here, we tell Python that we want our while loop to run while the value of rand is not equal to 10. We also tell it that the rand will get its value from random.randint(1, 100) with every new iteration.

The ellipsis (i.e., ...) is an interesting keyword and rather useful during the early development stages. When dealing with complex logic, the best 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 implementing these smaller functions first and then tie everything together.

However, we sometimes (for various reasons) want to define the function but write its code later on. The ellipsis allows us to do just that!

Let us see how.

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

# we can use it anywhere we like
some_list = [1, 2, 3, ...]

The above code won’t fail even though the function some_function defines no code. We can even call the function and it still would not fail (of course, it would not return anything either).

In Python, any function is stored as an object. Any object can have attributes. Therefore, in Python, functions can also have attributes.

We can use function attributes to define additional information about the function and other metadata. For example, suppose we want to keep track of how many times a specific function is called. We can 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)

Another interesting use-case of function attributes is to set an is_verbose attribute to switch between printing extra information or not. This is often done by passing an extra parameter to the function. With function attributes, we would no longer require the extra parameter.

Another good example is to display the function’s docstring.

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

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

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

There are numerous uses for function attributes. You can read more about them here:

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

Consider the below example:

x = 5
y = 10

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

print(result)

We can obtain the same functionality using the ternary operator syntax as follows:

x = 5
y = 10

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

print(result)

FOLLOW US ON GOOGLE NEWS

Read original article here

Denial of responsibility! Techno Blender is an automatic aggregator of the all world’s media. In each content, the hyperlink to the primary source is specified. All trademarks belong to their rightful owners, all materials to their authors. If you are the owner of the content and do not want us to publish your materials, please contact us by email – [email protected]. The content will be deleted within 24 hours.
Leave a comment