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

Source: Internet
Author: User

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

2-1 variables, print and string formatting operators. Start the interactive interpreter. Assign values to some variables (string, value, etc.) and display their values by entering the variable name. Use the print statement to do the same thing. What is the difference between the two? Also try to use the character string format operator % and do it several times to get familiar with it.

Print is used to display the content of a variable. When only the variable name is used, the output string is enclosed in single quotes, so that non-string objects can be displayed on the screen as strings, the print statement uses the str () function to display objects. The interactive interpreter calls the repr () function to display objects.

2-2 program output. Read the following Python script:

#! /Usr/bin/env python

1 + 2*4

(A) What do you think this script is used?

(B) What do you think the script will output?

(C) enter the above Code, save it as a script, and then run it. Does it do the same as you expected? Why?

Sample/different?

(D) How is the code executed separately different from that in the interactive interpreter? Try it and write the result

(E) How to Improve the script so that it can work as you think? Why is the same/different?

(A) Operations 1 + 2*4 (B) only perform operations and do not output (c) operations without displaying results (d) after an interactive interpreter inputs a statement, it returns the statement result (e) print '1 + 2*4' 2-3 Numeric and operator. Start the interactive interpreter and use Python to add, subtract, multiply, and divide two values (of any type. Then The remainder operator is used to obtain the remainder of the two numbers, and the multiplication operator is used to calculate the power B of the number.  2-4 Use the raw_input () function to obtain user input.

(A) Create a script using the raw_input () built-in function to get a string from the user input, and then display

The string you just typed.

(B) Add a similar piece of code, but this time the input is a numerical value. Converts the input data into a numeric object,

(Enable

Use int () or other numeric conversion functions) and display the value to the user. (Note: If you use a version earlier than 1.5

You need to use the string. ato * () function to execute this conversion)

()
#!/usr/bin/env pythonstring =raw_input("please type the string:\n")print string
(B)
#!/usr/bin/env pythonstring =input("please type the string:\n")print stringprint type(string)

2-5

Loops and numbers

Use while and for to create a loop:

(A) Write a while LOOP, and the output integer ranges from 0 to 10.

(Make sure it is from 0 to 10, instead of from 0 to 9 or

From 1 to 10)

(B) Do the same thing as (a), but this time we use the range () built-in function.

()
#!/usr/bin/env pythoni=0while i<=10:        print i        i+=1

(B)
#!/usr/bin/env pythonfor counter in range(11):        print counter

2-6

Condition judgment

Determine whether a number is positive or negative, or equal to 0. Start with a fixed value.

Then modify your code to support user input and judgment.

#!/usr/bin/env pythonvalue=input("please type the value:\n")if value>0:        print "This number is positive"elif value<0:        print "This number is negative"else:        print "This number is zero"

2-7

Loop and string

Receives a string input from the user, and displays the string by character. Use while

Loop implementation, and then use the for loop implementation.

#! /Usr/bin/env python #-*-coding: UTF-8-*-string = raw_input ("please type the string: \ n ") print "for loop completion show string by character" for I in string: print iprint "while loop completion show string by character" j = 0 while j <len (string ): print string [j] j + = 1

2-8 Loop and operator. Create a list or tuples containing five fixed values to output their sums. Then repair Change your code to accept user input values. Use the while and for loops respectively.
#! /Usr/bin/env python #-*-coding: UTF-8-*-aList =, 5] j = 0 print "for loop and" for I in aList: print I j + = iprint jprint "while loop to implement the output list and" j = 0i = 0 while I <len (aList ): j + = aList [I] print aList [I] I + = 1 print j

2-9 Loops and operators create a list or tuples containing five fixed values to output their average values. Difficulties in this exercise One of the vertices is to obtain the average value through division. You will find that Integer Division removes decimal places, so you must use floating point division to get more

Accurate results. Float () built-in functions can help you implement this function.

#! /Usr/bin/env python #-*-coding: UTF-8-*-aList = (, 3) j = 0 print "for loop and" for I in aList: print I j + = icounter = float (len (aList) print "average value :", j/counterprint "while loop implements the output list and" j = 0i = 0 while I <len (aList ): j + = aList [I] print aList [I] I + = 1 print jprint "average value:", j/counter

2-10 The raw_input () function is used for user input with loops and condition judgments to prompt the user to enter a value between 1 and 100. Number. If the number entered by the user meets this condition, it is displayed as successful and exits. Otherwise, an error message is displayed and then prompted again. Enter a value until the condition is met.
#!/usr/bin/env python#-*- coding:utf-8 -*-while True:        i =input("please type the number:\n")        if(0<i<100):                print"success!"                break        else:                pass

  2-11 A program with text menus writes a program with text menus. The menu items are as follows (1) take the sum of the five numbers (2) Take the average of the five numbers .... (X) Exit. The user makes a selection and then executes the corresponding functions. The program ends when the user selects to exit. The utility of this program is that you do not need to restart your script once to switch between functions. (This is also useful for developers to test their own programs)
#! /Usr/bin/env python #-*-coding: UTF-8-*-myList = [] I = 0sum = 0 while I <5: counter = input ("please enter the number: \ n") myList + = [counter] I + = 1 while True: print "(1) take the sum of the five numbers (2) Take the average of the five numbers (3) Exit "choose = input (" please enter your choose: \ n ") if choose = 1: for j in range (len (myList): sum + = myList [j] print sum elif choose = 2: for j in range (len (myList )): sum + = myList [j] print sum/(len (myList) + 1) elif choose = 3: break

2-12

Dir () built-in functions

(A) Start the Python interactive interpreter and press dir () to execute the dir () built-in function. You see

What? 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 dir can execute dir ()

What if built-in functions are not enclosed in parentheses? Try it. What information does the interpreter return to you? You think this information table

What does it mean?

(C) type () built-in functions receive arbitrary Python objects as parameters and return their types. In the interpreter, Type

Type (dir) to see what you get?

(D) In the last part of this exercise, let's take a look at the Python document string. 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 all have corresponding document strings. We hope that you will also write documents in your code

String, which provides timely and convenient help to those who use the code.

A. obtain the attribute list of the current module ['_ builtins _', '_ doc _', '_ name _'] B. dir <built-in function dir> displays the built-in function dirc. see the built-in Function Method <type 'builtin _ function_or_method '> d. 2-13

Use dir () to find more information in the sys module.

(A) Start the Python interactive interpreter, execute the dir () function, and then 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 the sys

All attributes of the module.

(B) display the version number attributes and platform variables of the sys module. Remember to add sys. Before the attribute name, which indicates

This attribute belongs to the sys module. The version variable stores the version of your Python interpreter, platform

This attribute contains information about the computer platform you used when running Python.

(C) Finally, call the sys. exit () function. This is another way to exit the Python interpreter except the hot key.

.

A. B. c. 2-14 Rewrite the arithmetic expression in the print statement in Section 2.4, and try to add the appropriate Parentheses so that it can work properly
print (-2*4)+(3**2)
2-15 element sorting

(A) Ask the user to enter three values and save them to three different variables respectively. If you do not use a list or sorting algorithm, write your own code to sort these three numbers in ascending order. (B) modify (a) The solution to sort it in ascending order.

#! /Usr/bin/env python #-*-coding: UTF-8-*-number1 = input ("Enter the first value! : \ N ") number2 = input (" enter the second value! : \ N ") number3 = input (" enter the third value! : \ N ") if number1> number2: number2, number1 = number1, then number1> number3: number3, number1 = number1, then number2> number3: number3, number2 = number2, number3print number1, number2, number3number1, number2, number3 = number3, number2, number1print number1, number2, number3


How does Python core programming (version 2)

Upstairs nonsense. The second version was revised for the first version because of the upgrade of the python version. This book is suitable for beginners and detailed in the basic part.
It is recommended to install python, which can be learned and tested.
This book is intended for python2.5 and should never contain 3.1

Don't buy it. If you have a computer, just go to the next pdf.

What is the focus of python learning? With the second version of python core programming, how can this book be used better?

Python is the fourth-generation programming language. It has a low entry threshold and a quick start.
At the beginning, to cultivate interest, you can write some small script examples, such as batch file processing and regular expression matching;
Other network applications can also be involved.
To be more in-depth, you need to understand object-oriented.
The core programming book is a collection of online python Forum results, more practical, you can learn from examples.
Then you can look for popular python frameworks and python open-source projects to see the source code.
But in general, python has a bottleneck in efficiency. Generally, it plays the role of script cohesion 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.