0

I am looking to understand some basic python functions in their entirety. How does the "del" produce this (in bash):

>>> temp = 1
>>> python = 1 + temp
>>> 
>>> 
>>> temp
1
>>> 
>>> python
2
>>> 
>>> 
>>> del temp
>>> 
>>> 
>>> python
2
>>> 
>>> temp
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'temp' is not defined
>>> 
>>> 
>>> 
3
  • 1
    Are you asking how variables are deleted, or is there some other behaviour here that is unexpected? Commented Mar 19, 2014 at 3:08
  • python was already assigned the value 2. It doesn't make a reference to temp in order to produce the result. What's unexpected here? Commented Mar 19, 2014 at 3:10
  • see answer from Elias Benevedes below. I didn't understand that variables are defined at one point in time, and not continuously redefined. Commented Mar 19, 2014 at 6:31

4 Answers 4

1

For del in python, it means

Deletion of a name removes the binding of that name from the local or global namespace

so when you del var, it removes this variable, and it's not usable when you call it again, that's why exception happens.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks - I was asking why the var 'python' will run without a NameError, after deleting 'temp', seemingly contained within var 'python'.
0

The way variables are created are in reference one time to another variable. In your example, python = temp + 1, python is equal to temp plus 1 at its time of definition.. The variable python does not re-compute every time the processor goes through a loop. Its value is only defined once. If a variable included in its definition changes, it does not change.

1 Comment

Thanks, Elias - you've entirely explained what I misunderstood about defining variables in this example.
0

python delete variable within variable

temp is not inside python. In the line

python = 1 + temp

only the value of temp will be used to create the variable python. So if you delete temp, it won't affect python.

1 Comment

Thanks - you've understood and explained well.
0

Here is the what the manual for the python del command says:

Deletion of a name removes the binding of that name from the local or global namespace, depending on whether the name occurs in a global statement in the same code block. If the name is unbound, a NameError exception will be raised.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.