Listado de la etiqueta: Python


“The interpretation of command line arguments has been made by the use of the Python module argparse. By providing user input elements to be processed, argparse would be used to give customization and reuse of the program in place of explicitly specifying variables within the function.”

Command Line Interface

A method to negotiate with a command line script would be through the command line interface or CLI. Although Python has several modules which we may use to construct command line interfaces for different scripts, the Python argparse package is now the efficient method for doing so.

The argparse module for Python was made available as a component of the standard framework. It is the preferred method for creating a Python Interface. The earlier “getopt” and “optparse” libraries were replaced with this one as they lacked several crucial functionalities.

Uses of Argparse Module

These are the uses of the Python argparse module:

    • Provides different units of arguments for a single item.
    • Supports the utilization of positional parameters.
    • Allow intermediate for subcommands.
    • Enable modification of the prefix elements.

Based on certain parameters, a primary command line parser may utilize additional command line parsers.

Utilization of a Command Line Interface

Now that we are aware of what a command line interface is, we might be concerned as to when it would be appropriate to incorporate it into the program. The común rule is that we will think about a command line interface if we decide to offer a user-friendly method of customizing the project.

The suitable technique is to use the Python argparse module. It is a great way to handle the value by constructing a command line interface using the Python argparse module unless we are constructing a complicated command line script that requires a configuration file to function. This way can let the user designate whose configuration file to be using.

How to Construct a Command Line Interface by Using Python Argparse Package

There are 4 phases to using the Python argparse module:

    • Include the argparse framework in Python.
    • Construct the parser.
    • Provide the parser with optional and positional parameters.
    • Run parse_args() function.

A User-defined object with a basic attribute for every input parameter obtained from the command line is what we can get after calling the parse_args() method.

Let’s execute different examples in which we utilize the argparse module.

Example no 1

An efficient interface for processing command line parameters is provided by the argparse tool. It shows the program’s común usage, instruction, and exceptions. The use of appropriate command line parameters is demonstrated in the succeeding illustration.

This example computes the circle’s area using a one-parameter radius from the command line. To add parameters and analyze them, the ArgumentParser object parser has been constructed. A radius parameter is added by the user, although it is left as an optional parameter. The method would not return an exception and set the parameter’s value to None if the user will not give a value for it, as seen in the scenario below.

import argparse

parser = argparse.ArgumentParser(description = ‘Find the radius of any given circle’)

parser.add_argument(‘-r’,‘–radius’, type = int, help=‘Calculated radius of any given circle’)
args = parser.parse_args()

def main():
    print(args.radius)
main()

 

At the start of the program, we will import the header file “argparse”. In the next step, we will initialize a variable “parser”, and at the same time, we will call the argumentpraser() method. This function is related to the argparse module. We have given the “description” as the parameter of the argumentpraser() function. Then we add different parameters so we utilize the function add_argument() function. This function has three parameters which include the radius of the circle, the data type of the radius, and the value of the “help” argument.

After specifying the arguments, we will invoke the function parse_args() of the parser package. Now let’s define the body of the main() method. Within this function, we have been using the function print() to display the radius of the given circle. In the end, we utilize the main() method.

Example no 2

The “required” is an argument of the add_argument() method of the ArgumentParser object. Parameters of the attribute “f” or “foo” are unnecessary and, therefore, will be eliminated by default. The parameter “required” need can be set to True if the user wants to insert this parameter. As shown below, whenever we set an attribute as “required” but do not specify a value for this, the compiler returns an exception.

import argparse

parser = argparse.ArgumentParser(description = ‘Determine radius of any circle’, prog = ‘The program’, usage = ‘%(prog)s [options]’)
parser.add_argument(‘-r’,‘–radius’, type = int, required = True, help=‘Calculated radius of any given circle’)
args = parser.parse_args()
def main():
    print(args.radius)
main()

 

First of all, we are going to integrate the module “argparse”. The following step involves initializing the variable “parser” and applying the argumentparser() method simultaneously. This method is associated with the argparse package. The arguments for the argumentparser() method are description and prog.

Next, we add some additional parameters by using the add_argument() method. The radius of the circle, the radius’s data type, and the value of the “help” parameter are the four arguments for this function. We set the value of the “required” parameter to “True”.

In addition to this, we will call the method parse_args() of the parser header file after providing the arguments. Then we will define the main() function’s body. The print() method has been used here in the body of the main function to show the radius of the circle. We finally use the main() function.

Conclusion

By completing this article, we now comprehend a command line interface and the method of constructing a single command line argument using the argparse package. We also discussed what the Python argparse module is and why users will utilize it if they have to generate command line Python code. How and when to efficiently build a basic Interface using the argparse framework. We also observed the innovative use of the argparse module. An effective command line interface can provide users with a mechanism to engage with their system.



Source link


“We need to employ a lot of modules while creating Python apps for various functionalities. The number of modules a given application uses can be considerable. Generally, it is advised to create a posible environment tailored to the project when developing such massive programs, as well as smaller ones, because doing so enables us to install anything we want and of any version without overburdening the available package space.

The script and dependencies must be installed on the user’s computers for them to utilize the developer. Because the dependencies are set up in a posible environment, it would be useless to share the entire posible environment because the folder size would be enormous, and there would be a risk of integrity problems.

When this occurs, programmers include a requirements.txt file in the project that contains a list of all the dependencies that have been installed in the posible environment as well as information on the version that is being utilized. To utilize the program, the borrower or end-user merely needs to set up a posible environment and install any necessary components. This post will explain how to create the requirements.txt file and install dependencies using it.”

Definition of requirement.txt File in Python

During the development of a specific project, libraries, packages, and modules are typically listed in a requirement.txt file, a type of file in Python. It also keeps track of all the files and programs needed for the project to function or on which it depends. In most cases, your project’s root directory is where the file “requirement.txt” is kept (or is located). The reason why we require this kind of file in our projects is raised here, which is yet another crucial question.

Importance of requirement.txt File in Python

As it resolves nearly all compatibility difficulties, it benefits us in several ways, even when we return our project in the future. If you’ve ever written a project in Python or worked on one, you know that we typically need many packages. However, whenever we worked on a project, we frequently used a certain version of the packages.

Later, the maintainer or package manager might make certain adjustments, and those changes could easily damage your entire application. Consequently, keeping track of each package change would take a lot of time. To avoid unpleasant surprises, it’s critical to keep a record of every package we use when the project is excessively large.

Utilizing a posible environment is one of the common strategies for dealing with this kind of problem. Since we typically do not need all of these package types while focusing on a particular project, it is important to recognize which one is necessary for each project in order to facilitate reproducibility. There are two primary types of modules and places where Python modules are typically stored.

The following files are typically involved:

    • The Standard Python Library’s System Packages are a component of it.
    • Site packages, often known as third-party packages, which you install with pip.

Posible Environment for the requirement.txt File in Python

The user’s packages are kept apart from the regional (or main) system installation in a posible environment, which is a kind of químico or separated workspace. It enables us to build an isolated, “posible” environment for all Python schemes. This makes it simpler for each project to operate independently of the others, particularly when they have similar requirements. A posible environment can be created using a variety of packages that are accessible. First, make all right that python and pip are mounted on your system.

>Python –version
>Pip –version

 

Install virtualenv

Let’s now explore how to install the modules and libraries after the posible environment for our project has been constructed. With the posible environment, obtaining all the necessary packages for our project is really simple. Let’s examine how to use “virtualenv.”

It is a particular kind of library that enables the creation and use of posible environments. You can adhere to the directions provided to install the virtualenv. To install virtualenv, launch the shell prompt on your computer and enter the subsequent command.

>> Pip install virtualdev

 

Building the Directory for a New Project

Now, in order to prevent unneeded problems, build a new posible environment within the directory of that project by giving the following command in prompt command.

>> Python –m venv name_of_environment

 

We only need to activate it at this point in order to use the newly generated posible environment. The following command must be entered, and the enter key must be pressed to enable this isolated environment.

>name_of_environmentScriptsactivate

 

We have titled our posible environment “name _of_environment” in our example, so you can check that it has been formed by looking at the prompt to see that the prefix has been updated. Additionally, you may confirm it by navigating to the project folder or the directory where the relatively new directory with the provided name will be created.

Creating the requirement.txt File With the Python Path

It will be helpful to know its contents before creating the requirement.txt file. A requirement.txt file lists every type of standard package and library that is utilized in that specific project. Therefore, while creating any project, no matter how big or small, this requirement.txt file. Our projects become more transportable as a result of it. Several significant issues can be easily avoided with the “requirement.txt” file’s assistance. We can obtain the requirements.txt file from this location. We may use the next command to make the requirement.txt file:

>> Pip freeze > requirements.txt
>> requirements.txt

 

The requirement.txt file opens as the following image is displayed.

Conclusion

Here, we have concluded our article that the requirement.txt file is crucial because it will be used whenever a new user runs the code they downloaded from internet platforms on their PC. There is no necessity for the requirements.txt file name to appear in this file. Use dependencies.txt or another file if you choose. However, requirements.txt is the name given to this file most frequently in conventional development practice.



Source link


In addition to the tools used to effectively loop through data known as Itertools, Python offers its users many important operations and structures that facilitate a simpler dealing with the data. A for-loop-steppable data structure can be iterated over using the Python library called Itertools. Iterator algebra is created using this module as a quick, memory-efficient technique, either alone or in combination. This module includes features that make the optimal use of computing resources.

Additionally, using this module tends to make the code easier to read and maintain. Itertools is a built-in package in Python that enables us to manage the iterators effectively. They simplify the process of iterating across iterables like lists and strings. The Islice() is one such Itertools feature. This section is devoted to the islice approach in its entirety.

Syntax of the Itertools.Islice() Function in Python

The Itertools library’s “islice()” function extracts a segment from an iterable object between the elements specified by the function’s start and end arguments. It accepts an iterable object as input. The following is the normal syntax of the itertools.islice() function in Python:

itertools.islice(iterable, start, stop, step)

 
The functionality of the parameters specified in the itertools.islice() function is discussed in the following:

Iterables: Iterables are objects that produce iterators. Lists, tuples, strings, and dictionaries are some examples of common Python iterables.

Start: Start value establishes the location to start slicing from; examples of natural numbers are 0, 1, 2, 3, and so on.

Stop: Stop value establishes the place at which the slice ends; it slices up to the given number (exclusively). It may also be a natural number.

Step: Step describes the value’s increase or decrease.

The islice method of Itertools returns an iterator that, upon iteration or traversal, returns the individual values. Although the start, stop, and step values for the slice method can all be negative, this is not acceptable for the islice function which yields a ValueError.

Example 1: Program of Using the Itertools.Islice() Function with the Stop Parameter

We simply explained the working of the itertools.islice() function. The stop parameter is a single value given together with the iterable.

import itertools
 
i = itertools.islice(range(12), 5)
for values in i:
    print(values)

 

As already discussed, the islice() function is provided by the itertools module in Python. So, we have to include this module while deploying the islice() function. Here, we first added the itertools with the import keyword. Then, we defined a variable “i” to which we assigned the itertools.islice() function. The itertools.islice() function takes the range method as an input. The range value is also defined in the range method.

After that, we passed the stop parameter value to the islice function. The for loop is used to cycle over each value in the variable “i” and assigned to the new variable – “value”. The print method generates the result obtained from the “values” variable.

The outcome we have from the previous Python script is as follows:

Example 2: Program of Using the Itertools.Islice() Function with the Start and Stop Parameter

Here, we introduced another example of the itertools.islice() function. This time, the itertools.islice function takes the two parameters which are the start and stop parameters.

import itertools
 
iterate = itertools.islice(range(9), 0, 7)
for element in iterate:
    print(element)

 

We started our Python script by importing the module Itertools for utilizing the islice() function. Then, we established a variable with the name given as “iterate”. To the variable iterates, we have given an itertool.islice() function where the range method sets the range value and the start and the stop parameters value are assigned. The slicing takes place from the 0 starting index and stops at index 7 as we passed these values inside the function.

Then, we cycled the loop over each value in the iterating variable provided by the itertools.islice() function with the help of the for loop. We printed the results using a print statement.

The following is the result generated from the islice function with the start and stop index:

Example 3: Program of Using the Itertools.Islice() Function with the Step Parameter

As in the aforementioned illustrations, we passed the start and stop index values to the itertools.islice() function. Now, we have another parameter called the step parameter. We can also pass this step parameter along with the start and the stop index values. Let us implement the step parameter in the subsequent example:

from itertools import islice
x = islice(range(15), 2, 8, 1)
for item in x:
    print(item)

 

There, we introduced another technique to import the islice package from the Python Itertools as you can see in the script implementation. After importing the module of islice, we generated the variable as x. The variable is called the itertools.islice() function and sets the range value with the range method. Also, the itertools.islice() function sets the start index value, the step-index value, and the stop index value. Through the loop, we examined each value provided by the itertools.islice() function and printed the results.

The previous Python script generates the subsequent output:

Example 4: Program of Using the Itertools.Islice() Function to the List

Using the list() function, the iterator can be converted very efficiently. Let us discuss this with the following example code:

import itertools

sliced_value = itertools.islice(range(50), 0, 51, 2)
sliced_List = list(sliced_value)
print(sliced_List)

 

We first included the Itertools module in our script. Then, we have a variable “sliced_value” to which the itertools.islice() function is assigned. The itertools.islice() function takes the range method with the start, step, and stop values as an input. We created another variable “slice_List” where we have to invoke the list method. To the list method, the variable “slice_value” is passed as an input. This converts the islice value to the list values.

You can see that the list is generated in the following output:

Conclusion

The islice() method is discussed in this guide which is provided by the Itertools module of Python. The islice() technique uses an iterator to cycle over a list without requiring a memory because the elements are created as needed. It is a built-in function that you will use frequently to subsequence other sequences, and it frequently pairs with the various functions mentioned in the tutorial.



Source link


We cover the combinations() function by utilizing the Itertools. However, it is crucial to comprehend its utilization before delving further into the topic. Let’s first have a look at it. We frequently experience combinations or permutations when performing different calculations. But even though we may compute numbers, dealing with large values would be challenging sometimes. Think about what might occur if we had tools that could make this determination for users.

Itertools Package

Our requirements are precisely fulfilled by the Itertools package. Its reach extends beyond that, though. It offers additional methods that facilitate the other predefined operations as well. But this package is categorized into three types namely: Infinite Iterators, Combinatorics Iterators. and Terminating Iterators.

We would only discuss the combinations() function because this module is too important to describe in its entirety at this point. While proceeding, let’s look at how to deploy it, how to integrate it, and see what the combinations include.

Installation

Since this approach is built into Python, there is no installation procedure needed. Before utilizing it, we must integrate it. The following command could be used to accomplish it:

 

Definition of Combinations

When we think about combinations, we may define them as a method of organizing a group of objects. The order of the components in combinations is unimportant, therefore “xy” works similarly to “yx”.

Combinations() Method

The particular function is a component of the Itertools package’s combinatorics classification. This group includes the additional functions like products() and permutations(). The combinations() function, on the other hand, usually deals with every combination that could be feasible for the provided data collection.

To be more precise, the suggested method displays every unique data combination without any substitution. However, we may utilize the combinations_with_replacement() approach to display every combination with substitution. We must provide the parameters in proper order in both situations. Now, we will discuss how to utilize the combinations() method in Python.

Example 1:

By using the combinations() method, we will demonstrate the set of two-word combinations that are available with the letter “information” in this instance.

from itertools import combinations
 
str = ‘information’
a = len(str)
print(a)
 
combination = combinations(str,2)
 
x = [‘ ‘.join(j) for j in combination]
print(x)
print(len(x))

 

To start the code, we integrate the “combinations” package from the “itertools” framework. Now, we define the word “information” and that word is stored in “str” variable. We call the len() method to find the length of the specified letter. Then, we print the length of that letter. Using the word “information”, we have to obtain every possible combination. So, we apply the combination() function. We choose the number “2” to stand in for the total number of values in the set. We then call the join() function in the following step.

Along with this, we also utilize the “for” loop to obtain all the possible combinations of the defined word. To hold the possible combinations, we must define a variable “x”. Now, the print() function is used to display those combinations. Lastly, we find the total number of combinations with the help of the len() method and that length is shown by using the print() function.


Since we didn’t sort the letters in the previous instance, the defined string contains the letters in a lexicographical manner.

Example 2:

We will observe from the outcome of the preceding instance that the letters were not changed during the arrangement. We also have an option of replacement setups. The combinations_with_replacement() technique allows us to accomplish that. Here’s an illustration:

from itertools import combinations, combinations_with_replacement
 
w = ‘badminton’
m = len(w)
print(m)
 
combination = combinations_with_replacement(w,3)
 
c = [‘ ‘.join(l) for l in combination]
print(c)
print(len(c))

 

The “combinations” and “combinations with replacement” libraries from the “itertools” framework must be incorporated before we can start coding. Now, we specify the term “badminton” which is maintained in the variable “w.” To determine the length of the provided word, we utilize the len() function. Then, we show how long that letter was. We just want to identify every feasible combination using the word “information”.

In order to do this, we call the function combination with replacement(). The number of items we wish to include in the set is specified as “3”.We use the join() method in the following step. In addition, we use the “for” loop to get every possible combination of the specified term. To retain the possible combinations, an attribute called “c” has to be declared.

Now, the combinations are presented by using the print() method. In the final step, we use the len() function to calculate the total number of combinations and the print() method is used to display that length.

Example 3:

We probably need to retrieve the combinations from the Pandas dataframes. The lambda method will be used to accomplish it. Let’s look at the following scenario:

import pandas as pd
from itertools import combinations
 
d_f = pd.DataFrame({‘subj1’:(‘x’,‘z’), ‘subj2’: (‘i’,‘j’), ‘subj3’: (‘r’, ‘s’),  ‘subj4’: (‘a’, ‘e’)})
 
d_f[‘combinations’] = d_f.apply(lambda v: list(combinations(v, 2)), axis=1)
print(d_f)

 

We import two required header files which include “pandas” as “pd”, and “combinations” from the “itertools” module. We create a data set by using the DataFrame(). This function is associated with the pandas library. We define the elements of the data set within this function.

In the next step, we utilize the lambda and combinations methods. The lambda method contains two parameters. We specify the value of the axis here. To store the generated combinations, we insert a column into the dataset called combinations. Lastly, we represent the required data set with the help of the print() method.

Conclusion

The combination techniques from the Itertools package are discussed in this article. The syntax, setup, and importation procedures for it into the system are all demonstrated. Then, we looked at how to create the combinations of letters by using the combination functions and employing the various data types including strings and arrays. While utilizing the combinations() method, we make use of the dataframe module. In one instance, we performed the combinations with replacements and in another example, we performed the replacement-free combinations.



Source link


We are all aware that an object function and function constructor can be used to refer specifically to a class variable. The setattr() method is the only other alternative to this one. In dynamic programming, where the variable name is not static, the setattr() method is helpful. The dot operator is inapplicable in that situation. Using the user input as an illustration, it sets the value of an object attribute. A value is assigned to an object’s attribute using the setattr() function in Python. It accepts an object, a string, and an unspecified value as parameters but doesn’t provide any output. When we wish to give an object a new attribute and assign a value to it, it is useful.

You will gain knowledge about the setattr() method of Python in this article, while we cover what it accomplishes, when to employ it, and when it is unnecessary. Regardless of whether the attribute is present or not, the method is used to define an attribute’s value for an object.

Syntax of the Setattr() Function in Python

The following is the setattr() syntax that we deployed in a Python script:

setattr(set_object, set_variable, set_value)

 
The object.attribute parameter is set to equal value using the arguments name of the object, variable name, and value. This function does not throw any exceptions because any object property can be of a certain type. It returns Nothing to the calling function.

Example 1: Program of Using the Setattr() Function

The setattr() method shows how the object-oriented programming still works well in these situations and is highly useful if an object’s attributes can change while it is being utilized. Here is the program to demonstrate the working of the setattr() function:

class Employee:
    Emp_name = ‘Alice’
my_object = Employee()
print(«Before setattr employee name : «, my_object.Emp_name)
setattr(my_object, ‘Emp_name’, ‘Alice jeo’)
print(«After setattr employee name : «, my_object.Emp_name)

 

In the script, we first established a class that is represented with the name “Employee”. In the specified class, we created a class variable as “Emp_name”. The class variable “Emp_name” is set with the string value that is the name of the employee. Then, we defined an object as “my_object” and invoked the class “Employee”. The print is utilized here to print the value of the variable “Emp_name” before the setattr() function is deployed.

To the setattr function, we passed three inputs: my_obeject, the variable name “Emp_name”, and the modified value of the variable “Emp_name”. Then, in the last print statement, we printed the employee name after using the setattr() function.

The following is the outcome obtained from the previous script of the Python setattr() function:

Example 2: Program of Using the Setattr() Function Property

Here, we showed the property of the setattr() function in Python.

class Animal:
    animal_name = ‘Cat’
obj1 = Animal()

print(«Before setattr name : «, str(obj1.animal_name))

setattr(obj1, ‘animal_name’, None)

setattr(obj1, ‘detail’, ‘Persian kittens’)

print(«After setattr animal name : « + str(obj1.animal_name))
print(«After setattr animal detail : «, str(obj1.detail))

 

In the previous script, we defined the class to which we have assigned the name “Animal”. To the class “Animal”. We defined a variable as “animal_name” which is set with the string value of the animal’s name “cat”. Then, we have an object as “obj1” where the class “Animal” is invoked. Then, we printed the object by passing it in the str method before the setattr() function.

After that, the setattr() function is deployed where the “obj1” is passed. The “animal_name” variable is also passed with the value “none”. Here, we deployed another setattr() function to the new attribute and initialized it with the new value. The print statement is provided to print the object after the setattr() function.

The setattr() function results before and after utilizing it are shown in the following:

Example 3: Program of Using the Setattr() Function with Dict

Having the ability to set numerous attributes simultaneously is one benefit of utilizing the setattr() function. If you were given a dictionary of an object’s characteristics, what would it contain? To set them for the various attributes of an object, you can loop over them.

class MyDictClass(object)
    def __init__(self, dict1)
        for key in dict1:
            setattr(self, key, dict1[key])
if __name__ == «__main__»:
   
    dict1 = {«Student_Name»: «Edison»,
            «Student_ID»: «3278»,
            «Student_Degree»: «IT»}
   
    my_result = MyDictClass(dict1)
   
    print(«After the conversion of Dictionary to Class : «)
    print(my_result.Student_Name, my_result.Student_ID, my_result.Student_Degree)
    print(type(my_result))

 

In this particular script, we first defined the class “MyDictClass”. We called the object to the class. Then, we have a definition of the init method which takes the “self” and the “dict1” as arguments.

After that, we have the for loop which loops over each key and the value of the given dictionary. We then deployed the setattr() function where the self, key, and dict values are added. Then, within the main function of this script, we created the dictionary. After that, we passed that dictionary to the class “MyDictClass” with the help of the newly created object – “my_result”. In the end, we printed the result.

Example 4: Program of Using Setattr() Function with Exception

Here, we’ll construct the read-only attributes for the object. If we attempt to use the setattr() function to change the attribute’s value, an exception is raised.

class Product:

    def __init__(self):
        self._Function = None

    def Function(self):
        print(‘Function called’)
        return self._Function

    obj = property(Function, None)

p1 = Product()

setattr(p1, ‘obj’, ‘laptop’)

 

First, we have the class definition as “Product”. We defined the init method where the self as an argument is provided to the class. The variable is created as a “Function” that has a value set to none. Then, we defined the function of the previous variable, “Function”.

After that, we created an object as “obj” where we have the property name “function”. To the property function, we passed the variable “Function” and its value. The setattr() function is invoked to which we provided the p1, obj, and the new value which throws the exception.

You can see that the following exception is raised from the previous script:

Conclusion

This article taught us how to utilize the setattr() function to dynamically set the object attributes while an application is running. When the properties are unknown to the developer and an API needs to be flexible, this is a highly helpful way for the Object-Oriented Programming. You learned how to assign a value to an object’s attribute using the Python setattr() function. Your knowledge of defining the function with the setattr() function is also cleared. Then, you learned how to use the setattr() method while using it to set the attributes with a Python dictionary.



Source link


As most of us might know, a function in Python is a chunk of code that can be reused when required without having to write it repeatedly.

Each program has a particular “flow”. Flow refers to the order in which a program gets executed. In a program, we have lines of code where we initialize variables, take inputs and outputs, and often create and call functions.

We can have one or more functions to perform particular tasks or operations. These functions might or might not return some value or result. However, we need to make a function call for these functions to run and execute. This is necessary.

Merienda the function has run completely, the next step is to exit the function. For this, we have the “return statement”. The return statement is used (implicitly or explicitly) to exit the function.

Exiting Function in Python Using Explicit and Implicit Return Statements

In this article, we will learn how to exit a function in Python with the help of return statements. We can use return in two ways:

Explicit Return in Python Function

By explicitly using the return keyword, you write and use the return statement in the code yourself. This method has many advantages, and it can be done in various situations.

When We Want To Stop the Execution and Exit the Function Early (if a Particular Condition Is Satisfied)

In this, we simply write “return” where we want the flow of the function to no longer continue and exit.

For example, we create a function here. We run a for loop from 1 to 10 and print the values individually. For each value “i”, after printing, we check if it equals 5. If it’s not equal to 5, we increment the “i” and continue. Merienda we reach “i=5”, “exit loop early” is displayed. Then, we exit the function due to the “return” statement.

Output

When We Want To Return a Value From the Function Which Will Be Further Used in the Program

Here, we call the add function and assign its value to the variable “value”. Then, the control goes to the function, which receives arguments 1 and 2 and stores them in a and respectively. Next, we return a +b from the function. Here, a+b is calculated, and the value is returned to the line where the function was called and is stored in the variable “value”. Finally, we print the sum, i.e., 3.

Output

Implicit Return in Python

It’s important to note that when the control reaches the last line of the function, the compiler calls “return” with the value “none”. Even when you only write “return” explicitly without passing any value, you are returning “none”. The value “none” is returned means that the function has been executed completely and returns no value. So, when the function ends, it calls the return statement implicitly.

Let’s take an example.

We create a function “solution” where we assign a string, “John”, to the variable, “name”. We check if the name stores “John”, print it, and exit the function. If it does not match, we exit the function without doing anything by implicitly calling the return statement.

Output

Python Exit Commands

Apart from exiting a function, we also have situations where we might want to end the program flow and exit the program abruptly.

Normally, the scripts exit merienda the control or interpreter reaches the end of the code. However, we have some commands that help us explicitly end the program with the help of built-in exit functions. Let’s discuss these functions one by one.

  • quit(): This command should be used only in the interpreter as it works only when the site module is imported and not in the Production code, i.e., the code is open to real-world users.
  • exit(): It is the same as quit(). It also can be used only in the interpreter and not in the production code.
  • sys.exit([args]): Unlike quit() and exit(), this can be comfortably used in the production code because of the availability of the sys module
  • os._exit(n): This method exits the process without calling any clean-up handlers, flushing buffers, etc.

As you might have noticed, all four have almost the same functionalities. They all raise the SystemExit exception, which causes the interpreter to exit without stack traceback.

What Is Exit() Function in Python?

Python’s exit() function is used to exit and come out of the code directly. This function is only used by interpreters and is synonymous with the quit() method. The exit function closes the program with a detailed status.

Conclusion

So, these are the two ways we can exit a function in Python. Either way, a return statement is used to exit a function. This can be done implicitly or explicitly, as explained above. You should try to understand this and implement this by yourself. This article mentioned some exit commands that can be used to quit the program suddenly. Exiting the function in Python using return commands is finta helpful when you have to leave midway in the function.



Source link


In Python, a dictionary is a list of elements that can only be retrieved using a unique key instead of indexing. Similar to a list in Python, the items can be stored in dictionaries. But instead of utilizing the item’s index to retrieve it, we provide the item in the dictionary with a unique key and then utilize it to do so. A technique for converting one dictionary into the other is called ”dictionary comprehension.”

Elements from the initial dictionary could be explicitly added to the new one throughout this conversion, and every element will undergo the appropriate modifications. The program may become more descriptive and hence simpler to comprehend if it has dictionary comprehension. Being able to obtain a dictionary’s key elements and the value of those elements is necessary for dictionary comprehension. The ‘for’ loop and lambda methods will be replaced with the use of dictionary comprehension. In this article, we will talk about dictionary comprehension in detail.

Example no 1:

In this scenario, we are going to use a ‘for’ loop with dictionary comprehension.

num = range(20)
new_dict = {}

for i in num:
    if i%2==0:
        new_dict[i] = i**3

print(new_dict)

First, we declare a variable ‘num’ and along with this, we define the range of the numbers. Another variable, ‘new_dict’ is being initialized, and this list will be set as an empty list. Now we are going to add different values to the dictionary ‘new_dict’ by the use of the ‘for’ loop. We initialize a loop variable ‘i’. We apply the condition on the loop variable that the defined value will be completely divided by 2. And then we apply multiplication to the values of the dictionary. The values will be multiplied by 3. In the last, we apply the print() function to display the elements.

Example no 2:

The alternate method used in place of ‘for’ loops is the deployment of dictionary comprehension. For loops have been applied in computer programs to continuously run a specific function or a series of commands for a defined couple of iterations. Nested for loops, where one for loop is present inside the other, become complicated and perplexing. In these situations, dictionary comprehension is preferable since it makes the program easier to read and comprehend properly.

num = range(20)
new_dict = {}
new_dict = {i:i**2 for i in num if i%2 == 0}

print(new_dict)

The range of the numbers is specified concurrently with the initial declaration of the variable “num.” This list would be configured as an empty list as another variable, ‘new_dict’, is initialized. We will use the for loop within the variable “new_dict” because we will be adding various values to the dictionary. We set the value of the loop variable “i.” On the dictionary’s values, multiplication is being used. The numbers will receive a 2x multiplier. On the loop variable, we provide a condition that the defined value will be evenly divided by 2. The print() function is finally invoked to print the values of the dictionary.

Example no 3:

The lambda method can also be approached using dictionary comprehension. The dictionary comprehension technique is an alternative technique for the lambda method. Some unidentified operations can be created by utilizing lambda methods. These include nameless procedures. These are reusable methods that are only used in the context in which they were assembled. Some functionalities are frequently combined with the lambda method.

fahrenheit = {‘t1’:-40, ‘t2’:-50, ‘t3’:-60, ‘t4’:10}
celsius = list(map(lambda a: (float(5)/9)*(a-32), fahrenheit.values()))
celsius_dict = dict(zip(fahrenheit.keys(), celsius))
print(celsius_dict)

We will initialize the Fahrenheit dictionary and define four temperatures. This dictionary is stored in the ‘fahrenheit’. We use the Celsius formula to convert the Fahrenheit temperature into a Celsius temperature. For this purpose, we utilize the lambda() function. By using this, we can obtain the appropriate Celsius values. We declare a variable ‘celsius_dict’ to create the Celsius dictionary.

Here we also utilize the zip() function. The inbuilt zip() method in Python iterates through the values and accumulates them. Fahrenheit.keys() and Celsius are two parameters of the zip() method. This instance utilizes the zip method to combine the elements of fahrenheit.keys() and the celsius dictionary, creating the appropriate key-value combination, which will be combined with other items in a dictionary by the use of the dict() method. Lastly, we will show the dictionary of Celsius by calling the print() function.

By using the dictionary comprehension, the outcome is clear and simple to comprehend. Thus, dictionary comprehension will be a useful replacement for lambda methods.

Example no 4:

Nested dictionary comprehension will be used in this instance. Information that is assembled in levels and wherever items incorporate additional things that are identical to them is called nesting in development. We would have frequently observed nested “if” statements that are composed of one if expression within the other one. Likewise, comprehensions and dictionaries could also be nested.

nested_dict = {‘third’:{‘x’:8}, ‘fourth’:{‘z’:9}}
float_dict = {outer_l: {float(inner_b) for (inner_l, inner_b) in outer_b.items()} for (outer_l, outer_b) in nested_dict.items()}
print(float_dict)

We create a dictionary that contains two values. In the next step, we will declare another dictionary that has some floating-point values. Within this dictionary, we configure a nested dictionary. This dictionary is stored in a variable ‘float_dict’. Then the print() function is employed to print the floating dictionary.

In this case, the variable “nested_dict” would be a dictionary having the values third and fourth storing dictionary elements as the data. The internal dictionary contents are used by the program, and when they have been transformed into floating-point values, the outer values and the initial floating-point numbers are merged to create a unique dictionary.

Conclusion:

This guide introduces us to dictionaries first, then illustrates what comprehension is and why it’s important, as well as certain situations in which it can be helpful, particularly when using dictionaries. We also successfully employ dictionary comprehension in a variety of programs that we run. A dictionary comprehension in Python loops through the values in a dictionary, enabling users to modify or analyze every element to develop a different dictionary. In this article, we also discussed how to utilize dictionary comprehension in place of the ‘for’ loop and lambda methods.



Source link


Every online application must be able to work with files. Python offers a few file management features. It allows users to work with files and perform basic operations including accessing, updating, copying, and a variety of other file management functions. The open() function in Python will be used to open a particular file. The open() method has several modes, each one provides the file be opened with a set of options.

Create a file

The first step is to create a new file. So, for creating a file we have been using the open() function. Within the open() method, we have given the name of the file which we want to create ‘myfile’. Along with this, we have provided the mode of the file. The ‘w’ mode represents that we will create a file to write in it.

After running the above code, we have this type of output which shows that the file ‘myfile’ is successfully created.

This file is situated in the ‘users’ folder of the ‘Restringido disk C’.

Open a file

After creating a file, we will open a required file to write the content in the file. We have been using the open() function. This method opens the file. This function contains two arguments. The first parameter shows the name of the specific file which we want to open for writing and the second argument shows the mode of the file ‘w’.

The output shows that we successfully open the file ‘myfile’ for writing.

Here the file named ‘myfile’ is opened.

Write some content in the file

Now, we are going to write the content in the defined file. So, we will use the f.write() function. Within this function, we have been given the line, text, or some content that we want to write in the file ‘myfile’.

This represents the successful execution of the code for writing the text in the file.

As we have provided the line ‘I love to play badminton’ so it is shown in the file.

Close the file

After writing the text in the file, we have to close the required file ‘myfile’. For that, we have been calling the f.close() function.

We have effectively closed the file.

Creation of new folder

Before copying and pasting the content of the file we will create a folder named ‘New folder’. First, we open the circunscrito disk C. Then, we will open the menu bar by clicking the left of the mouse. A menu bar appears from there and we choose a ‘New’ option.

After clicking the ‘New’ option again, a new menu bar will open. From that menu bar, we select the ‘Folder’ option.

By doing all this we create a ‘New folder’ in the same location (users of the circunscrito disk C).

When we open the ‘New folder’, we find that it is empty. Now, we have to copy and paste the file into this folder.

Copy and paste a complete file from one location to another

We will copy the text from the file ‘myfile’ and paste that text into the folder ‘New folder’. For this purpose, we will integrate the library ‘shutil’. Then, we utilize the function of shutil(). Its first parameter shows the name of the file which we want to be copied and the second parameter shows the name of the folder where we want the file to be copied or where we want to paste the file.

The outcome shows the implementation of the code.

We successfully copied the file ’myfile’ and pasted it into the folder ‘New folder’.

When the file will be copied, the whole content of the file is automatically copied and pasted to a new location.

Create a second new file

We’ll make a new file merienda more. We’ve been calling the open() command to create files. We’ve specified ‘myfile_1’ as the name of the file we wish to create in the open() function. The ‘w’ mode denotes the creation of a file to write on it.

We obtain this type of result after executing the preceding code, indicating that the file’myfile_1′ will be built.

The location of this file is the same as the location of the file ‘myfile’.

Open a file and add some text

We’ll now open a relevant file and type the data into it. The open() method has been used. This function is used to open a file. There are two parameters in this method. The first argument is the title of the particular file that we would like to open for writing and the second specifies the file’s mode, which is ‘w’. We’ll write the text into the specified file after accessing the file.

As a result, the f.write() method will be applied. We provided the text to write in the file ‘myfile_1’ as a parameter to this function. We must shut down the appropriate file ‘myfile_1’ after writing the text in the file. Thus, we have employed the f.close() method.

The output demonstrates that we effectively open the file ‘myfile_1’, then we write the data in it.

We want to add the text ‘I love to visit different places’ in the file as given below.

Read the text of the file and print

First, we have applied the open() function and ‘with’ keyword. We have given the file name which we want open as the function’s attribute. After this, we have been using the function readlines(). This method just reads the data from the entered file and then stores those lines in the variable ‘line’. At the end, print() statement is being utilized to display the data of the file.

When we execute the code, we find the content of the file ‘myfile_1’.

Copy and paste the text of one file to a different file

For copying the text from one file and replacing them with the text of another file, we will apply the open() function and the ‘with’ keyword. We declare a variable ‘f’ so the content of the file ‘myfile’ will be saved in the ‘f’ variable. Then, we again use the open() function and ‘with’ statement to open another file ‘myfile_1’. This file can be opened in write ‘w’ mode.

Now, we use the ‘for’ loop. This loop iterates until we write the sentence ‘I love to play badminton’ in file ‘myfile_1’. To write this content we employ the write() function.

This screenshot shows the successful implementation of the above code.

Before copying the text. The ‘myfile_1’ contains the data ‘I love to visit different places’. We copy the data from the file ‘myfile’ and then paste that data into the myfile_1’. Now, the file ‘myfile_1’ has the line ‘I love to play badminton’.

Conclusion

Before copying the file, we must first create a file, then open that file, add some content to the file, close the file, and then create a new folder in another location. Then, we copied a file from one position to another. In this article, we have demonstrated the method of copying the text from one file and pasting that text into another file.



Source link


If the ‘if’ condition becomes False, the very next ‘elif’ portion’s condition is evaluated. The content of ‘else’ would be implemented when all of the requirements become False. As per the situation, just one of the numerous if…elif…else statements is evaluated. There would only be another clause in the ‘if’ section. This could, however, have several ‘elif’ statements. We are going to explain the ‘elif’ python in this article.

Example no 1:

We will evaluate a defined number to see whether that value is a positive number or zero or a non-positive number.

1
2
3
4
5
6
7
8
9
10
11
12
13

num = 5.8

if num > 0:

    print(«Positive number»)

elif num == 0:

    print(«Zero»)

else:

    print(«Negative number»)

We will initialize a variable ‘num’ and assign it a value having a quebrado point in it. We have utilized the ‘if’ statement. Within the ‘if’ statement, we use the condition that num>0. It shows that if the required value is greater than 0, the print() command prints the message ‘Positive number’. In the next line, we use the ‘elif’ statement. Here, we apply condition num==0. It represents that if the defined number is equal to 0, then it prints the text ‘Zero’. At the end, within the else statement, the print() function is being used to display the line ‘Negative number’.

As the specified value is greater than 0, the print() statement prints the text ‘Positive number’.

Example no 2:

The ‘elif’ statements are employed just after the if expression in this instance. Python can assess the ‘if’ statement. If it returns False, this would analyze the ‘elif’ statements and implement the ‘elif’ statement with the True representative. If more than one ‘elif’ statement is fulfilled, the very first ‘elif’ section is invoked.

1
2
3
4
5
6
7
8
9
10
11
12
13

rate = 5000

if rate > 5000:

    print(«rate is greater than 5000»)

elif rate == 5000:

    print(«rate is 5000»)

elif rate < 5000:

    print(«rate is less than 5000»)

First of all the variable named ‘rate’ is being declared and then the value is assigned to it. To determine information about the provided value, we use conditions. We apply the criterion rate>5000 within the ‘if’ expression. The print() function prints the message ‘rate is greater than 5000’ if the defined value is greater than 5000. The ‘elif’ expression is being used in the next line. The requirement rate==5000 is used here. It indicates that if the specified value is equal to 5000, the text ‘rate is 5000’ will be displayed by using the print() function.

We utilize the condition ‘rate< 5000’ in the elif expression. It denotes that the value entered is less than 5000. The line ‘rate is less than 5000’ is presented with the help of the print() method.

Example no 3:

The innermost command will be indented more than the inclusive expression. All commands within a single segment will be extended identically.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

price = 2000

quantity = 6

rate = price*quantity

if rate > 1000:

    if rate > 1000:

        print(«rate is greater than 1000»)

    else:

        if rate < 1000 and rate > 1500:

            print(«rate is»)

        elif rate < 1500 and rate > 1300:

            print(«rate is between 1300 and 1500»)

        else:

            print(«rate is between 1200 and 1500»)

elif amount == 2000:

    print(«rate is 2000»)

else:

    print(«rate is less than 2000»)

At the start of the program, we initialize three variables and give them values. These variables include ‘price’, ‘quantity’, and ‘rate’. The values of variables ‘price’ and ‘quantity’ will be provided by the user but the value of ‘rate’ will be calculated by multiplying the value of price and quantity with each other. We have utilized greater than sign and applied conditions on the value of the ‘rate’ variable. We apply the if-else statement.

Whenever the condition of the ‘if’ statement is fulfilled, the print statement displays the message that ‘Rate is greater than 100’. Otherwise, we use various conditions. Within the portion of the else-condition, we have applied the ‘elif’-expression. The ‘elif’ expression uses the ‘BETWEEN’ and ‘AND’ operators to apply conditions on the value. The ‘elif’ expression shows that ‘rate <1500 and rate > 1300’ then print statement prints the line ‘rate is between 1300 and 1500.

When the specified condition becomes true the print() command of that appropriate condition prints the result. Similarly, outside the body of the if-else statement, we again employ the ‘elif’ statement. We use the equal operator in such a way that ‘rate == 2000’ then print() command shows the line ‘rate is 2000’. Otherwise, it prints the message ‘rate is less than 2000’.

Example no 4:

In this scenario, if, a sequence of ‘elif’ and else will be used to obtain the data type of a specified value.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

v = 3558.9769

if (type(v) == int):

    print(«Data type of the variable is Integer»)

elif (type(v) == float):

    print(«Data type of the variable is Float»)

elif (type(v) == complex):

    print(«Data type of the variable is Complex»)

elif (type(v) == bool):

    print(«Data type of the variable is Bool»)

elif (type(v) == str):

    print(«Data type of the variable is String»)

elif (type(v) == tuple):

    print(«Data type of the variable is Tuple»)

elif (type(v) == dict):

    print(«Data type of the variable is Dictionaries»)

elif (type(v) == list):

    print(«Type of the variable is List»)

else:

    print(«Data type of the variable is Unknown»)

Our step is to initialize the variable named ‘v’ and we will provide it with a value. To check its data type, we have been using the ‘if-elif’ statement. The ‘if’ statement checks if the entered value of variable ‘v’ is an integer. Then the print() command prints the line ‘Data type of the variable is Integer’.

After this, the ‘elif’ statement is utilized to see if the defined value is a floating-point value. Then, the print value shows the message related to this. If the value contains the complex portion it means the data type of the variable will be complex so we will use the print() function for this also. Similarly, if the given value contains the ‘True’ or ‘False’, then the data type is Boolean so the print statement shows that the type will be bool.

Then, we use str and tuple to check whether the specified value belongs to the string data type or tuple data type. The ‘elif’ statement is applied to check if the value is related to the dictionary data type or not. In the end, we utilized the equal operator (==) within the ‘elif’ command. This time we have seen if the value is present in the form of a list. Then the print() method prints the line ‘Data type of the variable list’. If the entered value does not belong to any of the above-mentioned data types, then the print() command prints the message ‘Data type of the variable is unknown’.

Conclusion:

In this article, we have talked about the ‘elif’ python. The ‘elif’ expression helps to verify several statements for TRUE and run a set of instructions immediately while one of them does. The ‘elif’ expression, like the else command, is unnecessary. Unlike other expressions, that can only have one, the ‘elif’ expression will have an arbitrary value of these after the ‘if’ statement.



Source link


“JSON or JavaScript Object Notation is a lightweight data exchange format that is widely adopted by modern applications. Whether you are working in NoSQL databases or fetching API data, you will encounter JSON.

It is a heavily adopted language due to its simplicity but strict schema. This helps to reduce errors while still retaining human readability.

Luckily, Python has a built-in package called json that allows us to interact and process JSON data.

For this tutorial, we will cover how you can pretty-print JSON data using Python’s json module.”

Let’s get started.

Python json.dumps() Function

To pretty print JSON data in Python, we use the dumps method from the json module. The function syntax is as shown:

1

json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)

The function parameters are as discussed below:

  1. obj – refers to the JSON object you wish to print.
  2. skipkeys – if set to true, the function will skip keys that are not of str, int, float, bool, or None type. This value is set to false by default.
  3. ensure_ascii – if set to true, the function will return an output with non-ascii characters escaped. This value is true by default.
  4. check_circular – skips the circular reference check for container types if true. Otherwise, return OverFlowError.
  5. allow_nan – out of range floats are substituted for NaN, Infinity, or -Inifinity if set to true.
  6. indent – specifies the indent level for the pretty-print format. If the indent level is 0 or negative, the function will only print new lines. For a more compact representation of the data, ensure to specify a positive integer of above 1.
  7. separators – specify the item and key separate characters.
  8. sort_keys – if true, the function sorts the output dictionary by its keys.

Let us explore how we can use this function to pretty-print JSON data.

Example 1

The example below shows how to use the json.dumps() function to pretty-print a JSON object.

1
2
3
4
5
6
7
8
9
10
11

from json import dumps, loads

 

data = ‘{«id»:1,»first_name»:»Jada»,»last_name»:»Deport»,»email»:»[email protected]«,»gender»:»Female»,»ip_address»:»68.40.159.153″}’

 

json_object = loads(data)

print(dumps(json_object, indent=3))

We start by importing the required functions. In our case, we need the dumps() function to pretty-print the json object and the loads to deserialize the json into a Python object.

Next, we create a variable holding the raw JSON data. We convert it into a Python object using the loads’ function and finally, pretty print it with the dumps() function.

The resulting output is as shown:

1
2
3
4
5
6
7
8
9

$ python pretty_print.py
{
   «id»: 1,
   «first_name»: «Jada»,
   «last_name»: «Deport»,
   «email»: «[email protected]«,
   «gender»: «Female»,
   «ip_address»: «68.40.159.153»
}

The code below shows the same JSO output level with an indent level of 1.

1
2
3
4
5
6
7
8
9
10
11

from json import dumps, loads

 

data = ‘{«id»:1,»first_name»:»Jada»,»last_name»:»Deport»,»email»:»[email protected]«,»gender»:»Female»,»ip_address»:»68.40.159.153″}’

 

json_object = loads(data)

print(dumps(json_object, indent=1))

The resulting output:

Note that the indent level of 3 adds more whitespace characters when printing the JSON.

Example 2 – Sorting Keys

We can also sort the keys of the output dictionary by setting the sort_keys parameter to True.

Consider the example below:

1
2
3
4
5
6
7
8
9
10
11

from json import dumps, loads

 

data = ‘{«id»:1,»first_name»:»Jada»,»last_name»:»Deport»,»email»:»[email protected]«,»gender»:»Female»,»ip_address»:»68.40.159.153″}’

 

json_object = loads(data)

print(dumps(json_object, indent=1, sort_keys=True))

The code should sort the keys of the output dictionary in ascending order as shown:

Note how each key in the resulting dictionary is sorted in alphabetical order.

Example 3 – Pretty Print JSON From File

Using Python’s open function, we can load data from a JSON file and pretty print it. Suppose we have a JSON file as shown:

We can load the file and use the json.dumps() method as shown in the example code below:

1
2
3
4
5
6
7

from json import dumps, load

with open(‘net_info.json’, ‘r’) as f:

    json_data = load(f)

print(dumps(json_data, indent=1))

In the example above, we use the load function to load the JSON data from the file into a JSON object.

We then use the dumps function to pretty print with an indent level of 1. The resulting output is as shown:

The output gives us a well-formatted list of Python dictionaries representing the JSON data.

Conclusion

In this tutorial, we learned how to use the JSON dumps function to pretty-print JSON data in Python. We also learned how to sort JSON data by its keys using the sort_keys parameter.

Thanks for reading!!



Source link