- Python also has a logical branch key \. Like in MATLAB...
- Input and Output
#! /Usr/bin/Python
# Filename: using_file.py
Poem = '' '\
Programming is fun
When the work is done
If you wanna make your work also fun:
Use python!
' ''
F = file ( 'Poem.txt' , 'W' ) # Open for 'W' riting
F. Write (POEM) # Write text to file
F. Close () # Close the file
F = file ('Poem.txt' ) # If no mode is specified, 'R' EAD mode is assumed by default
While True:
Line = f. Readline ()
If Len (line) = 0: # Zero Length indicates EOF
Break
Print line, # Notice comma to avoid automatic newline added by Python
F. Close () # Close the file
Note: When opening a file in Python, the default open mode is read open.
#! /Usr/bin/Python
# Filename: raising. py
Class shortinputexception (exception ):
'' 'A user-defined exception class .' ''
Def _ init _ (self, length, atleast ):
Exception. _ init _ (Self)
Self. Length = Length
Self. Atleast = atleast
Try:
S = raw_input ( 'Enter something -->' )
If Len (s) <3:
Raise shortinputexception (LEN (s), 3)
# Other work can continue as usual here
Failed t eoferror:
Print '\ Nwhy did you do an EOF on me? '
Except t shortinputexception, X:
Print 'Shortinputexception: the input was of length % d ,\
Was expecting at least % d' % (X. length, X. Atleast)
Else :
Print 'No exception was raised .'
Note that exception can be dropped by raise, which addsProgramThe robustness is very good.
#! /Usr/bin/Python
# Filename: Finally. py
Import time
Try:
F = file('poem.txt ')
While true: # Our usual file-reading Idiom
Line = f. Readline ()
If Len (line) = 0:
Break
Time. Sleep (2)
Print line,
Finally:
F. Close ()
Print 'cleaning up... closed the file'
Python latency method. When an exception occurs in Python, the statement block in finally is executed. The function of this program is to disable the file.