Python initial experience (5)

Source: Internet
Author: User
    • 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.
    • Exception
 #! /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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.