. , , ? ? .
, ? , .
print . print Print ? . , .
>>> Print(" ")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Print' is not defined
>>> print(" ")
NameError , . .
. , . , [-d] [-z] . ( , [-c] ).
>>> s = input('Enter something --> ')
Enter something --> Traceback (most recent call last):
File "<stdin>", line 1, in <module>
EOFError
EOFError , , ( -d ) .
try..except . , , '' .
(_.py ):
try:
= input(' --> ')
except EOFError:
print(' ??')
except KeyboardInterrupt:
print(' .')
else:
print(' {} '.format())
:
# + d
$ python _.py
--> ?
# + c
$ python _.py
--> ^C .
$ python _.py
-->
/ try , / except / . except , , / . , .
try except . , ?
, , . .
try..except else . , else .
, .
/ , , raise .
, Exception .
(_.py ):
class (Exception):
''' .'''
def __init__(self, , ):
Exception.__init__(self)
self. =
self. =
try:
text = input(' --> ')
if len(text) < 3:
raise (len(text), 3)
# .
except EOFError:
print(' - ?')
except as :
print((': ' +
'{} , {1} ')
.format(., .))
else:
print(' .')
:
$ python _.py
-->
ShortInputException: 1 , 3
$ python _.py
-->
.
, . . - length , atleast .
except , , / as () . . except , , length atleast .
...
. , , ? finally .
_.py:
import sys
import time
= None
try:
= open(".txt")
#
while True:
= .readline()
if len() == :
break
print(, end='')
sys.stdout.flush()
print(" +c ")
#
time.sleep(5)
except IOError:
print(".txt ")
except KeyboardInterrupt:
print("!! .")
finally:
if :
.close()
print("( : )")
:
$ python _.py
,
+C .
^C!! .
( : )
, , time.sleep 2 ( ). , / + c .
KeyboardInterrupt . , , finally , .
0 None False . if f: .
, print sys.stdout.flush() .
with
try , finally . , with :
__.py :
with open(".txt") as :
for in :
print(, end='')
. , open with - with open .
, with . , open ; '' .
, .__enter__, .__exit__ .
, finally __exit__ . , try..finally .
, PEP 343- .
try..except try..finally . .
, .