Python core programming 2 Chapter 3 after-school exercises, python after-school exercises

Source: Internet
Author: User

Python core programming 2 Chapter 3 after-school exercises, python after-school exercises

1. identifier. Why is variable name and variable type declaration not required in Python?

Variables in Python do not need to be declared. Variable assignment is a process of variable declaration and definition. Each variable created in the memory contains the variable identifier, name, and data. Each variable must be assigned a value before it can be used.

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

In Python, the def keyword is used to define functions. functions include function names and parameters. No return type is required. Python can return any type function without defining the return type. In fact, each function has a return value, the default value is None (null value of python ).

3. identifier. Why should we avoid double underscores (_) at the beginning and end of the variable name?

It has a special meaning in python, indicating the system definition name to prevent system script errors.

4. How does python write multiple statements in one row?

Multiple statements written in the same row of books are separated by a comma (;).

5. Statements. In Python, can a statement be divided into multiple lines for writing?

Write multiple lines of books. Add a backslash (\) to the headers of the line of statements.

6 variable assignment

(A) What values will be assigned to the values x, y, z = 1, 2, and 3 in x, y, and z?

X = 1 y = 2 z = 3

(B) After z, x, y = y, z, x is executed, what values are contained in x, y, and z?

Z = 2 x = 3 y = 1

7. identifier. Which of the following are valid Python identifiers? If not, describe the reason! Which of the following keywords are valid identifiers?

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

Int32, printf, _ print, this, self, _ name _, bool, true, type, thisavar, R_U_Ready, Int, True, do, and access are valid Python identifiers.

Print and if are valid Python identifiers and keywords.

4.0XL, $ aving $, 0X40L, big-daddy, 2hot2touch, thisn' tAVar, counter-1, and-are not Python's legal identifiers.

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

MakeTextFile. py

#! / usr / bin / env python
#-*-coding: utf-8-*-
import os
ls = os.linesep
#Import the os module to get the current system line terminator
#Get the file name of the fname variable
while True:
        fname = raw_input ("Enter filename:")
        try:
                if os.path.exists (fname):
                        print "ERROR: '% s' already exists"% fname
                else:
                        break
        except:
                print "*** file open error:", e
#Enter the file name, if there is a prompt, there is no end to loop and enter the next program
all = []
print "\ nEnter lines ('.' by itself to quit). \ n"
#Prompt to use.quit
while True:
        entry = raw_input ('>')
        if entry == '.':
                break
        else:
                all.append (entry)
#Cycle, if there is. End the loop, add in other cases.
fobj = open (fname, 'w')
fobj.writelines (['% s% s'% (x, ls) for x in all])
#Enter every line entered
fobj.close ()
print 'DONE!
 


readTextFile.py

#! / usr / bin / env python

#-*-coding: utf-8-*-

fname = raw_input ("Enter filename:")

#Prompt to enter the file name to be read

print

try:

    fobj = open (fname, 'r')

    #Open the file in read mode

except IOError, e:

    print "*** file open error:", e

    #If something goes wrong

else:

    for eachLine in fobj:

    print eachLine,

    fobj.close ()

#Print out each line and close
9. Transplant. If you have Python installed on different types of computer systems, check whether the value of os.linesep is different. Note the type of operating system and the value of linesep.

 

RedHat


 

WindowsXP

10. Abnormal. Replace the call to os.path.exists () in readTextFile.py makeTextFile.py with a method like exception handling in readTextFile.py In turn, replace the exception handling method in readTextFile.py with os.path.exists ().

 

#! / usr / bin / env python
#-*-coding: utf-8-*-
'readTextFile.py-read and display text file'
#fname variable get file name
import os
fname = raw_input ('Enter filename:')
if os.path.exists (fname):
        #fobjObject read mode to open the file
        fobj = open (fname, 'r')
        for eachLine in fobj:
                print eachLine.strip ()
        fobj.close ()
else:
        print "No this file"
 

11. String formatting No longer suppress the NEWLINE character generated by the print statement in readTextFile.py, modify your code, and delete the blank at the end of each line before displaying it. This way, you can remove the comma at the end of the print statement. Tip: Use the strip () method of string objects

 

#! / usr / bin / env python
#-*-coding: utf-8-*-
'readTextFile.py-read and display text file'
#fname variable get file name
import os
fname = raw_input ('Enter filename:')
if os.path.exists (fname):
        #fobjObject read mode to open the file
        fobj = open (fname, 'r')
        for eachLine in fobj:
                print eachLine.strip ()
        fobj.close ()
else:
        print "No this file"
 

12. Merge source files. Combine the two programs into one, give it a name you like, for example readNwriteTextFiles.py. Let the user choose whether to create or display a text file.

 

#! / usr / bin / env python
#-*-coding: utf-8-*-
import os
ls = os.linesep
while True:
    print "" "
        1.readTextFile
        2.makeTextFile
        3.quit
        4.make the already Text File
    "" "
    choose = raw_input ("please find the choose")
    if choose == '1':
        print "You choose 1"
        while True:
            fname = raw_input ("enter the name:")
            if os.path.exists (fname):
                print "the name is already exists!"
            else:
                break
        all = []
        print "\ n Enter lines ('.' by itself to quit) \ n"
        while True:
            entry = raw_input (">")
            if entry == '.':
                break
            else:
                all.append (entry)
        fobj = open (fname, 'w')
        fobj.writelines (['% s% s'% (x, ls) for x in all])
        fobj.close ()
        print "DONE!"
    if choose == '2':
        print 'You choose 2'
        fname = raw_input ("please choose the file:")
        fobj = open (fname, 'r')
        for eachLine in fobj:
            print eachLine,
            fobj.close
    if choose == '3':
        break
    if choose == '4':
        fname = raw_input ("please choose the file:")
        all = []
        while True:
            entry = raw_input (">")
            if entry == '.':
                break
            else:
                all.append (entry)
        fobj = open (fname, 'w')
        fobj.writelines (['% s% s'% (x, ls) for x in all])
        fobj.close ()
        print "DONE!"
 


Python script learning process recommendation
Learning process:

One: lay a good foundation
1. Find a suitable introductory book (recommended Python core programming 2, Dive into Python), read it roughly once, loop, judge, commonly used classes, understand
2. Diligent practice python exercises (Python core programming 2 has a large number of after-school exercises)
3. Join the Python discussion group and ask if you do n’t understand
4. Write a python learning summary blog
2: Start using Python to do some of your daily work
Such as Python search files, Python batch processing, etc., web crawlers, etc.
Three: Start learning Django, Flask, Tornado and other framework to develop some web applications
----------------------------
Resource recommendation:
"Concise Python Tutorial"
"Learning Programming with Children"
"Head First Python Chinese Version"
"Stupid Ways to Learn Python"
"Dive.Into.Python Chinese version (with course source code)"
"Python Core Programming"
"In-depth understanding of Python"
"Python Standard Library"
"Python Programming Guide"
"Diango_book Chinese version"
For more in-depth system learning, please see the python official website document and django official website document. Diligently studying, summarizing, practicing and practicing can slowly learn python.
 
What is the point of python learning? There is a second version of Python core programming, how should this book be used better

Python is the fourth generation programming language, the entry threshold is relatively low, and entry is fast.
In order to cultivate interest at the beginning, you can write some small script examples, such as batch processing of files, regular matching, etc .;
For other network applications can also be involved.
If you want to go deeper, you need to have a relevant understanding of object-oriented.
The book "Core Programming" is a collection of the results of the online python forum. It is more practical and can be learned by example.
Then you can look for the popular python framework and python open source project to see the source code.
But in general, Python efficiency has a bottleneck, and it generally plays the role of script connection and batch processing in large systems.

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.