Python is exist var

Python how to check if variable exist and its length, in one if statement?

To avoid repeating the same piece of code, I would like to combine those 2 if conditions, in one. But if var is None, I can’t check its length. Any idea? I would like something like this:

if var and len(var) == 5: do something. 

In addition to what everyone already said (i.e. that your suggestion indeed works as you expect) why are you checking for length if you are going to do the same thing anyway? Also note that in general when you have a body of code that you don’t want to repeat the tool to use is a function or a method (depending on how much context is needed by the code).

I shouldn’t ask questions at night, hoping to get an answer in the morning. I was sure I tried that and it didn’t work.

3 Answers 3

Did you try that? It works:

The and operator doesn’t evaluate the RHS if the LHS is false. Try this:

>>> False and 1/0 False >>> True and 1/0 ZeroDivisionError: division by zero 

@steabert: Add not or else to your code as you see fit. I’m not here to write your code, just to answer questions.

There is one snag here (which might or might not be relevant to @Tickon): This solution does not discriminate between the cases var == [] and var is None . In the former case, len(var) can be determined ( == 0 ), in the latter it can’t. (However, I don’t think this is a reason to downvote this answer)

The code as you’ve written it in the question executes the statements in two cases:

  • var evaluates to true and has a length of 5
  • var evaluates to false (e.g. it’s None or False )

You can combine those into one conditional as follows:

The conditional that some other answers are suggesting, var and len(var) == 5 , only evaluates to True in the first case, not the second. I will say, though, that the two cases you’ve chosen are kind of an unusual combination. Are you sure you didn’t intend to execute the statements only if the variable has a non-false value and has a length of 5?

Additionally, as 6502 wrote in a comment, functions are intended for exactly this case, namely making reusable code blocks. So another easy solution would be

 def f(): . if var: if var.length == 5: f() else: f() 

Источник

How to Check If Variable Exists in Python?

Python Certification Course: Master the essentials

In Python, before we perform an operation on a variable is important to check if a variable exists or not. If this step is avoided, an exception might appears. To avoid such errors, Python offers three explicit ways to check if a variable exists which are explained below making it easier for the developer to check in advance and make its code error less.

Introduction to Check if a Variable Exists in Python

In the below article, we shall check if a variable exists in Python in various ways (including code examples, algorithms, and elaborative explanations), but before that let us briefly discuss what a variable is.

Читайте также:  Css style color opacity

Defining a Variable in Python?

We can define a variable as containers (or reserved memory locations) where the data values are stored and used while evaluating any expression. In Python, the variables have data types like integer type, string type, float type, or a boolean value, etc. It is recommended to always define a variable before utilizing them in any function or program.

Note: You don’t need to necessarily mention the data type for the variable while you are defining it in the code.

Explanation:

As seen above, we considered two cases, where in the first case we defined the variable ‘y’ as an int value of 7 . We print the variable to check if the value given to the variable gets reflected. No data type like int is used before the variable name. For case two, we explicitly define the datatype as float and the same gets printed as well for the variable ‘a’ with a float value of 8.0 .

As we need to mandatorily define the variable before utilizing it, we often use the ‘None’ object to specify that we have no real value assigned for the variable as shown in the below code example.

Explanation:

As seen above, we can test like above whether a variable is a None object or not.

As we understand what is a variable, let us get back to learning in Python to check if a variable exists or not. Let us answer the question, of why is it necessary in Python, check if a variable exists.

We consider the scenario of not setting or defining the variable explicitly as a bad practice while programming in Python. It is so because this implies that the logic of the code is not appropriately thought out, which in the future leads to giving unpredictable errors or behavior.

In Python, check if a variable exists we use either one of the three methods given below:

  • Python check if a variable exists using a local variable
  • Python check if a variable exists using the global variable
  • Use any variable without being defined or set in Python

We shall use the in operator and check inside the locals() dictionary. Similarly, we can use the in operator and check inside the global() dictionary. We use the try-except block for the undefined variables in Python to check if the variable exists.

Let us discuss each one by one in detail.

Python Check if a Variable Exists Using a Local Variable

We define the local() variable as a built-in Python function that returns a dictionary for the current local symbol table. It is this local symbol table, where all the information related to the local scope of the code base is stored. This local() variable can be accessed for the information using the Python built-in function locals() .

Sample Code for local() varible:

We see the three variables we defined as locals printed at the end are all the ones we defined as the above sample code.

  • In Python, check if the variable exists using the local variable in the three cases we explored.
  • In the first case, we create a user-defined function named check_var_local_case1() , in which we declare the local_var as 22 int data type. We then check if this exists in the locals() variable using the in operator. We then print the variable to check and find that in Python, check if the variable exists.
  • In the second case, we create a user’s defined function named check_var_local_case2() , in which we declare the local_var as 33 int data type. We then check if this exists in the locals() variable using the if-else statement and in the operator. If the variable exists, we use the print statement to print the message that it is present in a local() variable as in this case.
  • In the third case, we create users defined function named check_var_local_case3() , in which we declare the local_var as 66 int data type. We then check if this exists in the locals() variable using the if-else statement and in the operator. If the variable exists, we use the print statement to print the message that it is not present in the local() variable.
Читайте также:  Условный оператор java это

Explanation:

As seen above, we see three defied cases where we declare a local_var of different int data type values. Then we check one by one in Python, checking if the variable exits using the local() variable. We implement the in operator in the first case and find local() variable exists. While in the second case we use the if-else statement and in-operator to find that the local() variable exists. For the third case we apply the same (if-else statement and in operator ). and find out that the local() variable doesn’t exist.

Python Check if the Variable Exists Using a Global Variable

We define the global() variable as a built-in Python function that returns a dictionary for the current global symbol table. All the essential data structures that a code base(or program) requires like classes, methods, and variable names are termed symbol tables.

Sample Code for local() variable:

Explanation:

We see the three variables we defined as globals printed at the end are all the ones we defined as the above sample code. We created the user-defined function where we used the globally defined variable to perform the addition operation. As no errors were thrown, it states that we accessed the global variable inside the user-defined function.

  • In the first case, we create a user-defined function named check_var_global_case1() , where we have already declared the global_var as a 22 int data type. We then check if this exists in the globals() variable using the in operator. We then print the variable to check and find that in Python, check if a variable exists.
  • In the second case, we create users defined function named check_var_global_case2() , where we have already declared the global_var as 33 int data type. We then check if this exists in the globals() variable using the if-else statement and in the operator. If the variable exists, we use the print statement to print the message that it is present in the globals() variable as in this case.
  • In the third case, we create a user’s defined function named check_var_global_case3() , where we have already declared the global_var as 66 int data type. We then check if this exists in the globals() variable using the if-else statement and in the operator. If the variable exists, we use the print statement to print the message that it is not present in the globals() variable.

Explanation:

As seen above, we see three different cases where we declare a global_var of different int data type values. Then we check one by one in Python, check if a variable exit using the globals() variable. We implement the in operator in the first case and find globals() variable exists. While in the second case we use the if-else statement and in-operator to find that the globals() variable exists. For the third case, we apply the same (if-else statement and in operator) and find out that the globals() variable doesn’t exist.

Читайте также:  Python for len range

Use Any Variable Without Being Defined or Set in Python

In Python, though we don’t have a defined function to check and test if a variable is already defined or not, as it is usually believed that all variables have been defined (be it initially assigned to a None object). You might come across a scenario where you may have got a NameError exception while trying to call or access the variable that has not been defined earlier. This NameError exception is efficiently handled using a try/except clause.

We use variables that have not been defined or set in Python, via the try-except statement. If we see that an error is raised, then set the value of that variable to None using the same try-except statement.

  • In Python, check if a variable exists is properly defined or not, we evaluate this problem statement with two cases.
  • In the first case, we don’t define the variable and check if the NameError arises and what is the value of the variable.
  • We use the try-except clause to check the same, as per expectation the NameError exception is raised and we set the value to a None object type to avoid further error exceptions. Hence, it returns None.
  • In the second case, we define the variable as a string data type, and hence when it passes through the try block it prints its value as a string. No NameError exception is raised in this case.

Explanation:

We explore two cases in Python, to check if a variable exists and is properly defined or not. In the first case, we don’t define the variable and check if the NameError arises and what is the value of the variable. Here we set the value to a None object type to avoid further error exceptions. Hence, it returns None. While in the second case, we define the variable as a string data type, and hence when it passes through the try block it prints its value as a string. No NameError exception is raised in this case.

Conclusion

  • A variable as containers (or reserved memory locations) where the data values are stored and are used while evaluating any expression. In Python, the variables have data types like integer type, string type, float type, or a boolean value, etc.
  • The local() variable is a built-in Python function that returns a dictionary for the current local symbol table. It is this local symbol table, where all the information related to the local scope of the code base is stored. This local() variable can be accessed for the information using the python built-in function locals() .
  • The scenario of not setting or defining the variable explicitly is a bad practice while programming in Python. It is so because this implies that the logic of the code is not appropriately thought out, which in the future leads to giving unpredictable errors or behavior.
  • The global() variable is a built-in Python function that returns a dictionary for the current global symbol table. All the essential data structures that a code base(or program ) requires like classes, methods, and variable names are termed a symbol table.

Источник

Оцените статью