Python: Update a variable inside the print function [duplicate] - python

This question already has answers here:
How to define a variable inside the print function?
(2 answers)
Closed 3 years ago.
a=1
print(a=2)
I am new in python. I tried to change the value for the variable a inside the print function. However, it's showing a syntax error. This concept will work in other languages. Could you please explain why it's showing a syntax error?

print is in-built function which takes positional and some keyword args.
Here you are calling print function with keyword args a with value 2, but there is no keyword args named a in print function.
You can't update the value inside a function call

Actually,what you would encounter is a TypeError,
>>> a=1
>>> print(a=2)
Traceback (most recent call last):
File "<pyshell#44>", line 1, in <module>
print(a=2)
TypeError: 'a' is an invalid keyword argument for print()
From the python documentation, you can find that if there was an = sign, the print() function would take it as an keyword argument unless it is given as a string.
So what actually happened here is that python tries to identify a as an argument, which obviously is not defined in the print() function. Therefore, it finds it as an invalid argument.
If you need to update the value of a, it is advisable to do it before the print() function and then print it.

Considering you are using python< v3.8, in my opinion, the closest you can get (pun intended) is:
>>> a = 1
>>> print(dict().get(exec('a=2'),a))
2
>>> a
2
Or,
>>> print({exec('a=2'):a}[None])
2
>>> a
2
Or,
>>> exec('a=2;print(a)')
2

I think this is the closest you can get:
a = 1
print('{} {}'.format(exec('a=2'), a))
Edit: I thought wrong. #Sayandip Dutta fixed my problem.

Related

8/2(2+2) doesn't work in python but 8/2+(2+2) and 8/2*(2+2) do. Why? [duplicate]

This question already has an answer here:
Why do I get "TypeError: 'int' object is not callable" from code like "5(side_length**2)"?
(1 answer)
Closed 5 months ago.
Trying to understand operands in python.
8/2(2+2) gave the following error:
TypeError Traceback (most recent call last)
<ipython-input-12-8949a58e2cfa> in <module>
----> 1 8/2(2 + 2)
TypeError: 'int' object is not callable.
Trying to do this like this then using sum() then as python dictionary then in numpy.
Python doesn't support implicit multiplication. When Python tries to run 2(2+2), it tries to call the numeric literal 2 as a function, passing 2+2 as an argument to it. You need to use * between things you want to multiply.
There is no operator between the 2 and the ( - human math assumes a multiplication here but a computer does not.
The parser sees 2(...) - which is interpreted as a function with the name 2 and a parameter.
Since there is no default function with that name and there is no def 2(x) you get that error message.
Additionally 2 is not a vaild function name in python.
Python doesn't work like normal maths. 2(2+2) will not be executed as 2×4. Instead, 2 will be treated as a function, which is not callable (your error message) . To do that, you've to put operator between 2 and (2+2). Try putting a * between 2 and (2+2). Your expression would be 8/2*(2+2)

assigning variables via input() function [duplicate]

This question already has answers here:
Python - User input for name of a variable to pass as an argument to a function
(3 answers)
Closed 5 years ago.
Is it possible to assign variables via the input() function in Python 3? In my case I am trying to give the user the option to assign objects to variables in a list.
My idea would be to type the variable assignement directly into the argument of the input function:
board=[f1,f2,f3,f4,f5,f6,f,f8,f9]
input(f1=some_Object)
print(board[0])
Result for print(board[0]) should then be some_object. The same procedure should then also work for f2,f3...f6.
However this does not work, it produces the following error:
Traceback (most recent call last):
File "C:/Users/Christian/AppData/Local/Programs/Python/Python35-32/Tic Tac
Toe.py", line 1, in <module>
board=[f1,f2,f3,f4,f5,f6]
NameError: name 'f1' is not defined
so im wondering if there is a way to do it in
Python.
Thanks for your help.
The way to assign a variable with input() is the following:
my_variable = input("Some prompt ")
If you then want to see the output to convince yourself, you can add:
print(my_variable)
This will output back at you whatever you enter.
In your case you can do
board[0] = input("Enter a value: ")

Why is print("{}").format() valid syntax?

Ran into some interesting Python behavior today. I though I was writing
print("{}".format("some value"))
but instead I wrote
print("{}").format("some value")
and funnily enough it worked. So my question is, how does this work?
Digging deeper
This behavior seems to be python2 specific.
Python2.7
>>> print("{}").format("testing")
testing
Python3.4
>>> print("{}").format("testing)
File "<stdin>", line 1
print("{}").format("testing)
^
SyntaxError: EOL while scanning string literal
It also seems like the print function of python2 doesn't have a return value but Python3 does? so that confuses me even more.
Python2.7
>>> type(print("testing))
File "<stdin>", line 1
type(print("testing))
^
SyntaxError: invalid syntax
>>> a = print("testing")
File "<stdin>", line 1
a = print("testing")
^
SyntaxError: invalid syntax
Python3.4
>>> type(print("{}"))
{}
<class 'NoneType'>
>>> a = print("{}")
{}
>>> a
>>> type(a)
<class 'NoneType'>
In Python 2, print is a statement, not a function (unless you do from __future__ import print_function at the top of your module). This means that the parentheses around the thing you're printing are not part of a function call, but just treated as grouping parentheses. In the situation you describe ("{}") is the same as "{}" (the parens do nothing), so the format call works just like you'd expect if you wrote "{}".format(...).
In Python 3, print is a function, so the parentheses are not optional and can't be put in the wrong place. print returns None, so you're almost certainly going to get an error if you do print(something).something_else, since None doesn't have a something_else attribute.
In Python 2.7, print is a statement; this means that
print("{}").format("testing")
prints one expression, the result of the expression ("{}").format("testing"). That is, the format method is called on the (parenthesized) string before the print statement is evaluated. If you use
from __future__ import print_function
in the 2.7 examples, you'll get identical behavior to Python 3.
You're missing the closing quote after some strings (e.g. "testing).
As others are saying, Python 2 doesn't have a print() function, it has a print statement. Your strings (even if they were properly closed) are not what and where you think they are.
In Python 2, print is a statement keyword like raise, not a function. Parentheses aren't used for its arguments, and so print("{}").format("testing") is parsed as though you'd written print ("{}").format("testing"), which is the same as print(("{}").format("testing")). Because print is a statement, it cannot be used as an expression, and therefore it cannot have a return value.
If you want print in Python 2 to act like Python 3's print function, place this line at the top of your file:
from __future__ import print_function

python function: scope of function parameter initialized with default value [duplicate]

This question already has answers here:
"Least Astonishment" and the Mutable Default Argument
(33 answers)
Closed 8 years ago.
I have a python programming question, I am using a caching pattern to speed up computation, here is an example code:
def f(a=1, a_dict={}):
try:
b=a_dict['one']
print 'fetched from cache'
except:
b=10
a_dict['one']=10
print 'put in cache'
return b
Now if I call this function the first time the result is:
>>> f(1)
put in cache
10
I call again:
>>> f(1)
fetched from cache
10
This is nice a behaviour since it uses caching. However, I find it strange because the variable a_dict has been defined within the function, so once the function is over it should be out of scope... Note that this variable is not visible from outside the function:
>>> a_dict
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a_dict' is not defined
I would have guessed that when I call the function the second time, the default variable a_dict should have been initialized to {}, so I find it strange that when I call f() the second time the previous value of a_dict is somehow still in scope.
In summary, I would have expected to achieve the desired behaviour like this:
the_dict={}
f(1, the_dict)
# call second time
f(1, the_dict)
Because the object the_dict is passed by reference and hence stays in scope.
Can someone please explain the semantics of parameter initialization in a function and their scope?
Functions are objects in python, so default parameters can be thought of as 'members'. It is explained fully: http://effbot.org/zone/default-values.htm
To get the behaviour you expect, you can have the function defined as follows:
def f(a=1, a_dict=None):
if a_dict is None:
a_dict = {}
try:
b=a_dict['one']
print 'fetched from cache'
except:
b=10
a_dict['one']=10
print 'put in cache'
return b
This means that, rather than the {} being made when the function is defined (and therefore retained in it's object def), it's made when the function is run (and therefore is a local variable).

Python built-in type as function parameter [duplicate]

This question already has answers here:
Can I use the variable name "type" as function argument in Python?
(5 answers)
Closed 9 years ago.
I've decided to do some coding exercises at coderbyte.com and right in the first exercise (reverse a string) I found this:
def FirstReverse(str):
Even though it works, I don't think it's a good idea to use a built-in type name as a parameter. What do you think?
I know it's kinda silly, but it's my first question at stackoverflow! Thanks =)
In that function definition, str is supposed to be a string, not the built-in function str(). When you do this, you are overwriting the built-in function, so you won't be able to call str() inside the function f, but you can still using it outside. This is because scoping, you are overwriting it in the local scope of f:
def f(str):
print str(123) # will raise an error, because 'str' is not callable (i.e. a function) anymore
f("some string here")
print str(123) # OK
This is a very common mistake, the sooner you learn to avoid it, the sooner you will become a good programmer.
You can use "anything" except keywords as variable/parameter names.
It's usually not a good idea though - as in practically never.
Perhaps the example is from Python1 series where there was a string module, but no str type.
The use of list, dict, str as variable names is a common newby 'mistake'.
I think that it is not a good practice for tutorials, but works OK in practice in this example. I would frown if code was presented to me with that parameters name however.
The more interesting thing to explore is WHY doesn't this tramp on the built-in str function.
Look:
>>> str(123) # the built-in prior to the function 'f' declared
'123'
>>> def f(str): # Note 'str' as parameter
... return str[::-1]
...
>>> f('123') # function works...
'321'
>>> f(str(123)) # function 'f' works with the function 'str' prior
'321'
>>> str(123) # built-in 'str' still works...
'123'
The answer is that in f the str parameter overrides the built-in str function only locally -- inside of f. It is 'restored' to the built-in str after the scope of f is done.
Notice:
>>> def f(str):
... return str('123')[::-1]
...
>>> f(123)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in f
TypeError: 'int' object is not callable
Since you are calling int inside f you are referring to the parameter, not the function. It gets confusing and, hence, not a great idea to use the name of a built-in as a variable, parameter, etc whether local or global.
I'm not the one that voted Christian's answer down but here's an elaboration if it helps:
Working Function
def f(string):
print ("In function.")
print (string)
print (type(string))
real_string = str(string)
print (type(real_string))
print ("In main.")
int_val = 123
print (type(int_val))
f(int_val)
Results
In main.
In function.
123
class 'int'
class 'str'
Broken Function
def f(str):
print ("In function.")
print (str)
print (type(str))
real_string = str(str)
print (type(real_string))
print ("In main.")
int_val = 123
print (type(int_val))
f(int_val)
Results
----> 5 real_string = str(str)
TypeError: 'int' object is not callable

Categories

Resources