Python core programming version 2, 36th page, Chapter 2 exercise continued 2-answers to Python core programming-self-developed-

Source: Internet
Author: User
Tags builtin

2-11.
A program with a text menu. Write a program with a text menu. The menu items are as follows: (1) take the sum of the five numbers; (2) Take the average of the five numbers... (X) and exit. The user makes a selection and then executes the corresponding functions. The program ends when the user selects to exit. This program is useful because you do not need to restart your script over and over again during function switching (this is also useful for developers to test their own programs ).
[Answer]
The Code is as follows:
Def to_total ():
Total = 0
A = [1, 2, 3, 4, 5]
For I in range (0, 5 ):
Print 'Please input number', I + 1
A [I] = float (raw_input ())
Total = total + a [I]
Print total

Def to_average ():
Total = 0
A = [1, 2, 3, 4, 5]
For I in range (0, 5 ):
Print 'Please input number', I + 1
A [I] = float (raw_input ())
Total = total + a [I]
Print total/5.

Print 'Please select... \ N'
Print '(1) To get the total of 5 numbers, please input letter ""...'
Print '(2) To get the average of 5 numbers, please input letter "B "...'
Print '(x) To quit, please input letter "x"... \ N'
Choice = raw_input ('your choice is ...')
If choice = 'A ':
To_total ()
Elif choice = 'B ':
To_average ()
Elif choice = 'X': pass
[Not finished] There is still room for optimization of this Code. In addition, it does not check whether the input is not a number.

2-12.
Dir () built-in functions.
(A) Start the Python interactive interpreter. Press dir () and press enter to execute the dir () built-in function. What do you see? Show the value of each list element you see, and write down the actual value and the expected value.
(B) What is the dir () function? We already know that adding a pair of parentheses behind the dir can execute the dir () built-in function. What if no parentheses are added? Try it. What information will the interpreter return to you? What do you think this information means?
(C) type () built-in functions receive arbitrary Python objects as parameters and return their types. Type (dir) in the interpreter to see what you get.
(D) In the last part of this exercise, let's take a look at the Python document string. You can use dir. _ doc _ to access the document string of the dir () built-in function. Print dir. _ doc _ can display the content of this string. Many built-in functions, methods, modules, and module attributes have corresponding document strings. We hope that you will also write document strings in your code, which will provide timely and convenient help to those who use the code.
[Answer]
The Code is as follows:
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C: \ Documents ents and Settings \ root> python
Python 2.7 (r27: 82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> Dir ()
['_ Builtins _', '_ doc _', '_ name _', '_ package _']
>>> Dir
<Built-in function dir>
>>> Type (dir)
<Type 'builtin _ function_or_method '>
>>> Dir. _ doc __
"Dir ([object])-> list of strings \ n \ nIf called without an argument, return the names in the current scope. \ nElse, return an alphabetized list of names comprisin
G (some of) the attributes \ nof the given object, and of attributes reachable from it. \ nIf the object supplies a method named _ dir __, it will be used; otherwise
\ Nthe default dir () logic is used and returns: \ n for a module object: the module's attributes. \ n for a class object: its attributes, and recursively the attr
Ibutes \ n of its bases. \ n for any other object: its attributes, its class's attributes, and \ n recursively the attributes of its class's base classes ."
>>> Print dir. _ doc __
Dir ([object])-> list of strings

If called without an argument, return the names in the current scope.
Else, return an alphabetized list of names comprising (some of) the attributes
Of the given object, and of attributes reachable from it.
If the object supplies a method named _ dir __, it will be used; otherwise
The default dir () logic is used and returns:
For a module object: the module's attributes.
For a class object: its attributes, and recursively the attributes
Of its bases.
For any other object: its attributes, its class's attributes, and
Recursively the attributes of its class's base classes.
>>>

2-13.
Use dir () to find more information in the sys module.
(A) Start the Python interactive interpreter and execute the dir () function. Type import sys to import the sys module. Run the dir () function again to confirm that the sys module is correctly imported. Run dir (sys) to view all the attributes of the sys module.
(B) display the version number attributes and platform variables of the sys module. Remember to add sys. Before the attribute name, which indicates that this attribute belongs to the sys module. The version variable stores the version of the Python interpreter you are using. The platform attribute contains the information about the computer platform used when you run Python.
(C) Finally, call the sys. exit () function. This is another way of introducing the Python interpreter besides the hot key.
[Answer]
The Code is as follows:
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C: \ Documents ents and Settings \ root> python
Python 2.7 (r27: 82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> Dir ()
['_ Builtins _', '_ doc _', '_ name _', '_ package _']
>>> Import sys
>>> Dir ()
['_ Builtins _', '_ doc _', '_ name _', '_ package _', 'sys ']
>>> Dir (sys)
['_ Displayhook _', '_ doc _', '_ thook _', '_ name __', '_ package _', '_ stderr _', '_ stdin _', '_ stdout _', '_ clear_type_cache ', '_ current_frames', '_ g
Etframe ', 'api _ version', 'argv', 'builtin _ module_names', 'byteorder', 'Call _ tracing', 'callstats', 'copyright ', 'displaycall', 'lhandle', 'dont _ write_bytecode
', 'Exc _ clear', 'exc _ info', 'exc _ type', 'mongothook', 'exec _ prefix', 'executable', 'eg ', 'flags ', 'float _ info', 'float _ repr_style', 'getcheckinterval ', 'getde
Faultencoding ', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit ', 'getrefercount', 'getsize', 'gettrack', 'getwindowsversion', 'hversion', 'long _ inf
O ', 'maxint', 'maxsize', 'maxunicode', 'meta _ path', 'modules', 'path', 'path _ hooks ', 'path _ importer_cache ', 'Platform', 'prefix', 'ps1', 'ps2 ', 'py3kwarning ','
Setcheckinterval ', 'setprofile', 'setcursionlimit ', 'settrack', 'stderr', 'stdin', 'stdout', 'subversion', 'version ', 'version _ info', 'waroptions', 'winver ']

>>> Sys. version
'2.7 (r27: 82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)]'
>>> Sys. platform
'Win32'
>>> Sys. exit ()

C: \ Documents ents and Settings \ root>

2-14.
Operator priority and bracket grouping. Rewrite the arithmetic expression in the print statement in Section 2.4, and try to add appropriate parentheses in the expression so that it can work properly.
[Answer]
The Code is as follows:
>>> Print-2*4 + 3 ** 2
1
>>> Print-2 * (4 + 3) ** 2
-98
>>> Print (-2*(4 + 3) ** 2
196
>>>

The answer here is not from official resources, but from my own exercises, which may be incorrect.

 

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.