Python Core Programming 2 Chapter III after-school exercises

Source: Internet
Author: User

1. The identifier. Why don't I need variable names and variable type declarations in Python?

Variables in Python do not need to be declared, and the assignment of variables is the process of declaring and defining variables. Each variable is created in memory and includes information about the identity, name, and data of the variable. Each variable must be assigned before it is used, and the variable will not be created until the variable is assigned.

2. The identifier. Why does the function type not need to be declared in Python?

Python uses the DEF keyword to define functions, functions that include function names and parameters, do not need to define return types, Python can return any type of function that does not have a return type defined, and in fact each function has a return value that defaults to none (Python's null value).

3. The identifier. Why should you avoid using double underlines at the beginning and end of variable names?

Special meaning in Python, indicating system-defined names to prevent system script errors

4.python How many statements are written in one line?

Write multiple statements on the same line using (;) number separated

5. Statements. Can I write a statement into multiple lines in python?

MultiRow Write, add a backslash (\) to the row of the line statement

6 Assigning Values to variables

(a) Assignment statement x, y, z = 1, 2, 3 What values will be assigned in X, Y, z respectively?

X=1 y=2 z=3

(b) z, x, y = y, z, x, what are the values in X, Y, Z, respectively?

z=2 x=3 Y=1

7. The identifier. Which of the following are the valid Python identifiers? If not, please explain why! What are the keywords in the legal identifiers?

Valid identifiers: The first character must be a letter or an underscore (_), and the remaining characters can be letters and numbers or underscores

Int32, printf, _print, this, self, __name__, bool, True, type, Thisisavar, R_u_ready, Int, True, do, access is a valid Python identifier.

Print, if, is a python-valid identifier and is a keyword.

4.0XL, $aving $, 0x40l, Big-daddy, 2hot2touch, Thisisn ' Tavar, counter-1,-not a Python legal identifier.

8.Python code. Copy the script to your file system, and then modify it. You can add comments, modify the change prompt (' > ' is too monotonous), and so on, and modify the code to make it look more comfortable.

maketextfile.py

#!/usr/bin/env python#-*-coding:utf-8-*-ImportOsls=Os.linesep#Import the OS module to get the current system line terminator#get the file name of the fname variable whileTrue:fname=raw_input ("Enter FileName:")        Try:                ifos.path.exists (fname):Print "ERROR: '%s ' already exists"%fnameElse:                         Break        except:                Print "* * * File Open error:", E#Enter the file name, if there is a hint exists, there is no end loop to enter the next programall =[]Print "\nenter lines ('. ' by itself to quit). \ n"#tips for using. Quit whileTrue:entry=raw_input ('>')        ifentry=='.':                 Break        Else: All.append (Entry)#Loop, if there is. End loop, add other cases.Fobj =open (fname,'W') Fobj.writelines (['%s%s'% (X,ls) forXinchAll ])#enter each line in the inputfobj.close ()Print 'done!

readtextfile.py

#!/usr/bin/env python#-*-coding:utf-8-*-fname=raw_input ("Enter FileName:")#prompt to enter the file name to readPrintTry: Fobj=open (fname,'R')    #open a file in read modeexceptioerror,e:Print "* * * File Open error:", E#if error is indicatedElse:     forEachlineinchFobj:PrintEachline, Fobj.close ()#print out each line, and close

9. Transplant. If you have Python installed on different types of computer systems, check to see if the value of OS.LINESEP is different. Note the type of the operating system and the value of LINESEP.

RedHat

Windows xp

10. Exceptions. Replace the call to Os.path.exists () in readtextfile.py maketextfile.py with a method similar to exception handling in readtextfile.py. In turn, the exception handling method in readtextfile.py is replaced with os.path.exists ().

#!/usr/bin/env python#-*-coding:utf-8-*-'readtextfile.py--Read and display text file'#fname variable get file nameImportOsfname=raw_input ('Enter FileName:')ifos.path.exists (fname):#Fobj Object read mode open fileFobj=open (fname,'R')         forEachlineinchFobj:PrintEachline.strip () fobj.close ( )Else:        Print "No This file"

11. String formatting no longer suppresses the NEWLINE characters generated by the print statement in readtextfile.py, modify your code to remove whitespace at the end of each line before displaying a row. This way, you can remove the comma at the end of the print statement. Tip: Use the Strip () method of a String object

#!/usr/bin/env python#-*-coding:utf-8-*-'readtextfile.py--Read and display text file'#fname variable get file nameImportOsfname=raw_input ('Enter FileName:')ifos.path.exists (fname):#Fobj Object read mode open fileFobj=open (fname,'R')         forEachlineinchFobj:PrintEachline.strip () fobj.close ( )Else:        Print "No This file"

12. Merge the source files. Combine the two-segment program into one, giving it a name you like, such as readnwritetextfiles.py. Let the user choose whether to create or display a text file.

#!/usr/bin/env python
#-*-coding:utf-8-*-
ImportOsls=Os.linesep whileTrue:Print """1.readTextFile 2.makeTextFile 3.quit 4.make the already Text File"""Choose=raw_input ("Please find the Choose") ifChoose = ='1': Print "You choose 1" whileTrue:fname=raw_input ("Enter the name:") ifos.path.exists (fname):Print "The name is already exists!" Else: Break All=[] Print"\ n-Enter lines ('. ' by itself to quit) \ n" whileTrue:entry=raw_input (">") ifEntry = ='.': Break Else: All.append (entry) Fobj=open (fname,'W') Fobj.writelines (['%s%s'% (X,ls) forXinchAll ]) Fobj.close ()Print "done!" ifchoose=='2': Print 'You choose 2'fname=raw_input ("Please choose the file:") Fobj=open (fname,'R') forEachlineinchFobj:PrintEachline, Fobj.closeifchoose=='3': Break ifchoose=='4': fname=raw_input ("Please choose the file:") All=[] whileTrue:entry=raw_input (">") ifentry=='.': Break Else: All.append (entry) Fobj=open (fname,'W') Fobj.writelines (['%s%s'% (X,ls) forXinchAll ]) Fobj.close ()Print "done!"

Python Core Programming 2 Chapter III after-school exercises

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.