Python automation development: Cycle times control, common data types, string formatting, list common operations, list of follow-up operations detailed introduction

Source: Internet
Author: User
Tags mathematical constants
The function of the counter can be automatically exited in the dead loop, if the condition is met.

#!/usr/bin/env python# _*_ coding:utf-8 _*_# @Time    : 2017/3/14 11:23# @Author  : eason# @File    : Guest_lucknum. Py.pylucky_num = 19input_num = -1guset_num = 0while guset_num<3:    input_num = Int (raw_input ("Input The Guess num:"))    if Input_num > Lucky_num:        print ("The real number is smaller.")    Elif Input_num < lucky_num:        print ("The real num is bigger ...")    else:        print ("bingo!")        Break    Guset_num + = 1else:    print ("Too many retrys!")

The results obtained

C:\Python27\python.exe d:/worklog/pytools/s12/day1/guest_lucknum_limit.py
Input The Guess Num:10
The real num is bigger ...
Input The Guess num:19
Bingo!

Using a for override, you can eliminate the counting method

#!/usr/bin/env python# _*_ coding:utf-8 _*_# @Time    : 2017/3/14 11:23# @Author  : eason# @File    : Guest_lucknum. Py.pylucky_num = 19input_num = -1for i in range (3):    input_num = Int (raw_input ("Input The Guess num:"))    if Input_nu M > Lucky_num:        print ("The real number is smaller.")    Elif Input_num < lucky_num:        print ("The real num is bigger ...")    else:        print ("bingo!")        Breakelse:    Print ("Too many retrys!")

Common types of data

The specific explanation, in Liaoche's blog has the notes, is here to affix the address and the content

Http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/ 001431658624177ea4f8fcb06bc4d0e8aab2fd7aa65dd95000 data Type a computer, by definition, is a machine that can do mathematical calculations, so a computer program can handle a variety of values. However, the computer can handle far more than the numerical value, but also can deal with text, graphics, audio, video, web and other kinds of data, different data, need to define different data types. In Python, there are several types of data that can be processed directly: integer python can handle integers of any size, including negative integers, which are represented in the program in the same way as mathematically, for example: 1,100,-8080,0, and so on. Computer because of the use of binary, so, sometimes hexadecimal notation is more convenient, hexadecimal with 0x prefix and 0-9,a-f, such as: 0XFF00,0XA5B4C3D2, and so on. Floating-point numbers, which are decimals, are called floating-point numbers because, when represented by scientific notation, the decimal position of a floating-point number is variable, for example, 1.23x109 and 12.3x108 are exactly equal. Floating-point numbers can be written in mathematical notation, such as 1.23,3.14,-9.01, and so on. But for very large or very small floating-point numbers, it must be expressed in scientific notation, the 10 is replaced with E, 1.23x109 is 1.23e9, or 12.3e8,0.000012 can be written 1.2e-5, and so on. Integers and floating-point numbers are stored inside the computer in different ways, and integer operations are always accurate (is division accurate?). Yes! ), and the floating-point operation may have rounding errors. string strings are arbitrary text enclosed in single quotes ' or double quotes, such as ' abc ', ' XYZ ', and so on. Note that the ' or ' itself is only a representation, not a part of the string, so the string ' abc ' only a,b,c these 3 characters. If ' itself is also a character, then you can use "", such as "I m OK" contains the characters are I, ', M, space, o,k these 6 characters. What if the inside of a string contains both ' and contains '? You can use the escape character \ To identify, for example: ' I\ ' m \ ' ok\ '! ' The string content represented is: I ' m "OK"! Escape character \ Can escape a lot of characters, such as \ n for the newline, \ t for the tab, the character \ itself to escape, so \ \ means the character is \, you can print the string in Python's interactive command line () to see:> >> print (' I\ ' mOk. ') I ' m ok.>>> print (' I\ ' m learning\npython. ') I ' m learningpython.>>> print (' \\\n\\ ') \ \ \ \ If there are many characters in the string that need to be escaped, you need to add a lot of \, in order to simplify, Python also allows to use R ' ' to indicate that the string inside of ' is not escaped by default, You can try it yourself.:>>> print (' \\\t\\ ') \ \>>> print (R ' \\\t\\ ') \\\t\\ If there is a lot of line wrapping inside the string, it is not good to read in one line, in order to simplify, Python allows you to format multiple lines of content in "...", and you can try:>>> print ("Line1 ... line2 ... line3") Line1line2line3 above is entered in the interactive command line, Note When you enter multiple lines of content, the prompt changes from >>> to ..., prompting you to enter on the previous line. If written as a program, it is: print ("' Line1line2line3 ') multi-line string ' ... ' can also be used in front of the R, please test yourself. Boolean Boolean values are exactly the same as Boolean algebra, with a Boolean value of only true, false two, or true, or false, in Python, which can be used to indicate a Boolean value directly with True, false (note case), or by Boolean operations: >>> truetrue>>> falsefalse>>> 3 > 2true>>> 3 > 5False Boolean values can be operated with and, or, and not. The and operation is associated with an operation, and only the result of all True,and operations is true:>>> true and truetrue>>> true and falsefalse>>> False and falsefalse>>> 5 > 3 and 3 > 1Trueor operations are or operations, as long as one of them is the result of a true,or operation is true:>>> True or truetrue>& Gt;> True or Falsetrue>>> False or falsefalse>>> 5 > 3 or 1 > 3Truenot operation is a non-operation, it is a monocular operator, turns true into False,false true:>>> not Tru Efalse>>> not falsetrue>>> not 1 > 2True Boolean values are often used in conditional judgments, such as: if Age >= 18:print (' adult ') ELSE:PR An int (' teenager ') null value is a special value in Python, denoted by none. None cannot be understood as 0, because 0 is meaningful, and none is a special null value. In addition, Python provides a variety of data types such as lists, dictionaries, and also allows you to create custom data types, which we'll continue to talk about later. The concept of variable variables is basically the same as the equation variables in junior algebra, but in computer programs, variables can be not only numbers, but also arbitrary data types. Variables are represented by a variable name in the program, and the variable name must be a combination of uppercase and lowercase English, numeric, and _, and cannot start with a number, for example: a = 1 variable A is an integer. t_007 = ' T007 ' variable t_007 is a string. Answer = True Variable Answer is a Boolean value of true. In Python, equals = is an assignment statement, you can assign any data type to a variable, the same variable can be repeatedly assigned, and can be different types of variables, for example: a = 123 # A is an integer print (a) a = ' ABC ' # A changed to a string print (a) This type of variable itself is called Dynamic language, which corresponds to static language. Static languages must specify the variable type when defining the variable, and if the type does not match, an error is given. For example, Java is a static language, the assignment statement is as follows (//For comment): int a = 123; A is an integer type variable a = "ABC"; Error: You cannot assign a string to an integer variable compared to a static language, which is why dynamic languages are more flexible. Do not equate an equal sign of an assignment statement with a mathematical equal sign. For example, the following code: x = 10x = x + 2 If mathematically understood x = x + 2 That is not true in any case, in the program, the assignment statement first calculates the right expression X + 2, obtains the result 12, and assigns to the variable x. Since the value before X is 10, the value of X becomes 12 after the value is re-assigned. Finally, it is important to understand the representation of variables in computer memory. When we write: a = 'ABC ', the Python interpreter did two things: Create an ' abc ' string in memory, create a variable named a in memory, and point it to ' ABC '. You can also assign a variable A to another variable B, which actually points the variable B to the data that the variable a points to, such as the following code: A = ' abc ' b = AA = ' xyz ' Print (b) The last line prints out the contents of variable B is ' ABC ' or ' xyz '? If we understand mathematically, we will mistakenly conclude that B and a are the same, and should be ' XYZ ', but actually the value of B is ' abc ', let us execute the code in one line, we can see exactly what happened: execute a = ' abc ', the interpreter created the string ' ABC ' and variable A, and pointed a to ' ABC ': py-var-code-1 executes B = A, the interpreter creates the variable B and points B to the string ' ABC ' that points to a: py-var-code-2 executes a = ' xyz ', the interpreter creates the string ' xyz ' and changes the direction of a to ' XYZ ', but B has not changed: py-var-code-3 So, the result of printing variable B at last is ' ABC '. Constant constants are immutable variables, such as the usual mathematical constants π is a constant. In Python, constants are typically represented in all uppercase variable names: pi = 3.14159265359 But in fact pi is still a variable, and Python doesn't have any mechanism to guarantee that PI will not be changed, so it is a customary usage to use all uppercase variable names to denote constants. If you must change the value of the variable pi, no one can stop you. Finally, explain why the division of integers is also accurate. In Python, there are two divisions, a division is/:>>> 10/33.3333333333333335/Division computes a floating-point number, even if two integers are evenly divisible, and the result is a floating-point number:>>> 9/ 33.0 There is also a division is//, called the floor except, the division of two integers is still an integer:>>> 10//33 You do not see wrong, the whole number of the floor except//is always an integer, even if not endless. To do the exact division, use/can. Because//division takes only the integer part of the result, Python also provides a remainder operation that can get the remainder of two integers:>>> 10 31 Regardless of whether the integer is a//division or the remainder, the result is always an integer, so the result of the integer operation is always accurate.

  

formatting strings

#!/usr/bin/env python# _*_ coding:utf-8 _*_# @Time    : 2017/3/15 10:39# @Author  : eason# @File    : String_format. Pyname = Raw_input ("Name:") Age = Raw_input ("Age:") job = Raw_input ("Job:") msg = ' Information of%s: name:%s age    '    :%s    job:%s "% (name,name,age,job) print (msg)

Result is

C:\Python27\python.exe d:/worklog/pytools/s12/day1/string_format.py
Name:eason
Age:30
Job:it

Information of Eason:
Name:eason
Age:30
Job:it

Common features of strings:

...

Strip () Remove the space around the string

List

View all functions of the list dir (name_list)

Name_list.index ("65brother") can find the corresponding index value, but this can only find a record, then if there are several similar records, it is wrong, need

Name_list.count ("65brother")

Name_list.insert (2, "66brother") is inserted in the 2 position

Name_list.pop () Delete a bit last

Name_list.remove ("65brother") deletes a specified element

For I in range (Name_list.count (' 65brother ')): Name_list.remove ("65brother")

Slice Name_list[0:2] Slice is Guxio regardless of tail

Name = "Alex"

Name_list.extend (name) will put Alex split into the list

Detailed usage of the list

Http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/ One of the data types built into the 0014316724772904521142196b74a3f8abf93d8e97c6ee6000<br>listlistpython is the list: lists. A list is an ordered set of elements that can be added and removed at any time. For example, list all the classmates in the class name, you can use a list to represent:>>> classmates = [' Michael ', ' Bob ', ' Tracy ']>>> classmates[' Michael ', ' Bob ', ' Tracy '] variable classmates is a list. Use the Len () function to get the number of list elements:>>> Len (classmates) 3 uses an index to access the elements of each position in the list, remembering that the index is from 0:>>> classmates[0] ' Michael ' >>> classmates[1] ' Bob ' >>> classmates[2] ' Tracy ' >>> classmates[3]traceback (most Recent call last): File ' <stdin> ', line 1, in <module>indexerror:list index out of range when the index is out of range, Python will report a Indexerror error, so to ensure that the index does not cross over, remember that the index of the last element is Len (classmates)-1. If you want to take the last element, in addition to the index location, you can also use 1 to index, directly get the last element:>>> Classmates[-1] ' Tracy ' and so on, you can get the bottom 2nd, the bottom 3rd:>>>  Classmates[-2] ' Bob ' >>> classmates[-3] ' Michael ' >>> classmates[-4]traceback (most recent call last): File "<stdiN> ", line 1, inch <module>indexerror:list index out of range of course, the last 4th one crosses the line. List is a mutable ordered table, so you can append elements to the list to the end of:>>> classmates.append (' Adam ') >>> classmates[' Michael ', ' Bob ', ' Tracy ', ' Adam ') can also insert elements into the specified position, such as the position of index number 1:>>> classmates.insert (1, ' Jack ') >>> classmates[' Michael ', ' Jack ', ' Bob ', ' Tracy ', ' Adam '] to delete the element at the end of the list, use the Pop () method:>>> Classmates.pop () ' Adam ' >>> classmates[' Michael ', ' Jack ', ' Bob ', ' Tracy '] to delete the element at the specified position, using the pop (i) method, where I is the index position:>>> classmates.pop (1) ' Jack ' >>> classmates[' Michael ', ' Bob ', ' Tracy '] to replace an element with another element, you can assign a value directly to the corresponding index position:>>> classmates[1] = ' Sarah ' >>> classmates[' Michael ', ' Sarah ', ' Tracy ']list the data type of the elements inside can also be different, such as:>>> L = [' Apple ', 123, True] The list element can also be another list, such as:>>> s = [' Python ', ' Java ', [' asp ', ' php '], ' scheme ']>>> len (s) 4 to note that S has only 4 elements, of which s[2 ] is a list, if it is easier to understand the:>>> p = [' asp ', ' php ']>>> s = [' Python ', ' Java ', p, ' scheme '] to get ' php ' can write p[1] or s [2] [1], so s can beAs a two-dimensional array, similar to three-dimensional, four-dimension ... arrays, but rarely used. If an element is not in a list, it is an empty list with a length of 0:>>> L = []>>> len (l) 0

  

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.