1

I try to understand something,

x = 10
print x

The result will be 10

x is 10
print x

The result will be Error X is not defined.

x = 10
y = 10

if x == y:
  print True

if x is y:
  print True

The result is:

True
True

Is there another way to define a variable without using the equal sign?

Roy Holzem
  • 860
  • 13
  • 25
  • `X is 10` returns a boolean. There's no other way to declare a variable other than `=` AFAIK. – Mangohero1 Aug 10 '17 at 20:40
  • 7
    But... why would you want to? Not only would it make your code less understandable (because it's obviously not a common practice), there is really just no point. – GrumpyCrouton Aug 10 '17 at 20:41
  • 4
    `globals().__setitem__('x', 10)` – inspectorG4dget Aug 10 '17 at 20:43
  • 1
    Your first two examples have a capitol X and then you're trying to print a lower case x – Westly White Aug 10 '17 at 20:44
  • @Westly White, Thank you, fixed. – Roy Holzem Aug 10 '17 at 20:45
  • globals().update({'x':10, 'y':20}) – PRMoureu Aug 10 '17 at 20:47
  • I know the question is absurd, I was just trying to prove a point at 22:42 and we got an answer, thanks @inspectorG4dget can you put this into an answer? – Roy Holzem Aug 10 '17 at 20:48
  • 2
    You aren't _really_ defining a variable, you're binding a name to an object. Please see [Other languages have "variables", Python has "names"](http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables). For a more in-depth discussion of this topic, see [Facts and myths about Python names and values](http://nedbatchelder.com/text/names.html), which was written by SO veteran Ned Batchelder. – PM 2Ring Aug 10 '17 at 20:48
  • Note that `x, y = 100, 10 * 10; print(x is y)` prints `True`. But `x, y = 300, 30 * 10; print(x is y)` prints `False`. – PM 2Ring Aug 10 '17 at 20:53

4 Answers4

6

Your question is pretty weird. In practice, you'd never want to not use = to assign to a variable. But just for the sake of completeness, it is possible to assign to a new variable by screwing around with globals() (or locals(), depending).

Here's one way to do that:

globals().__setitem__('x', 10)

Proof:

In [139]: x
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-139-401b30e3b8b5> in <module>()
----> 1 x

NameError: name 'x' is not defined

In [140]: globals().__setitem__('x', 10)

In [141]: x
Out[141]: 10

EDIT:

Don't mess with locals(). That's the mentally unstable, overly buff, drunk guy at the bar that'll f--- up your codez and make you say "he be cray cray".
So just don't mess with locals(). On the other hand, just use x = 10 and save your sanity. Bah! this post physically hurts

inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
1

You cannot declare a variable using "is" as "is" compares the identities of operands (a stricter version of == imo) not assigns it. Back to your question, I don't think that's necessary as "=" serves that role quite well. However in a block of code, like for loop, you can assign temporary variables in that block of code. Example:-

for i in range(20):
    print i

or

You can also use "as" keyword like

import xml.etree.ElementTree as ET

and

with open('file.txt') as f:
    a = f.readlines()

It all depends on what you mean by 'define a variable'.

PM 2Ring
  • 54,345
  • 6
  • 82
  • 182
Vedarth Sharma
  • 339
  • 1
  • 8
1

When you're in the interactive Python interpreter the return value of the last expression is automatically stored in the _ (underscore) variable:

>>> 1.0 + 1.0
2.0
>>> _
2.0
>>> _ * 2
4.0
>>> _
4.0

Furthermore, if you're using IPython,

  • __ and ___ (double and triple underscores) refer to the second to last and third to last output values,
  • _iii, _ii, _i refer to the last three input commands,
  • any previous output can be accessed using something like _2, and
  • any previous input can be accessed as a string using something like _i2:

(See a corresponding Stackoverflow answer.)

In [1]: True
Out[1]: True

In [2]: 'asdbsd'
Out[2]: 'asdbsd'

In [3]: -5 + 0
Out[3]: -5

In [4]: ___, __, _
Out[4]: (True, 'asdbsd', -5)

In [5]: _i
Out[5]: u'___, __, _'

In [6]: _1
Out[6]: True

In [7]: _i3
Out[7]: u'-5+0'

(IPython documentation.)

zahypeti
  • 183
  • 1
  • 8
0

The short answer is not really, but that doesn't mean empty declarations aren't ever used in python. If you want to declare a variable but not instantiate it, your best bet is

x = ''

or

x = Null

There are times when you'd want to do this, despite what others have mentioned. For example, consider this code.

try:
    myValue = foo()
except:
    pass

print(myValue);

If foo() throws an error, your code won't break because of the try-catch. However, when you try to print myValue, your code will break because it's not defined. To prevent this you could add an empty declaration of myValue above the try-catch

bsivo
  • 36
  • 7
  • I would argue that it's often actually _better_ for the code to fail noisily if there isn't an object named `myValue` than to supply a meaningless default value that allows the code to continue executing and possibly return an invalid result. – PM 2Ring Aug 10 '17 at 20:57
  • I agree that if your code really depends on a valid myValue, then it would be better to fail. I was just trying to come up with a basic example of where you might want to forward-declare a variable. In the end, it's all up to the requirements of the code to determine how to handle errors. – bsivo Aug 10 '17 at 21:07