Reputation: 49
When i was going through the codes i found an interesting thing, if we initialize a variable in python shell, and we print that variable we get the value, if we use type the variable and press enter we get the same value. I could't figure out the reason behind it?? Can anyone help....
>a = 5
>print(a)
>5
>a
5
Upvotes: 2
Views: 843
Reputation: 132
The Python console is a Read Evaluate Print Loop (REPL). It first reads your input, evaluates it, prints any output, and repeats until you exit. It's a very common way to interact with a language, and exists for many many languages.
Another example of what you've observed is
>>> 1+2
3
Here the console evaluates 1+2
and prints the returned result. Try it with any function or expression.
print()
works as expected because when it is evaluated, it does its own printing before returning None
, just how any other function does all of its own code before returning to the console whatever will be printed. You could try this, for example
>>> type(print('test'))
test
<class 'NoneType'>
Here the console evaluates print('test')
, which causes the first, manual print, and then automatically prints the return of the type
call, resulting in the second line.
To answer your question, the difference between >>> print(a)
and >>> a
is that, in the first case, the console evaluates the print and has no return value to print, and in the second case, the console evaluates the expression and prints the result, which is a
's value.
Upvotes: 2
Reputation: 1286
print
will work in the shell AND in a script while giving the variable name is just a syntactic sugar for the shell.
Upvotes: 2