A summary of the exercises in "interesting learning Python Programming"

Source: Internet
Author: User
Tags windows x86 python script

Last week, I bought a book called "Fun to learn Python programming" (English name: Python for kids), yesterday after reading the book after the title has been done. As the 1th and 2 chapters do not have exercises, the 13th chapter and then are descriptive examples of the chapters, so this summary of the article contains only the 第3-12 chapter of the exercise answer.

1. My Debugging Environment

I debugged Python on my Win7 and Redhat respectively:

1) Win7 IDE can be downloaded from the official website of Python:

https://www.python.org/downloads/windows/

Click on the link Python 3.4.2→download Windows x86 MSI installer, which can be downloaded to a file Python-3.4.2.msi

2) on Redhat, you can install Python directly using the Yum command, where you need to use turtle, and you need to install it with Yum Tkinter

Also, on Redhat, the Turtle popup window disappears immediately after it runs, so I use the time.sleep () function to delay some time to observe the results.

2. About the Python script run

1) Win7 After downloading the idle (Python 3.4 GUI-32 bit), open an editor via file→new, enter the code and press F5 to run

2) Redhat directly into the command "Python xxx.py" can run the script xxx.py

3. Chapter III: Strings, lists, tuples, and dictionaries

1) Use the list of games to list your hobbies, list your favorite foods by listing foods, connect the two lists together and name the results favorites and print them.

Games = [' GAME0 ', ' game1 ', ' game2 ', ' game3 ']foods = [' food0 ', ' food1 ', ' food2 ', ' food3 ']favorites = games + foodsprint (fav Orites)

2) There are three buildings, each with 25 ninjas, two tunnels, each with 40 samurai, and ask how many people can be put into battle?

Building = 3ninja_per_building = 25tunnel = 2samurai_per_tunnel = 40total = Building * ninja_per_building + tunnel * Samur Ai_per_tunnelprint (total)

3) Create two variables: A last name and a name, create a string, use these two variables with placeholders to print your name's information

Namemap = {' Tsybius ': ' A ', ' Galatea ': ' B ', ' Gaius ': ' C ', ' Flavia ': ' D '}text = ' Name %s%s "Print (text% (' Tsybius ', namemap[' Tsybius ')) print (text% (' Galatea ', namemap[' Galatea ')) print (text% (' Gaius '), namemap[' Gaius ')) print (text% (' Flavia ', namemap[' Flavia '))

4. Chapter Fourth: Drawing with turtles

1) Create a canvas with the pen function of turtle and draw a rectangle

Import Timeimport turtlewidth = 40height = 30t = Turtle. Pen () t.forward (width) t.left () t.forward (height) t.left (All) t.forward (width) t.left (All) t.forward (height) Time.sleep (5)

2) Create a canvas with the pen function of turtle and draw a triangle

Import mathimport Timeimport Turtlet = Turtle. Pen () #画一个等边三角形t. Forward (T.left) T.forward (+) T.left (+) T.forward (+) T.left (+) #把坐标换到另一个位置t. Up () T.right (T.forward) T.left (+) T.down () #画一个内角分别为30 °, 30°, 120° triangular T.forward (MATH.SQRT (3)) T.left (80 ) T.left (T.forward) t.left (+) Time.sleep (5)

3) Draw a square with no corners

Import Timeimport Turtlet = Turtle. Pen () #下t. Forward (+) T.up () T.forward (50) T.left () T.forward () T.down () #右t. Forward (+) t.up () T.forward T.left (T.forward) T.down () #上t. Forward (+) T.up () T.forward (+) T.left (+) T.forward () T.down () #左t. Forward ( Time.sleep (5)

5. Use if and else to ask questions

1) Enter the code to verify the answer

Original code

Money = 2000if Money > 1000:print ("I ' m rich!!") Else:print ("I ' m not Rich") print ("But I might be later ...")

This code is wrong, and the beginning of line fifth and line sixth should be in the same column as follows:

Money = 2000if Money > 1000:print ("I ' m rich!!") Else:print ("I ' m not Rich") print ("But I might be later ...")

2) Use the IF statement to determine whether a number is less than 100 or greater than 500, if the condition is true print "not too little is too much"

#twinkies = 50#twinkies = 300twinkies = 550if Twinkies < or Twinkies > 500:print ("Too less or Too more")

3) Use an If statement to check if the variable money is between 100 and 500, or between 1000 and 5000

#money = 250#money = 2500money = 9999if (Money >=, <=) or (Money >=, Money <= 5000): Print ("money in [+] or in [] [+]") else:print ("Neither in [[+]] nor in [1000, 5000]")

4) Create a set of if statements, the variable ninja is less than 10 o'clock print "I can play", less than 30 o'clock print "a bit difficult", less than 50 o'clock print "too much"

Ninjas = 5#ninjas = 10#ninjas = 30if Ninjas < 10:print ("I can beat them") Elif Ninjas < 30:print ("It s a Litt Le difficult but I can deal with it ") Elif Ninjas < 50:print (" Too more ninjas there! ")

6. Cycle

1) Explain what happens to the following code

For x in range (0): print (' Hello%s '% x) if x < 9:break

Break is triggered by x<9 on the first loop, so you can print only once Hello 0

2) If your age is even, start from 2 to print until you know your age, if your age is odd, starting from 1

Age = 23start = 2if Age% 2! = 0:start = 1for x in range (start, age + 2, 2): Print (x)

3) Create a list of 5 different sandwich making materials, create a loop, print the list sequentially, and write out the sequence number

INGREDIENTS = [' snails ', ' leeches ', ' Gorilla Belly-button lint ', ' caterpillar eyebrows ', ' centipede toes ']fo R x in range (0, 5): Print ("%d%s"% (x + 1, ingredients[x]))

4) on the Moon your weight is 16.5% on the earth, assuming you grow 1 kilograms a year and print your weight status for the next 15 years

Weight = 9999 #体重increment = 1 #体重年增量coefficient = 0.165 #体重转换系数for x in range (1): Print ("%d years late R:%f "% (x, (weight + increment * x) * coefficient))

7. Chapter Seventh: Reusing your code using functions and modules

1) Use the function to calculate your weight in topic 6.4 (the annual increment of the current weight and weight)

def func_moonweight (weight, increment): coefficient = 0.165 #体重转换系数 for x in range (1, +): Print ("%d years LA ter:%f "% (x, (weight + increment * x) * coefficient)) Func_moonweight (30, 0.25)

2) Use the function to calculate your weight in topic 6.4 (Parameters are current weight, annual increment of body weight and number of years of statistics)

def func_moonweight (weight, increment, deadline): coefficient = 0.165 #体重转换系数 for x in range (1, Deadline + 1): Print ("%d years later:%f"% (x, (weight + increment * x) * coefficient)) Func_moonweight (90, 0.25, 5)

3) Use the function to calculate your weight in 6.4, the current weight, the annual increment of weight, and the number of years of statistics are given by the input

Import sysdef func_moonweight (weight, increment, deadline): coefficient = 0.165 #体重转换系数 for x in range (1, Deadline + 1): Print ("%d years later:%f"% (x, (weight + increment * x) * coefficient)) #读取信息并调用函数print ("Please enter your CU Rrent Earth weight ") para1 = Int (sys.stdin.readline ()) Print (" Please enter the amount your weight might increase all year ") Para2 = float (sys.stdin.readline ()) Print ("Please enter the number of years") para3 = Int (Sys.stdin.readline ()) func_ Moonweight (Para1, Para2, PARA3)

8. Chapter VIII: How to use Classes and objects

1) Add a function to the giraffes class to move the giraffe to the left, right, front, and rear four feet and print a full set of steps through the dance function

Class giraffes ():     #函数: Left Foot forward     def funcleftfootforward ( Self):         print (' Left foot forward ')       #函数: Right foot forward     def funcrightfootforward (self):         print (' Right foot forward ')      #函数: Left foot back     def  funcleftfootback (self):         print (' Left foot back ')      #函数: Right foot back     def funcrightfootback (self):         print (' Right foot back ')      #函数: Stationary      def funcstand (self):         print ()       #函数: Dancing     def funcdance (self):         Self.funcleftfootforwarD ()         self.funcleftfootback ()          self.funcrightfootforward ()         self.funcrightfootback ( )         self.funcleftfootback ()          self.funcstand ()         self.funcrightfootback ()          self.funcrightfootforward ()          self.funcleftfootforward () Reginald = giraffes () reginald.funcdance ()

2) draw a fork with the turtle of 4 pen objects

Import Timeimport turtle# Line 1t1 = Turtle. Pen () T1.forward (T1.left) T1.forward (+) t1.right (t1.forward) #线2t2 = Turtle. Pen () T2.forward (t2.right) T2.forward (+) T2.left (t2.forward) #线3t3 = Turtle. Pen () T3.forward (T3.left) T3.forward (+) t3.right (t3.forward) #线4t4 = Turtle. Pen () T4.forward (t4.right) T4.forward (+) T4.left (5) T4.forward (+)

9. Chapter Nineth: Python's built-in functions

1) Run the code to interpret the results

A = ABS (+) + ABS ( -10) print (a) b = ABS ( -10) + -10print (b)

A is the mathematical formula "10+|-10|=10+10", the result is 20

B is the mathematical formula "|-10|+ (-10) =10-10", the result is 0

2) try to use Dir and help to find out how to break the string into words

The Dir function can return information about any value

The Help function can return information about the function described in its arguments

The last code determined by the Dir and the Help function is:

String = ' ' This if is reading very this good and then wayto-a IT message wrong ' for x in String.Split (): Print (x)

3) Copy the file, which is used to read the information before writing to the new file mode

#读取文件内容test_file1 = open ("D:\\input.txt") Text = Test_file1.read () test_file1.close () #将读取到的内容写入到一个新文件test_file2 = Open ("D:\\output.txt", ' W ') test_file2.write (text) test_file2.close ()

10. The tenth chapter, the Common Python module

1) Explain what the following code will print

Import Copyclass car:passcar1 = Car () car1.wheels = 4car2 = Car1car2.wheels = 3print (car1.wheels) #这里打印什么? (3) Car3 = Copy.copy (car1) car3.wheels = 6print (car1.wheels) #这里打印什么? (3)

The first print prints 3 because car1 and CAR2 are the same object, and changing one will change

The second print prints 3 because CAR3 is obtained from car1 by copy, and Car1 is not an object, and modifying CAR3 does not change at the same time car1

2) Serialize and print a message with pickle and save it to a *.dat file, and then read the information from that file to deserialize

Import pickleinfo = {' Name ': ' Tsybius ', ' age ': $, ' hobby ': [' hobby1 ', ' hobby2 ', ' Hobby3 ']} #序列化写入文件outputfile = Open (' D:\\save.dat ', ' WB ') pickle.dump (info, outputfile) outputfile.close () #反序列化读取文件inputfile = open (' D:\\save.dat ') , ' RB ') Info2 = Pickle.load (inputfile) inputfile.closeprint (Info2)

11.11th: Advanced Turtle Mapping

1) Draw the eight-edged shape

Import Timeimport Turtlet = Turtle. Pen () for x in range (1, 9): T.forward (T.left) time.sleep (5)

2) Draw an eight-edged shape with an outline

Import Timeimport Turtlet = Turtle. Pen () #绘制实心八边形 (red) t.color (1, 0, 0) t.begin_fill () for x in range (1, 9): T.forward (+) T.left (GB) T.end_fill () #为八边形描边 (black ) T.color (0, 0, 0) for x in range (1, 9): T.forward (T.left) time.sleep (5)


3) give the number of sizes, size and stars, and draw a star

Import timeimport turtle#x Edge and 180* (x-3) #函数: gives the size and number of vertices to draw the star #size: The core of the star is an equilateral polygon, which is the distance from the vertex of the polygon to its center # Point: Top Def funcdrawstar (size, point):     t = turtle. Pen ()      #调校坐标位置     t.up ()     t.backward (200)     t.right (    t.forward)     t.left (90)     t.down ()      #开始画图     t.color (1, 0, 0 )     t.begin_fill ()     for x in range (1, point  * 2 + 1):         t.forward (size)          if x % 2 == 0:             t.left (        else):             t.right (180 *  (point - 2)  / point - 60)      t.end_fill ()      #funcDrawStar (100, 6) Funcdrawstar (100, 9) time.sleep (5)


12.12th Chapter: Drawing Advanced Graphics with Tkinter

1) draw a triangle on the screen, position random, color random

from tkinter import *import randomcolor = ["green",  "Red",  "Blue",   "Orange",  "yellow",          "pink",  "purple",   "Violet",  "magenta",  "cyan"]TK&NBSP;=&NBSP;TK () Canvas = canvas (tk, width =  400, height = 400) Canvas.pack () #函数: Create a random position, a random color triangle def funcrandomtriangle ():     x1 = random.randrange (    y1 = random.randrange) ( (    x2 = random.randrange)     y2 =  Random.randrange (    x3 = random.randrange)     y3  = random.randrange (    fillcolor = random.randrange)      canvas.create_polygon (x1, y1, x2, y2, x3, y3,         fill = color[fillcolor], outline =  "Black") For x in range (0, 15):     funcrandomtriangle ()

2) Move the triangle, first to the right, then down, then left, then up back to the original position

Import timefrom tkinter Import *tk = TK () canvas = Canvas (tk, width = +, height = in) canvas.pack () #创建一个三角形canvas. Create_ Polygon (1, 5, 0) tk.update () time.sleep (0.05) #向右移动for x in range (0): Canvas.move (+) For x in range (0, $): Canvas.move (1, 0, 5) tk.update () time.sleep (0.05) #向左移动for x in range (0): Canvas.mov E (1, -5, 0) tk.update () time.sleep (0.05) #向上移动for x in range (0): canvas.move (1, 0,-5) Tk.update () time. Sleep (0.05)

3) Moving photos (gif format)

Import timefrom tkinter Import *tk = TK () canvas = Canvas (tk, width = all, height = in) canvas.pack () myimg = Photoimage (fil E = "D:\\temp.gif") canvas.create_image (0, 0, anchor = NW, image = myimg) #向右移动for x in range (0): Canvas.move (1, 5, 0 ) Tk.update () Time.sleep (0.05)

END

A summary of the exercises in "interesting learning Python Programming"

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.