Python core programming version 2, 308th page, Chapter 2 exercises

Source: Internet
Author: User

The answer in this blog is not from official resources, but from my own exercises. If you have any questions or errors, please discuss them.

11-1.
Parameters. Compare the following three functions:
Def countToFour1 ():
For eachNum in range (5 ):
Print eachNum

Def countToFour2 (n ):
For eachNum in range (n, 5 ):
Print eachNum

Def countToFour3 (n = 1 ):
For eachNum in range (n, 5 ):
Print eachNum

What do you think will happen if the following input is given until the program output? Enter 11.2 In the output table. If you think an Error occurs in the given input, enter "Error" or "NONE" if there is no output ".
[Note] Table 11.2 mentioned in the question is the table under question 11-2 on this page. That is to say, it depends on the input values of 2, 4, 5, and nothing to the three functions. What will happen.
[Answer]
The Code is as follows:

>>> def countToFour1():...     for eachNum in range(5):...             print eachNum...>>> def countToFour2(n):...     for eachNum in range(n, 5):...             print eachNum...>>> def countToFour3(n = 1):...     for eachNum in range(n, 5):...             print eachNum...>>> countToFour1(2)Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: countToFour1() takes no arguments (1 given)>>> countToFour2(2)234>>> countToFour3(2)234>>> countToFour1(4)Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: countToFour1() takes no arguments (1 given)>>> countToFour2(4)4>>> countToFour3(4)4>>> countToFour1(5)Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: countToFour1() takes no arguments (1 given)>>> countToFour2(5)>>> countToFour3(5)>>> countToFour1()01234>>> countToFour2()Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: countToFour2() takes exactly 1 argument (0 given)>>> countToFour3()1234

 

11-2.
Function. Create a function and return the sum and product of two numbers.

[Note] the question is modified according to the English version.

[Answer]

The Code is as follows:

def func(a, b):    c = a * b    d = a + b    return c, da = raw_input("Please input the first number: ...  ")# From www.cnblogs.com/balian/b = raw_input("Please input the second number: ...  ")print Multi_P(float(a), float(b))

 

11-3.
Function. In this exercise, we will implement the max () and min () built-in functions.

(A) write two elements respectively to return a large and small element, simple max2 () and min2 () functions. They should be able to operate with any Python object. For example, max2 () and min2 () each return 8 and 4.

(B) Create new functions my_max () and my_min () that use the solution in Section a to reconstruct max () and min (). These functions return the maximum and minimum values of a non-empty queue respectively. They can also take a set of parameters as input. Use numbers and strings to test your solution.

[Answer]

(A) The Code is as follows:

def max2(a, b):if a >= b:return aelse:return bdef min2(a, b):if a >= b:return belse:return a

(B) The Code is as follows:

def max2(a, b):    if a >= b:        return a    else:        return bdef min2(a, b):    if a >= b:        return b    else:        return a    def my_max(*List):    Max = List[0]    for eachItem in List:        Max = max2(eachItem, Max)    return Maxdef my_min(*List):    Min = List[0]    for eachItem in List:        Min = min2(eachItem, Min)    return Minprint my_max(3,6,9,2,8)print my_min(3,6,9,2,8)

 

[Unfinished] the max () and min () functions can process a list of parameters. For example, the result of max ([1, 2, 3]) is 1. The result of my_max ([1, 2, 3]) is [1, 2, 3]. The program also needs to be improved.

 

11-4.
Return Value. Create a complementary function for your solution in step 5-13. Create a total time in units and return an equivalent total time in hours and units.

[Answer]

The Code is as follows:

def conversion(a, b):    return a * 60 + btime = raw_input('Please input the time in HH:MM format: ... ')print time, 'equals to't = time.split(':')print conversion(int(t[0]), int(t[1])), 'minutes'# From www.cnblogs.com/balian/

 

11-5.
Default parameter. Update the sales tax script you created in Exercise 5-7 so that the sales tax rate is no longer a required parameter of the function. Use your local tax rate as the default parameter.

[Answer]

The Code is as follows:

def tax(pureprice, rate = 0.13):    return pureprice * ratepurePrice = float(raw_input('Please input the price: ... '))print 'You should pay:'print 'Subtotal:  %10.2f ' % purePriceprint 'Sales Tax: %10.2f ' % tax(purePrice)# From www.cnblogs.com/balian/

 

11-6.
Variable length parameter. Write a function called printf. There is a value parameter in the format string. The rest is the variable parameters to be displayed on the standard output based on the formatted string value. The value in the formatted string allows special string format operation indicators, such as % d, % f, etc. Tip: the solution is trivial-you do not need to implement the function of the string operator, but you need to use the string formatting operation (% ).

[Note] the original English version of the question is attached:

Variable-Length Arguments. write a function called printf (). there is one positional argument, a format string. the rest are variable arguments that need to be displayed to standard output based on the values in the format string, which allows the special string format operator directives such as % d, % f, etc. hint: The solution is trivial-there is no need to implement the string operator functionality, but you do need to use the string format operator (%) explicitly.

[Answer]

The Code is as follows:

>>> def printf(fmt, *args):...     print fmt % args...

 

[Execution result]
>>> Printf ('% s', 'Tom ')

Tom

>>> Printf ('% d', 12)

12

>>> Printf ('% F', 12)

12.000000

>>>

[Reference]

For more information, see the following link:

Http://www.velocityreviews.com/forums/t676359-emulate-a-printf-c-statement-in-python.html

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.