Python Introductory tutorial (ii)

Source: Internet
Author: User
Tags readline string methods


Talk about programming thinking today.


Maybe this is useful for first-time programming people--I don't want to get to the point, I just want to stress that there's nothing going on, I might have mentioned it in other articles. "The programming language is the grammatical sugar", perhaps you do not know what is the grammatical sugar, but knows the person also may not agree with me. I'm not sure you can understand ... Python has a lot of tutorials, but I'm not happy with many of them, so this is my try.


We will implement a "filter 100 in Prime" program. I don't use Python language, but pseudo code--pseudo code doesn't have a fixed notation, but naturally not everything is called pseudo-code. It takes two properties to become pseudo code:

    1. No ambiguity. Maybe others will feel ambiguous, as long as you feel that there is no line.

    2. Executable. This means you have to enter an action instead of "The weather is fine today" and so on.


But not all that can be done is a machine. In general, you can make the machine do:

    • Create a variable. A variable is like an empty box, you can put something in it, but only one. The most common is to load a number, 0,12345,-233333, and so on.

    • Put something in the variable.

    • Log to perform mathematical operations and place the result in a variable

    • Print a string; print a number. ("print" simply means display on the screen, which is the general view)

    • Condition selection. (Say later)

    • Cycle. (Say later)


Most of the things you think are more "mechanical" work, machines can do. Although I don't know how you feel about the machine ...


Now we are trying to implement a program that filters up to 100 primes. You can write exactly as you wish, such as:

If 1 is prime, print 1 if 2 is prime, print 2 if 3 is prime, print 3 if 4 is prime, print 4 if 5 is prime, print 5 if 6 is prime, print 6 If 7 is prime, print 7 If 8 is prime, print 8 If 9 is prime, print 9 If 10 is a prime number, Print 11 If 12 is prime, print 12 If 13 is prime, print 13 If 14 is prime, print 14 if 15 is prime, print 15 If 16 is prime, print 16 if 17 is prime, print 17 If 18 is prime, print 18 if 19 is prime, print 19 if 20 is prime, Print 20 If 21 is prime, print 21 If 22 is prime, print 22 if 23 is prime, print 23 if 24 is prime, print 24 if 25 is prime, print 25 if 26 is prime, print 26 If 27 is prime, print 27 if 28 is prime, print 28 if 29 is prime, Print 29 If 30 is prime, print 30 if 31 is prime, print 31 if 32 is prime, print 32 if 33 is prime, print 33 If 34 is prime, print 34 if 35 is prime, print 35 if 36 is prime, print 36 If 37 is prime, print 37 If 38 is prime, Print 38 If 39 is prime, print 39 if 40 is prime, print 40 if 41 is prime, print 41 if 42 is prime, print 42 If 43 is prime, print 43 if 44 is prime, print 44 if 45 is prime, print 45 if 46 is prime, print 46 If 47 is prime, Print 47 If 48 is prime, print 48 if 49 is prime, print 49 if 50 is prime, print 50 if 51 is prime, print 51 if 52 is prime, print 52 If 53 is prime, print 53 If 54 is prime, print 54 if 55 is prime, print 55 if 56 is prime, Print 56 If 57 is prime, print 57 If 58 is prime, print 58 If 59 is prime, print 59 If 60 is prime, print 60 if 61 is prime, print 61 if 62 is prime, print 62 If 63 is prime, print 63 if 64 is prime, print 64 If 65 is prime, Print 65 If 66 is prime, print 66 if 67 is prime, print 67 if 68 is prime, print 68 if 69 is prime, print 69 If 70 is prime, print 70 if 71 is prime, print 71 If 72 is prime, print 72 if 73 is prime, print 73 if 74 is prime, Print 74 If 75 is prime, print 75 If 76 is prime, print 76 If 77 is prime, print 77 If 78 is prime, print 78 if 79 is prime, print 79 If 80 is prime, print 80 if 81 is prime, print 81 if 82 is prime, print 82 if 83 is prime, Print 83 If 84 is prime, print 84 If 85 is prime, print85 If 86 is prime, print 86 If 87 is prime, print 87 if 88 is prime, print 88 if 89 is prime, print 89 If 90 is prime, print 90 if 91 is prime, print 91 if 92 is prime, print 92 if 93 is prime, print 93 if 94 is prime, Print 94 If 95 is prime, print 95 if 96 is prime, print 96 if 97 is prime, print 97 If 98 is prime, print 98 if 99 is prime, print 99 if 100 is prime, print 100

This "is" pseudo-code, because there is no ambiguity, and can be executed. But the machine cannot execute, because "is prime" we understand that the machine does not understand. But we can split the "is prime" into several separate conditions, so that the machine can understand the simpler conditions. But before we do, should we consider that there are too many of these 100 rows? We can use some tips:

Create a new variable a put 1 in a if the number in a is a prime, the number in print a increases the number of a in a by 1 back to the third row

The code, which would have been 100 lines, now only has 5 lines--that's a big use of the loop, and obviously "going back to the third line" has caused a loop to form. But this code is not correct, because it will loop indefinitely, it will not end, "can continue to print the prime number." So to make some changes:

Create a new variable a put 1 in a if the number in a is a prime, the number in print a increases by 1 if a is greater than 100, and jumps out of the loop back to the third row

Because there is only one loop, "jumping out of the loop" is pseudo-code. Python is a powerful language, and it should be possible to change these pseudo-code into Python language, but there is a bizarre rule in the world (most languages, C is the exception): "Go back to the third line" is forbidden. In order to compensate, it can be written like this:

Create a new variable a put 1 in a and repeat 100 times in parentheses (if the number in a is prime, the number in a print a increases by 1)

Next we deal with "is prime". If a number is greater than 3 and is divided by all values greater than 1 and 1 smaller than itself, then it is a prime number. So the following two sections of code are functionally identical:

1:

If the number in a is a prime, print the number in a

2: (Generally, we use the variable name directly to address the thing, although the name of the box to address the things inside is very strange)

Create a new variable B create a new variable "is it possible that the number is prime?" Put 2 in the B string "it is possible to put in the variable" this number is likely to be prime? Repeat the sentence in the brackets below (if a divided by B has no remainder, then the string "cannot" be put into the variable " Is this number still likely to be prime? "Put B plus 1 if B equals a at this point, then jump out of the loop" if the variable "this number may be prime" is "possible", print a number

Added together, is this: (at the same time, only one layer of circulation, jumping out of the loop is still no ambiguity)

Create a new variable A, put 1 in a and repeat 100 times in parentheses (create a new variable B to create a new variable, "Could it be a prime number?" Put 2 in the B string, "It's possible to put" the variable "the number is likely to be prime?" Repeat the sentence in parentheses (if A is divided by B , then the string "Can not be" put into the variable "this number may be prime?" Put B plus 1 if at this point B equals a, then jump out of the loop) if the variable "this number is also likely to be a prime number" is "possible", print a in the number of a will increase by 1)

Now for the first time we formally use Python code: (#号到行末是注释, not run as a statement, just to make it easier for programmers to read)

a = 1                                                 #    new Variable A,   Put 1 in Afor i in range (:          )                        #    repeat the words in parentheses 100 times                                                        # (    b = 2                                             #     Create a new variable b,  and put 2 in b     this number is also possible prime numbers  =  "possible"                       #     New variable "Could this number be prime?",  and put the string "possible"     while True:                                       #    Repeat the sentences in the brackets below                                                       # (         if a % b == 0: Is this number still likely to be prime?  =  "Impossible"     #    If a divided by B does not have a remainder, then the string "impossible" to put into the variable "this number may also be prime"         b  += 1                                        #    b plus 1        if  a == b:  break                            #    If B equals a at this point, then jump out of the loop                                                       #)      if  This number could be prime?  ==  "Possible":p rint (a)         #     If the variable "this number is still possible prime" is "possible", print the number of a in     a += 1                                             #    increase the number in a 1                                                       #)

"Put the number in the variable"-that is, the "assignment operation", with the symbol is the equal sign. In fact, this is not intuitive, and will be used for a long time to create an illusion. The double equals sign that appears in the code represents a comparison operation, and the equals sign can only be used for assignment.

In this code, for I in range (100) means to create a new variable called I, and make it 0. Python must be assigned at creation time, which is actually equal to the first time it was created. Then the brackets--python without parentheses, but when the brackets need to indent 4, the end of the parenthesis 4 square forward, so that can be aligned-the contents of the parentheses to execute again, I plus 1, so continue.

However, the above code does not work. You will see that the cursor is flashing continuously-because 1 cannot be used to test whether it is a prime number. But starting from 3, there is no problem--more than 1, and a few 1 smaller than itself, the logic is also running. So we changed the first line to A=3.

However the result appeared in 101 ... So we can change ... But these logic errors--not grammatical errors--are something outside the language. We didn't think about it when we wrote the pseudocode, not that we didn't learn the language well.


This little program is primitive, but it's very much about thinking. We can at least see 3 Revelations: (and long-term effectiveness)

    • To replace repetitive things with loops

    • Notice how the loop ends

    • Notice whether the loop can start


And beyond programming thinking, which is the overwhelming majority of traditional books, I've decided to skip it. But learn to ask questions, you will find that you really need to learn so much is enough, give people to fish than to teach people to fishing. Here are a few words to explain.


Function

Please look at the code:

def f (x): Return 2*xa = f (7) print (a)

Functions are functions that simplify mathematical operations. In addition to mathematical manipulations, however, functions can do other things, but are subject to some limitations. If you want to calculate a number twice times over and over again (or twice times +3+2 this number of times + ...) Such a complex function), Def is a good choice. DEF should be an abbreviation for define (Chinese: definition). You can write print in the function, reference variables outside the function, and cannot modify variables outside the function, and so on.

Want to know more, Baidu search "Python3 function", a skill is, can not understand the first pick to see see.


String

In Python, the contents of the "half-width, that is, the English-language" quotation marks are treated as strings. In English there is no front and back quotation marks, in the previous reading, the first will be treated as the front quotation marks, the second match with the previous one, is treated as a post-quote. You can assign a string to a variable. If a string of English is not in quotation marks, it is considered a variable name. Quotation marks do not work in Chinese. The space is a character, the line break is also a character (it may be possible to print ("Hello\nworld"), but the line break can not be hit out at once, people use "\" followed by a letter to indicate these invisible symbols, \ n for the line, \ \ Self, \ " is a double quotation mark (obviously the quotation marks cannot be typed separately). It is worthwhile to sacrifice a symbol to get a bunch of extra symbols. In Python, single and double quotes can be mixed in pairs (matching the same kind), but I am accustomed to using single quotes to handle a single character (a single character is also a string).

Things that can be put into variables-such as "strings"-Can be Baidu "Python3 string Methods" (also such as "Python3 complex methods", but the methods of strings are particularly numerous). "Method" is to add a point followed by a function, is a function of one. Most of the people who say "method" rather than "function" emphasize that this function can use a "." to invoke it. As to what is going on, the next tutorial is again (related to "class")


List

L = [1,2,3,4,5]print (l [0]) print (l [1]) print (l [2]) print (l [3]) print (l [4])

Five print prints out of 12345. A[I] represents the I element in a, but the first one is the "No. 0 element". Like the bottom of some buildings is the "No. 0 Floor"-this habit is not without merit.

If you change the first line to L=1, the next line will go wrong. Because an integer does not have "nth element".

L usually use no space before the parenthesis, here is to see clearly

("Python3 list Method")


Meta-group

t = (1,2,3,4,5) print (t[0]) print (t[1]) print (t[2]) print (t[3]) print (t[4])

Tuples and lists are similar. However, the list can be assigned again after it is created, such as a[2] = 100. However, when attempting to use a tuple, an error is made. Tuples cannot be changed--and not without merit

You can assign multiple values in a, B = (), only tuples can.

Dictionary

D = {' name ': ' Jack ', ' Age ': ' 7 ', ' hobby ': ' Nothing '}print (d["name"]) print (d["age"]) print (a["hobby"])

You know what's going to print out. "Name" "Age" "hobby" (note the quotation marks, is the string) are the dictionary "key", "Jack" 7 "hobby" is the "value", "Jack" is the key "name" corresponding to the value, "name": "Jack" is called a "key value pair." A value can say anything that can be put into a variable, and the key must be something that cannot be modified (such as integers, strings, tuples)


Else

Baidu "Python3 Conditional statement"


Abnormal

Baidu "Python3 conditional statement", "Python3 assert" (assertion)


File operations

Code: (Self-understanding) (R is read, open in read mode, W is write, open in write mode, the original content will be cleared, you can also use a, open with Append mode, will continue to write at the end.) In short, can not change back)

With Open ("Demo. txt", ' W ') as Tp:tp.write ("six demo text \ n") Tp.write ("13 demo text") Tp.write ("20 demo text") with Open ("Demo. txt", ' r ') as Tp:print (Tp.read ()) print ("=" *20) print ("===============") with Open ("Demo. txt", ' r ') as Tp:print (Tp.readline ()) Print ( Tp.readline ())


Keyboard input

Code: (Enter confirm input)

s = input ("Input prompt >") print ("Just entered:", s)


Module (import)

from XXX import *, the equivalent of the same folder under the xxx.py file contents are all pasted here.

Import xxx, similar to the previous one, but if you want to use the variable a in that file, write xxx.a; Use the function in that file as XXX.F ()


Boolean value

True and false, and the normal variable name does not look much different (capitalized only), but reserved for Python, that is, it cannot be assigned a value. 1 = = 1 has a value of true,1! = 1 is false (not equal to the meaning), the value of 1== ' a ' is false,3 > 2 is True, the string and number can be compared for equality, the comparison size will be an error. If you force the addition of a Boolean value, True is treated as 1,false as 0.

Can search for "Boolean algebra"


Standard library

The library is a module. Most are placed under environment variables.

For example import OS can use Os.system ("echo Hello"), you know what that is, import sys can sys.stdout = open ("Xxxxxxxxxxxxxxxxxxxxxxx.txt", ' W '), And then just print something and see what happens.

Search for "Python standard library"


Ide

Some tutorials start with the IDE, and I think the command line needs to be spoken first. The so-called IDE is a more luxurious Notepad, and will give you a button (but often more than one button), click, will send a message to the command line, such as "Python xxx.py." I use Geany, I feel good. Anyway, I'm absolutely against the novice with VS and Eclipse, and I've just been able to read it (after all). Online search "Geany python" There is a tutorial, but the last step I put a diagram (the use of environment variables to come)

Only the execution of a column is useful, because Python hardly compiles. and seems to be able to paste all at once, can't input (my computer problem?) ), make a full copy in Notepad.


Class, Object-oriented

The next content.


Python Introductory tutorial (ii)

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.