How about learning python3 the stupid way? How about learning python3 the stupid way?

Hello everyone, the editor is here to answer the following questions for you. How about the book "Learning Python 3 the Hard Way"? Download the e-book "Learning Python 3 the Hard Way". Let's take a look today!

Hacker Mr. Yu Xian mentioned a good book for getting started with Python "Learn Python the Hard Way (English version link)" in the Know Chuangyu R&D Skills List v3.1. All the codes are from the 2.7 version of Python Programming Basics and Applications Higher Education Society, an introductory python tutorial for high school students .

If you feel tired of looking at the English version, Dangdang has a Chinese version and an electronic version to choose from.

I'm trying to update the code in it to Python 3. At the same time, I attach some of my own beginner's experience, I hope it will be helpful to you.

Someone in the Chinese version translated the title of the book as "Learning Python the Hard Way". In fact, I think it is more interesting to call it "Learn Python, Don't Take the Unusual Path".

You can learn more about the author's meaning in the preface. Be sure to read it several times. Be sure to read it several times. Be sure to read it several times.

[Programming thinking model]

The program is based on input and after certain processing, produces appropriate output.

This processing process actually makes decisions based on input. Think about it, artificial intelligence. That is to use various inputs and various algorithms to make the most appropriate decision and output it.

ex0: Prepare the program environment by yourself. For Windows, go to the official website to install it.

ex1: Learn Print, please note that the print statement must be enclosed in parentheses in python3. Quotes must be in English. Note the difference between "" and ""

print("Hello World")

print("Hello Again")

Further reading:

https://docs.python.org/3/whatsnew/3.0.html

https://wiki.python.org/moin/Python2orPython3

http://www.cnblogs.com/codingmylife/archive/2010/06/06/1752807.html

ex2: Learn to comment

Use the # symbol to add comments to your program. Anything after the comment statement will not be executed. Pay attention to the print statement and don’t forget how to write python3.

ex3: Numbers and simple mathematical formulas

Addition, subtraction, multiplication and division are the same as general procedures. + - */

Remember to use the English input method.

%here refers to the remainder. 5 % 2 remainder is 1

The remainder of 9 % 3 is 0

Another thing to pay attention to is the logical judgment of expressions. print(3+2 < 5-7)

Take a look at the return value, False. Capitalize first letter

ex4: variables and names

Note that the variable name is added in the middle of print. Please continue to pay attention to the way print statements are written in python3. Until you no longer need reminders.

cars = 100

print ("There are", cars, "cars available")

The author of this section also mentioned the difference between integer and floating-point values.

Good programming writing habits. Compare x=100 and x = 100 (note the spaces)

Search pep8 on Baidu to see more information.

ex5: More knowledge about variables and printing

my_name = "Albert Hao"

my_age = 38  # not a lie

print ("Let's talk about %s." % my_name) #Pay attention to the position of the brackets. % here refers to replacing the content inside the double quotes. Pay attention to %s and %d in this sentence and the next sentence.

print ("He's %d years old." % my_age)

The author of this section also introduces the round function, which can be learned in the IDE.

print (round(1.7333,2))

Let’s take a look at the results.

Think about it: What does %r mean? The difference between %d and %s.

ex6: strings and text

binary = "binary"

do_not = "don't"

y = "Those who know %s and those who %s." % (binary, do_not) #When using multiple variables, add parentheses (parenthesis)

print (y)

hilarious = False #Note the first letter is capitalized

joke_evaluation = "Isn't that joke so funny?! %r"

print (joke_evaluation % hilarious)

w = "This is the left side of ......"

e = "a string with a right side."

print (w+e)

# False is not equal to false

# % y must follow the string ahead of it.

ex7: More about printing

print ("Mary had a little lamb.") #Enter print in the ide and you can see that print does not bring back the parameters of the carriage.

print ("." * 10) # Strings can also be multiplied. Change the decimal point to _ and try it. You can output a line of underlines.

end1 = "H"

end2 = "i"

end3 = "!"

print (end1 + end2 + end3)

print (end1,end2,end3,end=" ")

print (end1,end2,end3,end=" \n") #If you use sublime3, observe the position of finished in 0.2s

ex8: more printing

Understand that %r and formatter are passed in as parameters.

formatter = "%r %r %r %r"

print (formatter % (1,2,3,4))

print (formatter % ("one","two","three","four"))

print (formatter % (True, False, True, False))

print (formatter % (formatter,formatter,formatter,formatter))

print (formatter % (

'I had this thing.',

"That you coud type up right.",

"But it didn't sing.",

"So I said goodnight."))

ex9: print, print, print

This section mainly talks about the usage of \n, which is the carriage return and line feed character.

Three quotation marks means that line breaks are allowed within the paragraph. """

days = "Mon Tue Wed Thu Fri Sat Sun"

months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"

print ("Here are the days:",days)

print ("Here are the months:",months)

print ("""

There's something going on here.

With the three double-quotes

We'll be able to type as much as we like.

Even 4 lines if we want, or 5, or 6.

""")

ex10:What is that

This section mainly talks about special characters like \n.

The escape character \, if you want to output \, then you must write it as \\ in the program.

Similar special characters are:

\ttab key

\" output quotes

tabby_cat = "\tI'm tabbed in."

persian_cat = "I'm split\non a line."

backslash_cat = "I'm \\ a \\ cat."

fat_cat = '''

I'll do a list:

\t* Cat food

\t* Fishies

\t* Catnip\n\t* Grass

'''

print ("%s" % tabby_cat)

print (persian_cat)

print (backslash_cat)

print (fat_cat)

Try the following loop code:

while True:

for i in ["/","-","|","\\","|"]:

print("%s" % i,end="") #The original text is %s\r, I replaced \r and added end=""

Note that there must be a colon at the end of the line where while and for are located.

At the same time, the next line must have four spaces as indent, which is indent in English.

Note that the loop here does not execute the end statement, so it can be ended manually. ctrl+z

Newbies can try this version:

count = 0 #Counter

while count <500: #If it does not exceed 500, execute the following command

for i in ["/","-","|","\\","|"]: #Inside the square brackets is the list object. The meaning of this line is that i takes each element of the following square brackets in turn. You can try using other symbols

count= count +1

print("%s" % i,end="")

ex11: Let the computer ask people questions

In this chapter, input begins. This statement is the statement that the computer accepts input in the form of a command line.

This statement is also a difference between Python 2 and 3. There is no raw_input in Python3.

print ("How old are you? ")

age = input()

print ("How tall are you? ")

height = input()

print("How much do you weigh? ")

weight = input()

print("So, you're %r old, %r tall and %r heavy," % (

age,height,weight))

The original article uses a comma at the end of the print statement so that there is no line break. In Python3, you can refer to the writing method of print in the loop statement in ex10, and you can also test it in the IDLE integrated environment.

It will remind you when you type print (. You can also enter help(print) on the command line

ex12: Using a computer to ask people questions

The difference from the previous section is that this section directly prompts the user for input and stores the input results in variables.

age = input("How old are you? ")

height = input("How tall are you? ")

weight = input("How much do you weigh? ")

print ("So, you're %r old, %r tall and %r heavy." % (

age, height, weight))

#Note that the spaces for line breaks cannot be omitted.

You can enter python -m pydoc input at the command line to view the help file for the input command.

ex13: parameters, receiving parameters, variables

This section uses the import command to import the argv module. Mainly enter parameters on the command line. You need to use commands like python ex13.py first second third in the command line (cmd in Windows) to see the effect of the program.

from sys import argv

, first, second, third = argv

print ("The is called:", )

print ("Your first variable is:", first)

print ("Your second variable is:", second)

print ("Your third variable is:", third)

ex14: Use the prompt to enter and pass parameters

This section combines the content of the previous two sections. Remember to pass the user_name parameter using the command line.

from sys import argv

, user_name = argv

prompt = '> '

print ("Hi %s, I'm the %s ." % (user_name, ))

print ("I'd like to ask you a few questions.")

print ("Do you like me %s?" % user_name)

likes = input(prompt)

print ("Where do you live %s?" % user_name)

lives = input(prompt)

print ("What kind of computer do you have?")

computer = input(prompt)

print ("""

Alright, so you said %r about liking me.

You live in %r. Not sure where that is.

And you have a %r computer. Nice.

""" % (likes, lives, computer))

Remember the role of three quotation marks? Three quotation marks allow line breaks within the paragraph.

ex15: read file

This section practices reading text files. You need to prepare an ex15_sample.txt in advance

The content used by the author is:

This is stuff I typed into a file.

It is really cool stuff.

Lots and lots of fun to have in here.

Contents of ex15.py

from sys import argv

, filename = argv

txt = open(filename)

print ("Here's your file %r:" % filename)

print (txt.read())

txt.close()

print ("Type the filename again:")

file_again = input("> ")

txt_again = open(file_again)

print (txt_again.read())

In this section you can also practice the following abilities:

Describe the function of this line in English above each line; you can ask others, or you can search online, such as using python open to retrieve content related to the open command.

ex16: read and write files

This lesson mainly learns about reading and writing file operations. If you don't understand a line of code, you can add comments yourself.

Note that in this lesson you still need to pass parameters to the program through the command line. As an exercise in this lesson, you can try compressing the code in target.write into one line.

from sys import argv

, filename = argv

print ("We're going to erase %r." % filename)

print ("If you don't want that, hit CTRL-C (^C).")

print ("If you do want that, hit RETURN.")

input("?")

print ("Opening the file...")

target = open(filename, 'w')

print ("Truncating the file. Goodbye!")

target.truncate()

print ("Now I'm going to ask you for three lines.")

line1 = input("line 1: ")

line2 = input("line 2: ")

line3 = input("line 3: ")

print ("I'm going to write these to the file.")

target.write(line1)

target.write("\n")

target.write(line2)

target.write("\n")

target.write(line3)

target.write("\n")

print ("And finally, we close it.")

target.close()

ex17: More file operations

This section introduces a new module: exists. Cat test.txt in the book, in Windows you can enter type test.txt in the cmd command box.

You can use python -m pydoc import to learn more about the usage of import.

Tips:

1. If the code is very long, you can debug the code in sections.

2. You can use the print variable to output the intermediate results in segments to achieve the effect of debugging the code.

3. Think about it, why do you need to use the close method to close the document? If there are 100,000 people and everyone does not close the document, what will be the consequences? When programming, develop good habits from the beginning.

4. How to use the len() function?

from sys import argv

from os.path import exists

, from_file, to_file = argv

print ("Copying from %s to %s" % (from_file, to_file))

# we could do these two on one line too, how?

in_file = open(from_file)

indata = in_file.read()

print ("The input file is %d bytes long" % len(indata))

print ("Does the output file exist? %r" % exists(to_file))

print ("Ready, hit RETURN to continue, CTRL-C to abort.")

input()

out_file = open(to_file, 'w')

out_file.write(indata)

print ("Alright, all done.")

out_file.close()

in_file.close()

ex18: name, variable, code, function

# this one is like your s with argv

def print_two(*args):

arg1, arg2 = args #Note the 4 spaces, sometimes the spaces will be lost when copying

print ("arg1: %r, arg2: %r" % (arg1, arg2))

# ok, that *args is actually pointless, we can just do this

def print_two_again(arg1, arg2):

print ("arg1: %r, arg2: %r" % (arg1, arg2))

# this just takes one argument

def print_one(arg1):

print ("arg1: %r" % arg1)

# this one takes no arguments

def print_none():

print ("I got nothin'.")

print_two("Zed","Shaw")

print_two_again("Zed","Shaw")

print_one("First!")

print_none()

Functions do three things: Functions do three things, name the code, receive parameters, and construct your own code.

1. They name pieces of code the way variables name strings and numbers.

2. They take arguments the way your s take argv.

3. Using #1 and #2 they let you make your own "mini s" or "tiny commands".

Write out a function checklist for later exercises.

Write these on an index card and keep it by you while you complete the rest of these exercises or until you feel you do not need it:

1. Did you start your function definition with def?

2. Does your function name have only characters and _ (underscore) characters?

3. Did you put an open parenthesis ( right after the function name?

4. Did you put your arguments after the parenthesis ( separated by commas?

5. Did you make each argument unique (meaning no duplicated names).

6. Did you put a close parenthesis and a colon ): after the arguments?

7. Did you indent all lines of code you want in the function 4 spaces? No more, no less.

8. Did you "end" your function by going back to writing with no indent (dedenting we call it)?

And when you run ("use" or "call") a function, check these things:

1. Did you call/use/run this function by typing its name?

2. Did you put ( character after the name to run it?

3. Did you put the values you want into the parenthesis separated by commas?

4. Did you end the function call with a ) character?

Use these two checklists on the remaining lessons until you do not need them anymore.

ex19 functions and variables

This section mainly tests various methods of passing parameters to functions, including using numbers directly, using variables, using mathematical formulas, or using variables and mathematical formulas.

def cheese_and_crackers(cheese_count, boxes_of_crackers):

print ("You have %d cheeses!" % cheese_count)

print ("You have %d boxes of crackers!" % boxes_of_crackers)

print ("Man that's enough for a party!")

print ("Get a blanket.\n")

print ("We can just give the function numbers directly:")

cheese_and_crackers(20, 30)

print ("OR, we can use variables from our :")

amount_of_cheese = 10

amount_of_crackers = 50

cheese_and_crackers(amount_of_cheese, amount_of_crackers)

print ("We can even do math inside too:")

cheese_and_crackers(10 + 20, 5 + 6)

print ("And we can combine the two, variables and math:")

cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)

Try writing your own function and running it 10 different ways.

You can follow a program line by line by adding comments, or you can learn the code by reading it out loud. You can also learn by drawing pictures.

Is there a limit to the number of parameters a function can have?

Can a function call a function?

ex20: functions and files

This section introduces how to operate files through functions, mainly reading a file. You need to prepare a text file, such as ex20.txt, and write three lines of text. The execution is the same as before. You need to enter python ex20.py ex20.txt in the command line.

In the code below, if there are no spaces after copying, you have to add them manually. (For example, the fourth line below has 4 spaces in front of it)

from sys import argv

, input_file = argv

def print_all(f):

print (f.read())

def rewind(f):

f.seek(0)

def print_a_line(line_count, f):

print (line_count, f.readline())

current_file = open(input_file)

print ("First let's print the whole file:\n")

print_all(current_file)

print ("Now let's rewind, kind of like a tape.")

rewind(current_file) #Move the file pointer back to the file header

print ("Let's print three lines:")

current_line = 1

print_a_line(current_line, current_file)

current_line = current_line + 1

print_a_line(current_line, current_file)

current_line = current_line + 1

print_a_line(current_line, current_file)

Other knowledge: x = x + y is the same as x += y.

ex21: Functions that can return values

In this section, we learn about functions that can return values. Mainly use return to return.

def add(a, b):

print ("ADDING %d + %d" % (a, b))

return a + b

def subtract(a, b):

print ("SUBTRACTING %d - %d" % (a, b))

return a - b

def multiply(a, b):

print ("MULTIPLYING %d * %d" % (a, b))

return a * b

def divide(a, b):

print ("DIVIDING %d / %d" % (a, b))

return a / b

print ("Let's do some math with just functions!")

age = add(30, 5)

height = subtract(78, 4)

weight = multiply(90, 2)

iq = divide(100, 2)

print ("Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq))

# A puzzle for the extra credit, type it in anyway.

print ("Here is a puzzle.")

#Look at the following line. If it were written in arithmetic, what would it look like?

what = add(age, subtract(height, multiply(weight, divide(iq, 2))))

#What if you want to calculate this? 24+34/100-1023

print ("That becomes: ", what, "Can you do it by hand?")

ex22: What have you learned so far?

There are no coding exercises in today's lesson. You need to review everything you learned previously (strings or tokens). If there are any character strings or symbols that you don’t understand yet, find a piece of paper and write them down.

Learn from a book or the Internet, understand them, and then memorize them.

There is one very important thing to remind you:

The most important thing when doing this exercise is: "There is no failure, only trying."

It is recommended that you do this exercise for no more than 15 minutes at a time. Rest for a while and continue.

ex23: read some code

If the previous training was your ability to write code and debug code, then this section is training your ability to read code.

Mainly the following three aspects of ability:

1. Finding Python source code for things you need.

2. Reading through the code and looking for files. Read through all the code and find the appropriate code in the file.

3. Trying to understand code you find. Trying to understand the code you find.

Here's what you have to do:

Here's what you do:

1. Go to bitbucket.org with your favorite web browser and search for "python". Go to bitbucket.org to find "Python" code

2. Avoid any project with "Python 3" mentioned. That'll only confuse you. Because the original text uses Python2, the author mentioned avoiding Python3 code, but if you use Python3, then look for code written in Python3.

3. Pick a random project and click on it.

4. Click on the Source tab and browse through the list of files and directories until you find a .py file (but not

setup.py, that's useless). Select the source code page and find the .py file. Note that it is not setup.py, that file is useless.

5. Start at the top and read through it, taking notes on what you think it does. 通读一遍代码

6. If any symbols or strange words seem to interest you, write them down to research later.

More sites to view code:

github.com

launchpad.net

koders.com

ex24: More exercises

This section is mainly about exercising your endurance and perseverance. You can also use everything you learned previously to debug this program.

print ("Let's practice everything.")

print ("You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.")

poem = """

\tThe lovely world

with logic so firmly planted

cannot discern \n the needs of love

nor comprehend passion from intuition

and requires an explanation

\n\t\twhere there is none.

"""

print("--------------")

print(poem)

print("--------------")

five = 10 - 2 + 3 - 6

print("This should be five: %s" % five)

def secret_formula(started):

jelly_beans = started * 500

jars = jelly_beans / 1000

crates = jars / 100

return jelly_beans, jars, crates

start_point = 10000

beans, jars, crates = secret_formula(start_point)

print("With a starting point of: %d" % start_point)

print("We'd have %d beans, %d jars, and %d crates." % (beans, jars, crates))

start_point = start_point / 10

print ("We can also do that this way:")

print("We'd have %d beans, %d jars, and %d crates." % secret_formula(start_point))

ex25: more practice

I was halfway through writing it, and found that I could directly insert code into cnblogs. Fortunately, it's not too late.

def break_words(stuff):

"""This function will break up words for us."""

words = stuff.split(' ')

return words

def sort_words(words):

"""Sorts the words."""

return sorted(words)

def print_first_word(words):

"""Prints the first word after popping it off."""

word = words.pop(0)

print (word)

def print_last_word(words):

"""Prints the last word after popping it off."""

word = words.pop(-1)

print (word)

def sort_sentence(sentence):

"""Takes in a full sentence and returns the sorted words."""

words = break_words(sentence)

return sort_words(words)

def print_first_and_last(sentence):

"""Prints the first and last words of the sentence."""

words = break_words(sentence)

print_first_word(words)

print_last_word(words)

def print_first_and_last_sorted(sentence):

"""Sorts the words then prints the first and last one."""

words = sort_sentence(sentence)

print_first_word(words)

Debugging this code needs to be executed from the command line. Import ex25 as a module and then reference the function. Please refer to the website for details.

You can learn how the author analyzes the execution process of this code.

Try help(ex25) and help(ex25.break_words) to see where the output content comes from. Is it the content after the three quotation marks in ex25.

Take a close look at the string manipulation commands in this lesson. You can define the string yourself and then debug it in the command line format. The pop seems to be a pop operation.

ex26: Congratulations, let’s do a test

Good programmers assume that their program may go wrong and then try every possibility to fix it. This lesson asks you to be like a good programmer, fix every error, and make this piece of code better and better until the code can run perfectly.

If you get stuck, stop and rest for a while, then continue.

Good news for you, in this lesson, you can just copy the code. No need to type line by line. You can try to turn it into executable code under Python3.

In this lesson we're going to try to fix a "bad" programmer's code. Bad programmers are unreasonable, arrogant, think their code is perfect, and don't consider others.

Common mistakes include:

Forgetting to enter a colon when defining a function; spelling errors such as poop, returnen, pirnt, misuse of = and ==, mixing of underscores and dashes, and incorrect indentation.

def break_words(stuff):

"""This function will break up words for us."""

words = stuff.split(' ')

return words

def sort_words(words):

"""Sorts the words."""

return sorted(words)

def print_first_word(words):

"""Prints the first word after popping it off."""

word = words.pop(0)

print (word)

def print_last_word(words):

"""Prints the last word after popping it off."""

word = words.pop(-1)

print (word)

def sort_sentence(sentence):

"""Takes in a full sentence and returns the sorted words."""

words = break_words(sentence)

return sort_words(words)

def print_first_and_last(sentence):

"""Prints the first and last words of the sentence."""

words = break_words(sentence)

print_first_word(words)

print_last_word(words)

def print_first_and_last_sorted(sentence):

"""Sorts the words then prints the first and last one."""

words = sort_sentence(sentence)

print_first_word(words)

print_last_word(words)

print ("Let's practice everything.")

print ('You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.')

poem = """

\tThe lovely world

with logic so firmly planted

cannot discern \n the needs of love

nor comprehend passion from intuition

and requires an explantion

\n\t\twhere there is none.

"""

print ("--------------")

print (poem)

print ("--------------")

five = 10 - 2 + 3 - 5

print ("This should be five: %s" % five)

def secret_formula(started):

jelly_beans = started * 500

jars = jelly_beans / 1000

crates = jars / 100

return jelly_beans, jars, crates

start_point = 10000

beans, jars, crates = secret_formula(start_point)

print ("With a starting point of: %d" % start_point)

print ("We'd have %d jeans, %d jars, and %d crates." % (beans, jars, crates))

start_point = start_point / 10

print ("We can also do that this way:")

print ("We'd have %d beans, %d jars, and %d crabapples." % secret_formula(start_point))

sentence = "All god\tthings come to those who weight."

words = break_words(sentence)

sorted_words = sort_words(words)

print_first_word(words)

print_last_word(words)

print_first_word(sorted_words)

print_last_word(sorted_words)

sorted_words = sort_sentence(sentence)

print (sorted_words)

print_first_and_last(sentence)

print_first_and_last_sorted(sentence)

ex27: Remember logical operators

From this lesson on, you will learn computer logic operations. If you are a beginner, it is recommended that you spend a full week learning. It is not recommended to spend more time, because as you continue to learn, you will naturally become more proficient.

All that work memorizing the basics pays off big later.

Do a tiny bit at a time throughout the day and mark down what you need to work on most.

Common logical operators and terms:

and

or

not

!= (not equal)

== (equal)

>= (greater-than-equal)

<= (less-than-equal)

True

False

You can combine the above operators to test yourself.

For example, not False, True or False, not (False or True), 0 != 0 to try to tell its result. Of course, you can also verify it on the command line.

You can make a card and try it every day. Remember, there is no failure here, you just have to keep trying. Practice makes perfect.

ex28: Logical expression exercises

This section gives 20 practice questions. You can try them yourself. Similar to the previous section, you can test them on the Python command line.

The author gives six steps to help you complete the question

Find an equality test (== or !=) and replace it with its truth. = and then replace it with the true value.

Find each and/or inside parentheses and solve those first.

Find each not and invert it. Find each not and invert the value.

Find any remaining and/or and solve it.

When you are done you should have True or False.

Note that the first letter of False and True must be capitalized.

ex29: What If judgment statement

This section begins to explain the IF conditional judgment statement. Pay attention to the colon, pay attention to the indentation, and pay attention to the meaning of == and +=. You can change the initial values ​​of people, cats, and dogs to see how the program execution changes.

people = 20

cats = 30

dogs = 15

if people < cats:

print ("Too many cats! The world is doomed!")

if people > cats:

print ("Not many cats! The world is saved!")

if people < dogs:

print ("Too many dogs! The world is drooled on!")

if people > dogs:

print ("The world is dry!")

dogs += 5

if people >= dogs:

print ("People are greater than or equal to dogs.")

if people <= dogs:

print ("People are less than or equal to dogs!")

if people == dogs:

print ("People are dogs.")

ex30:else and If statements

The author of this section first reviews several questions from the previous section. Can you compare them to see if they are the same as what you think?

people = 30

cars = 40

buses = 15

if cars> people:

print("We should take the cars.")

elif cars

print("We should not take the cars.")

else:

print("We can't decide.")

if buses> cars:

print("That's too many buses.")

elif buses

print("Maybe we could take the buses.")

else:

print("We still can't decide.")

if people > buses:

print("Alright, let's just take the buses.")

else:

print("Fine. Let's stay home then.")

ex31: Make a decision

You can use if nesting in this section. Just continue to use the if branch in IF. Pay attention to proper indentation. You can try to write your own mini-game along similar lines.

print("You enter a dark room with two doors. Do you go through door #1 or door #2?")

door = input("> ")

if door == "1":

print("There's a giant bear here eating a cheese cake. What do you do?")

print("1. Take the cake.")

print("2. Scream at the bear.")

bear = input("> ")

if bear == "1":

print("The bear eats your face off. Good job!")

elif bear == "2":

print("The bear eats your legs off. Good job!")

else:

print("Well, doing %s is probably better. Bear runs away." % bear)

elif door =="2":

print("You stare into the endless abyss at Cthulhu's retina.")

print("1. Blueberries.")

print("2. Yellow jacket clothespins.")

print("3. Understanding revolvers yelling melodies.")

insanity = input("> ")

if insanity == "1" or insanity == "2":

print("Your body survives powered by a mind of jello. Good job!")

else:

print("The insanity rots your eyes into a pool of muck. Good job!")

else:

print("You stumbles around and fall on a knife and die. Good job!")

ex32: lists and loops

In addition to judgment, computers are also good at doing repetitive things. In the following code, please mainly observe how the loop part is written.

Check the knowledge about lists; see what else is there besides elements.append(). In IDLE, you can enter the list name, followed by a decimal point, and then press shift to take a look.

the_count = [1, 2, 3, 4, 5]

fruits = ['apples', 'oranges', 'pears', 'apricots']

change = [1, 'pennies', 2, 'dimes', 3, 'quarters']

# this first kind of for-loop goes through a list

for number in the_count:

print ("This is count %d" % number)

# same as above

for fruit in fruits:

print ("A fruit of type: %s" % fruit)

# also we can go through mixed lists too

# notice we have to use %r since we don't know what's in it

for i in change:

print ("I got %r" % i)

# we can also build lists, first start with an empty one

elements = []

# then use the range function to do 0 to 5 counts

for i in range(0, 6):

print ("Adding %d to the list." % i)

# append is a function that lists understand

elements.append(i)

# now we can print them out too

for i in elements:

print ("Element was: %d" % i)

ex33: while loop

Think about it, why do we need a While loop?

Things to note when using While Loops:

To avoid these problems, there's some rules to follow: In order to avoid the while loop executing forever, please follow the following rules:

1. Make sure that you use while-loops sparingly. Usually a for-loop is better. Try to use while loops sparingly, usually a for loop is better.

2. Review your while statements and make sure that the thing you are testing will become False at some point.

3. When in doubt, print out your test variable at the top and bottom of the while-loop to see what it's doing. How the code is executed.

i = 0

numbers = []

while i < 6:

print ("At the top i is %d" % i)

numbers.append(i)

i = i + 1

print ("Numbers now: ", numbers)

print ("At the bottom i is %d" % i)

print ("The numbers: ")

for num in numbers:

print

Study Drills Answer: Change code into functions

def make_list(ran,step):

i = 1

numbers = []

ran1=range(1, ran)

for i in ran1:

print("At the top i is %d" % i)

numbers.append(i)

print("Numbers now:", numbers)

print("At the bottom i is %d" % i)

return numbers

numbers=make_list(6,1)# first argv is range, second argv is step.

print("The numbers:")

for num in numbers:

print(number)

Use a for loop to achieve the same functionality:

i = 0

numbers = []

for i in range(0,6):

print ("At the top i is %d" % i)

numbers.append(i)

i = i + 1

print ("Numbers now: ", numbers)

print ("At the bottom i is %d" % i)

print ("The numbers: ")

for num in numbers:

print

ex34: How to use list elements

"ordinal" numbers The first and second ordinal words

"cardinal" number cardinal number one or two

So, how does this help you work with lists? Simple, every time you say to yourself, "I want the 3rd animal," you translate this "ordinal" number to a "cardinal" number by subtracting 1. The "3rd" animal is at index 2 and is the penguin. You have to do this because you have spent your whole life using ordinal numbers, and now you have to think in cardinal.

Just subtract 1 and you will be good.

Remember:

ordinal == ordered, 1st;

cardinal == cards at random, 0.

Small exercise:

animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus']

"The animal at 0 is the 1st animal and is a bear."

"The animal at 2 is the 3rd animal and is a peacock."

ex35: branches and functions

In this section, a game is written. Please read the code and draw the map of the game. Try debugging your code and document your mistakes, including typos.

If there is code you don't understand, use what you learned earlier and add comments in front of the code.

from sys import exit

def gold_room():

print ("This room is full of gold. How much do you take?")

next = input("> ")

if "0" in next or "1" in next:

how_much = int(next)

else:

dead("Man, learn to type a number.")

if how_much < 50:

print ("Nice, you're not greedy, you win!")

exit(0)

else:

dead("You greedy bastard!")

def bear_room():

print ("There is a bear here.")

print ("The bear has a bunch of honey.")

print ("The fat bear is in front of another door.")

print ("How are you going to move the bear?")

bear_moved = False

while True:

next = input("> ")

if next == "take honey":

dead("The bear looks at you then slaps your face off.")

elif next == "taunt bear" and not bear_moved:

print("The bear has moved from the door. You can go through it now.")

bear_moved = True

elif next == "taunt bear" and bear_moved:

dead("The bear gets pissed off and chews your leg off.")

elif next == "open door" and bear_moved:

gold_room()

else:

print ("I got no idea what that means.")

def cthulhu_room():

print ("Here you see the great evil Cthulhu.")

print ("He, it, whatever stares at you and you go insane.")

print ("Do you flee for your life or eat your head?")

next = input("> ")

if "flee" in next:

start()

elif "head" in next:

dead("Well that was tasty!")

else:

cthulhu_room()

def dead(why):

print (why, "Good job!")

exit(0)

def start():

print ("You are in a dark room.")

print ("There is a door to your right and left.")

print ("Which one do you take?")

next = input("> ")

if next == "left":

bear_room()

elif next == "right":

cthulhu_room()

else:

dead("You stumble around the room until you starve.")

start()

ex36: Design and Debugging

This section mentions the rules for designing and debugging IF and For loops.

Rules For If-Statements Rules for IF statements

1. Every if-statement must have an else. Every If statement must have an else statement.

2. If this else should never be run because it doesn't make sense, then you must use a die function in the else that prints out an error message and dies, just like we did in the last exercise. This will find many errors.

If the else statement is never executed because it makes no sense, you need to use the die function to print an error message, like the code in the previous exercise.

3. Never nest if-statements more than 2 deep and always try to do them 1 deep. This means if you put an if in

an if then you should be looking to move that second if into another function.

Do not nest more than two levels of ifs. That is to say, if you nest an if inside an if, it is best to move the second if to another function.

4. Treat if-statements like paragraphs, where each if,elif,else grouping is like a set of sentences. Put blank lines before and after.

Write each if statement as a paragraph, and if, elif, and else as one sentence. Add blank lines before and after each If statement paragraph.

5. Your boolean tests should be simple. If they are complex, move their calculations to variables earlier in your function and use a good name for the variable.

Your IF statement's test condition should be simple. If they are complex, define them ahead of time as variables and give them meaningful variable names.

You can combine the above rules with the examples in the previous section to deepen your understanding.

Rules For Loops Rules for loop statements

1. Use a while-loop only to loop forever, and that means probably never. This only applies to Python, other languages ​​are different. Use the while statement only when you want to loop forever. This also means almost "never" use. Of course this is only for Python, other languages ​​may be different.

2. Use a for-loop for all other kinds of looping, especially if there is a fixed or limited number of things to loop over. In other situations, use a for loop statement. Especially when there are only a fixed or limited number of variables.

Tips For Debugging Tips for debugging code

1. Do not use a "debugger". A debugger is like doing a full-body scan on a sick person. You do not get any specific useful information, and you find a whole lot of information that doesn't help and is just confusing.

Don't use a debugger. The debugger is like a full physical exam on a patient. You won't get concrete, helpful advice; you'll find a lot of advice that won't be very helpful but will confuse you.

2. The best way to debug a program is to use print to print out the values of variables at points in the program to see where they go wrong.

The best way to debug a program is to use print statements (print statements) at appropriate statement points to print out the values ​​of variables to see if they are errors.

3. Make sure parts of your programs work as you work on them. Do not write massive files of code before you try to run them. Code a little, run a little, fix a little.

Debug your code in sections to make sure they are correct. Don't write a lot of code at once. Try writing a paragraph, running a paragraph, correcting a paragraph.

ex37: Programming Notation Review

This section lists the content that the author considers important in several categories: keywords, data types, escape characters, and character formatters.

Then find some code to learn. Please follow the steps below to learn:

1. Print the part of the code you want to learn, one part at a time.

2. Follow the steps below to add annotations to learn:

1. Functions and what they do. Functions and what they do.

2. Where each variable is first given a value. The position where each variable is first assigned a value.

3. Any variables with the same names in different parts of the program. These may be trouble later. Any variables with the same names in different locations, these may cause trouble.

4. Any if-statements without else clauses. Are they right? Any IF statement without else clause. Are they right?

5. Any while-loops that might not end. Any while-loops that might not end.

6. Finally, any parts of code that you can't understand for whatever reason.

3. Use comments to explain the code to yourself. Explain functions: what they do, what variables they involve.

4. For some difficult codes, you can track variables line by line and function by function. You can print another copy of the code and write the values ​​of the tracking variables in the margins of the page.

practise:

1. Study the flow chart and try to draw one yourself.

2. If you find an error in the code you are studying, try to fix it and tell the author the changes you made.

3. If you don’t have paper, you can also use the comment # on your computer to complete it.

ex38: Learn to use "list"

The author of this lesson focuses on the operation of lists. split and pop methods. At the same time, an example is used to initially introduce classes. Of course, we will study it in depth in the following chapters.

In order to illustrate the execution process of mystuff.append('hello'), a small example of a class is used:

class Thing(object):

def test(hi):

print ("hi")

a = Thing()

a.test()

The following code contains examples of list operations:

ten_things = "Apples Oranges Crows Telephone Light Sugar"

print ("Wait there's not 10 things in that list, let's fix that.")

stuff = ten_things.split(" ")

more_stuff = ["Day","Night","Song","Frisbee","Corn","Banana","Girl","Boy"]

while len(stuff) != 10:

next_one = more_stuff.pop()

print( "Adding: ", next_one)

stuff.append(next_one)

print("There's %d items now." % len(stuff))

pass

print ("There we go:", stuff)

print ("Let's do some things with stuff.")

print (stuff[1])

print (stuff[-1])

print (stuff.pop())

print (" ".join(stuff))

print ("#".join(stuff[3:5]))

Pay attention to the element reference operations of the list, the pop and join operations of the list.

ex39: dictionary, cute dictionary (dictionary is a new data structure of Python)

You can only get elements of a list using numbers. A dictionary allows you to reference elements of a type with any value other than numbers. It's like a dictionary. Once you know the pinyin, you can look it up.

You can run the following code in IDLE:

>>> stuff = {'name': 'Zed', 'age': 36, 'height': 6*12+2}

>>> print (stuff['name'])

Zed

>>> print (stuff['age'])

36

>>> print (stuff['height'])

74

>>> stuff['city'] = "San Francisco"

>>> print (stuff['city'])

San Francisco

>>>

# create a mapping of state to abbreviation

states = {

'Oregon': 'OR',

'Florida': 'FL',

'California': 'CA',

'New York': 'NY',

'Michigan': 'MI'

}

# create a basic set of states and some cities in them

cities = {

'CA': 'San Francisco',

'MI': 'Detroit',

'FL': 'Jacksonville'

}

# add some more cities

cities['NY'] = 'New York'

cities['OR'] = 'Portland'

# print out some cities

print ('-' * 10)

print ("NY State has: ", cities['NY'])

print ("OR State has: ", cities['OR'])

# print some states

print ('-' * 10)

print ("Michigan's abbreviation is: ", states['Michigan'])

print ("Florida's abbreviation is: ", states['Florida'])

# do it by using the state then cities dict

print ('-' * 10)

print ("Michigan has: ", cities[states['Michigan']])

print ("Florida has: ", cities[states['Florida']])

# print every state abbreviation

print ('-' * 10)

for state, abbrev in states.items():

print ("%s is abbreviated %s" % (state, abbrev))

# print every city in state

print ('-' * 10)

for abbrev, city in cities.items():

print ("%s has the city %s" % (abbrev, city))

# now do both at the same time

print ('-' * 10)

for state, abbrev in states.items():

print ("%s state is abbreviated %s and has city %s" % (

state, abbrev, cities[abbrev]))

print ('-' * 10)

# safely get a abbreviation by state that might not be there

state = states.get('Texas', None)

if not state:

print ("Sorry, no Texas.")

# get a city with a default value

city = cities.get('TX', 'Does Not Exist')

print ("The city for the state 'TX' is: %s" % city)

Thought questions:

1. What is the difference between list and dictionary?

A list is for an ordered list of items. A dictionary (or dict) is for matching some items (called "keys") to other items (called "values").

You can use help(list), help(dict) to query help.

2. Give examples of scenarios where dictionary can be used? What about list?

Any time you have to take one value, and "look up" another value. In fact you could call dictionaries "look up tables".

A list is for any sequence of things that need to go in order, and you only need to look them up by a numeric index.

3. What should I do if I need a dictionary but also want to sort it? (collections.OrderedDict)

ex40: modules, classes, and objects

This section uses the concepts of dictionaries and modules that you are familiar with to introduce the basic concepts of classes.

A module is a piece of code, stored separately in *.py. It is similar to a dictionary.

In the case of the dictionary, the key is a string and the syntax is [key]. In the case of the module, the key is an identifier, and the syntax is .key. Other than that they are nearly the same thing.

Classes are like modules.

A way to think about modules is they are a specialized dictionary that can store Python code so you can get to it with the '.' operator. Python also has another construct that serves a similar purpose called a class. A class is a way to take a grouping of functions and data and place them inside a container so you can access them with the '.' (dot) operator.

Objects are like small imports. Also called instantiation.

ex40a.py

class MyStuff(object):

def __init__(self):

self.tangerine = "And now a thousand years between"

def apple(self):

print ("I AM CLASSY APPLES!")

thing = MyStuff()

thing.apple()

print (thing.tangerine)

ex40b.py

class Song(object):

def __init__(self, lyrics):

self.lyrics = lyrics

def sing_me_a_song(self):

for line in self.lyrics:

print (line)

happy_bday = Song(["Happy birthday to you",

"I don't want to get sued",

"So I'll stop right there"])

bulls_on_parade = Song(["They rally around the family",

"With pockets full of shells"])

happy_bday.sing_me_a_song()

bulls_on_parade.sing_me_a_song()

Thought questions:

1. Why do we need to pass in (self) when defining __init__ and other functions in a class?

Because self is not passed in, the variables are not clear enough, and it is not known whether it refers to the main function or the variables in the class.

EX41: Learning object-oriented languages

This section divides learning categories into three aspects: word training, phrase training, and training combining the two.

You can write all of this down on cards and memorize them when you have time.

1. Word:

class : Tell Python to make a new kind of thing.

object : Two meanings: the most basic kind of thing, and any instance of some thing.

instance : What you get when you tell Python to create a class.

def : How you define a function inside a class.

self : Inside the functions in a class, self is a variable for the instance/object being accessed.

inheritance : The concept that one class can inherit traits from another class, much like you and your parents.

composition : The concept that a class can be composed of other classes as parts, much like how a car has wheels.

attribute : A property classes have that are from composition and are usually variables.

is-a : A phrase to say that something inherits from another, as in a Salmon is-a Fish.

has-a : A phrase to say that something is composed of other things or has a trait, as in a Salmon has-a mouth.

2. Phrases:

class X(Y)

"Make a class named X that is-a Y."

class X(object): def __init__(self, J)

"class X has-a __init__ that takes self and J parameters."

class X(object): def M(self, J)

"class X has-a function named M that takes self and J parameters."

foo = X()

"Set foo to an instance of class X."

foo.M(J)

"From foo get the M function, and call it with parameters self, J."

foo.K = Q

"From foo get the K attribute and set it to Q."

Of course, the advantage of having a computer is that you can let the program help you remember.

import random

import urllib.request

import sys

WORD_URL = "http://learncodethehardway.org/words.txt"

WORDS = []

PHRASES = {

"class ###(###):":

"Make a class named ### that is-a ###.",

"class ###(object):\n\tdef __init__(self,***)":

"classe ### has-a __init__ that takes self and *** parameters.",

"class ###(object):\n\tdef __init__(self,@@@)":

"classe ### has-a function named *** that takes self and @@@ parameters.",

"*** = ###()":

"Set *** to an instance of class ###.",

"***py.***(@@@)":

"from *** get the *** function, and call it with parameters self, @@@.",

"***.*** = '***'":

"from *** get the *** attribute and set it to '***'."

}

#do they want to drill phrases first

PHRASES_FIRST = False

if len(sys.argv) == 2 and sys.argv[1] == "english":

PHRASES_FIRST = True

#load up the words from the websites

for word in urllib.request.urlopen(WORD_URL).readlines():

WORDS.append(word.strip().decode("utf-8")) #Here is a byte to str conversion

print(WORDS)

def convert(snippet, phrase):

class_names = [w.capitalize() for w in

random.sample(WORDS, snippet.count("###"))]

other_names = random.sample(WORDS, snippet.count("***"))

results = []

param_names = []

for i in range(0, snippet.count("@@@")):

param_count = random.randint(1,3)

param_names.append(", ".join(random.sample(WORDS, param_count)))

for sentence in snippet, phrase:

result = sentence[:]

#fake class names

for word in class_names:

result = result.replace("###", word, 1)

#fake other names

for word in other_names:

result = result.replace("***", word, 1)

#fake parameter lists

for word in param_names:

result = result.replace("@@@", word, 1)

results.append(result)

return results

#keep going until they hit CTRL-D

try:

while True:

snippets = PHRASES.keys()

random.shuffle(list(snippets))#A displayed list conversion is done here

for snippet in snippets:

phrase = PHRASES[snippet]

question, answer = convert(snippet, phrase)

if PHRASES_FIRST:

question, answer = answer, question

print (question)

input("> ")

print ("ANSWER: %s\n\n" % answer)

except EOFError:

print("\nBye")

ex42:Is-A,Has-A,object,and class

After checking, the author already has a Python 3 version of the book. But so far I have not seen the Chinese translation. 20170701

Websites to learn more about Python:

A byte of python, textbooks from many schools, including Stanford (https://mygsb.stanford.edu/sites/default/files/A Byte of Python.pdf)

Official website teaching materials

4. GUI programming

Lovely Python: TK Programming in Python

5. Python Chinese Manual

6. Experimental Building Python

Guess you like

Origin blog.csdn.net/chatgpt002/article/details/132977560