[Tutor] how do I set variables in Python 3.4

Alan Gauld alan.gauld at btinternet.com
Sun Jul 13 10:57:48 CEST 2014


On 13/07/14 08:25, Danielle Salaz wrote:
> This is what I've been doing, also I'm using version 3.4
>
> set "(operand1 = 2 and operand2 = 7)

Do you by any chance have some Lisp or Scheme experience?
That looks like a Lispy kind of syntax...

Whatever, in Python you don't need to use words
like set or let when assigning values to names.
The above line is meaningless to Python,
hence the errors.

To assign a value you simply do the assignment directly.

operand1 = 2
operand2 = 7


> print (operand1 = 2)

The print function displays output on the screen.
It converts its input (between the parentheses)
to strings for you. But it cannot do assignments.
Your print statement could look like

print(2)   # print a literal value

or

print(operand1)  # print a symbol's value

> print (result=operand1 + operand2)

Again this is trying to print what is inside the parentheses
But it can't execute the assignment. You need to assign
outside the print (or just print the expression).
So you could do it like this:


print (operand1 + operands2)   # print() evaluates and prints result

or

result = operand1 + operand2
print(result)        # just print the stored value

> Traceback (most recent call last):
>    File "C:/Python34/Assignment3_DanielleSalaz.py", line 1, in <module>
>      print (operand1 = 2)
> TypeError: 'operand1' is an invalid keyword argument for this function

See the comments above.

Its possible you have seen code that looks like this before but
that is due to a slightly confusing feature of Python.

Python functions have parameters. Some parameters have default
values so you don't always need to supply them. If you want to change 
one of these default values you can do it by assigning a value in the 
function call. But that is the only kind of assignment you are allowed 
to do, it must be to one of the functions defaulted parameters.

In this case the print function does not have a default parameter called 
operand1 so you cannot do an assignment to operand1 inside
the print function call. So although you might see code like

print(x,y,sep='-')

the sep assignment is a special operation specific to the print function
you cannot assign arbitrary values to arbitrary names inside the 
function. This is true of any function, not just print().

If you didn't understand those last 4 paragraphs don't worry, you
will get to it later in your course and all will become clear,
I hope. They were written on the assumption that you are coming
to python from another language such as Lisp...


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list