[Tutor] 2 basic problems
Chris “Kwpolska” Warrick
kwpolska at gmail.com
Sun Jun 16 17:45:34 CEST 2013
On Wed, May 29, 2013 at 11:23 PM, charles benoit
<feather.duster.kung.fu at gmail.com> wrote:
> 1:Python 2.7.4 (default, Apr 19 2013, 18:32:33)
> [GCC 4.7.3] on linux2
> Type "copyright", "credits" or "license()" for more information.
>>>> 4+4
> 8
>>>> 3+3=4
> SyntaxError: can't assign to operator
>>>> 3=1
> SyntaxError: can't assign to literal
>>
> I thought the last 2 lines should return False
`=` is the assignment operator (`a = 2` sets the variable `a` to the
value of `2`), whereas `==` is the comparison operator.
> 2:
> lot=('1'+'6'+'8')
> print(lot)
> a=open("acc","w")
> a.write(lot)
> a.close
missing `()` here
> b=open("acc","r")
> b.read()
> print (b)
1. There should be no parenthesis here in Python 2.
2. The proper syntax is `print b.read()`. You are reading the text
and discarding the return value (you aren’t setting a variable to it
or passing it to something else, like print), then printing the
information of what the `b` object is.
> b.close
missing `()` here, too
>
>
> returns
prints*, there is no return value
>>>>
> 168
> <open file 'acc', mode 'r' at 0xb6f9a650>
>>>>
>
> I thought I was saving a string to a file and reading and printing the
> string. The output looks like a description of the IO textwrapper at some
> location. I'm sure this is a syntax/format problem.but this like the other
> examples I saw. I ran this using python 2.6.7 on ubuntu 13.0 Thank you for
> any help
Please use the 2.7.4 interpreter (the same one you used for the first
example) instead.
Moreover, you could do it all in one step ('w+' stands for “clear file
and allow read/write output”, while f.seek(0) is used to return the
pointer back to the beginning of the file):
f = open('acc', 'w+')
f.write(lot)
f.seek(0)
print f.read()
f.close()
Or using the `with` syntax (a.k.a. the context manager syntax):
with open('acc', 'w+') as f:
f.write(lot)
f.seek(0)
print f.read()
--
Kwpolska <http://kwpolska.tk> | GPG KEY: 5EAAEA16
stop html mail | always bottom-post
http://asciiribbon.org | http://caliburn.nl/topposting.html
More information about the Tutor
mailing list