Python is a scripting language, and I also uh, but the real system of contact learning was at the end of last year (2013) to the beginning of this year (2014). Have to say is the official Python document is quite complete, if you are learning Python on Windows, the installation package of "Python Manuals" is a good learning material (basically do not have to find other materials); especially the tutorial, Very suitable for beginners. This paper summarizes the core of Python language-data type and control structure, on the other hand, it expresses my humble opinion of Python by contrast with other languages.
Data type
The simplicity behind Python is backed by a powerful type system. The basic data types of the Python world are {int, long, float, complex, str, list, set, tuple, dict}, which are shown below through the Python interpreter's input and output instance in interactive mode (with the leader character >> > Or ... Input): In the Tips:python world, you can use type (x) to output the types of x. int, long, float, str, complex
>>> type (123) <type ' int ' >>>> type ( -234) <type ' int ' >>>> type (123456123456) <type ' Long ' >>>> type ( -123456123456) <type ' long ' >>>> type (123.456) <type ' float ' >>>> type (' abc ') <type ' str ' >>>> type ("Hello, World") <type ' str ' >
From the last two inputs you can see that the Python string can be enclosed in single quotes or double quotes. In addition, you may wonder how big is int and how big is long? Let's explore the following:
>>> type (123456) <type ' int ' >>>> type (123456789) <type ' int ' >>>> type ( 1234567890) <type ' int ' >>>> type (12345678901) <type ' Long ' >
can see 1234567890 or int,12345678901 is a long, indicating that int is a range. Remember that the int length (4B) in C/s + + is aware that the value range of int in C/s + + is: [ -2^31, 2^31-1] that is [-2147483648, 2147483647]. Thus, we can look at Python's int range:
>>> type (2147483647) <type ' int ' >>>> type (2147483648) <type ' long ' >>>> type (- 2147483648) <type ' int ' >>>> type ( -2147483649) <type ' Long ' >
This experiment shows that Python's int range is the same as C + +. (In fact, as long, this is only because the 32-bit Python interpreter is running, and if it is a 64-bit Python interpreter, int is 8 bytes) then what if I want to specify a smaller long? can be suffixed by adding L (or lowercase L):
>>> type (1L) <type ' long ' >>>> type (2l) <type ' Long ' >
In addition, Python's floating-point number is not double:
>>> type (123.456) <type ' float ' >>>> type (123456123456.123456123456123456123456) <type ' Float ' >
complex (plural) plural types are not in many languages, Python uses integers plus j (or lowercase j) suffixes to denote complex numbers:
>>> type (3+4j) <type ' complex ' >>>> type (3+4j) <type ' complex ' >>>> type (4j) < Type ' complex ' >>>> type (j) Traceback (most recent call last): File "<stdin>", line 1, in <module& Gt Nameerror:name ' J ' is not defined>>> type (1j) <type ' complex ' >
However, 1j is not allowed to write directly j,j will be used as name lookup, if not found will be an error. Tuple, list, set, Dicttuple, list, set, Dict, respectively, are tuples, lists, sets, dictionaries (some languages are called map maps). These types are unique to the Python type system, and in most compiled languages (c, C + +, Java, C #, etc.), these types are provided through libraries (such as C + +, Java, C #), and perhaps libraries are not available (e.g. C).
>>> type ([1, 2, 3]) <type ' list ' >>>> type ({2, 3, 4}) <type ' Set ' >>>> type ((3, 4, 5)) <type ' tuple ' >>>> type ({' Key1 ': ' value1 ', ' key2 ': ' value2 '}) <type ' Dict ' >
Can see
(), [], {} and a series of elements enclosed in it, respectively: tuples, lists, collections。 And Dict is {key1:value1, [Key2:value2, ...]} The form. The various collections listed above are of the same element type, which is usually necessary in a compiled language, but not in Python:
>>> (1, ' both ', 3.0) (1, ' 3.0 ') >>> [(1, ' a ', ' 3.0 '), ' 4 ', 5][(1, ' a ', ' 3.0 '), ' 4 ', 5]>>> {1, 2 L, 3.0, 4j}set ([1, 2L, 3.0, 4j]) >>> {1: ' One ', ' One ': 1}{1: ' One ', ' One ': 1}
Control structure
When the structured programming method is put forward, it has been proved by predecessors that any algorithm can be used: sequence, selection, circulation three kinds of structure expression. The basic syntax of Python, along with selection and looping, is shown below. Sequential structure order structure itself there is nothing to say, here are some other features of Python. Statement
The Python statement ends with a newline character.(Unlike the end of the C-family semicolon):
>>> print ' Hello, world ' Hello, world
And the Python program has no so-called "portals", which are similar to most scripting languages. Weak type
Python is a weak type., that is, the type of the variable is not immutable. This is similar to many scripting languages.
>>> a = 123>>> B = "Asdf" >>> c = [3, 4, 5]>>> a123>>> B ' asdf ' >>> c[3 , 4, 5]>>> a = b>>> B ' asdf '
There are two points in this interaction that are different from the C language (c + +, etc.):
- Do not declare the type of the variable before using the variable
- When a variable is initialized to a type, it can be assigned another type of value.
Tip: Enter the variable name directly in the interactive mode of the Python interpreter to also display the value of the variableThe term "variable" in Python should be called "name" (or symbol) more precisely, in Python you can give a symbol any type of value. You'll see later that you can assign a value to a function, a class, to an object that was originally assigned an int. Function
the function definition of Python starts with Def, and if there is a return value you need to pass the return value with return. For example, the following code defines a function named SayHello and uses ' Jack ' to make a call to the parameter:
def sayHello (name):p rint ' Hello, ' + name + '! ' SayHello (' Jack ')
The result of this code is: Hello, jack! (You can save this code as sayhello.py, and then run the Python sayhello.py class in the corresponding directory)
the Python class definition starts with class, and the attribute can be declared under class or implicitly by Self.xxx in the __init__ method. Let's start with the simplest code for a class:
Class Man:def __init__ (self, name): Self.name = namedef Hello (self):p rint ' Hello, ' + self.name + '! ' m = Man (' Jack ') M.hello ()
This code will also output: Hello, jack!
the first parameter of the Tips:python method must be a parameter named self that is used to manipulate the members of the object. __init__ "Construction methods" similar to other languages.
The more features of the class are related to OOP, and there will be time to send a separate blog post. By the way, see what functions, classes, and instances of classes are in the Python interpreter's eye:
>>> type (SayHello) <type ' function ' >>>> type (man) <type ' classobj ' >>>> type (m) <type ' instance ' >>>> type (m.hello) <type ' Instancemethod ' >>>> type (Man.hello) <type ' Instancemethod ' >
It can be imagined that the python world of Things Are "gray", the interpreter "treat them equally", never judge by appearance, only look at their current label is what ~ Select structure
The python selection structure starts with an IF.
Boolif is bound to involve bool values, and the Python bool evaluates to True and false:
>>> type (1==1) <type ' bool ' >>>> type (True) <type ' bool ' >>>> type (False) < Type ' bool ' >
(The above seems to have forgotten to list the bool type) for number (int, long, float, complex), 0 is also false on the IF condition:
>>> if 1: ... Print "true" ...true>>> if 0: ... Print "true" ... else: ... Print "false" ...false>>> if 0.0: ... Print "0.0 is true" ...>>> if 0j: ... Print "0j is true" ...
tip: Python is a code block that is indented in code
In addition, empty strings and empty collections (tuple, list, set) are also false:
>>> if ': ... print ' null string is True ' ...>>> if (): ... print ' null tuple is true ' ...>>> if []: ... print ' null list is True ' ...>>> if {}: ... print ' null set is True ' ...
If, If-else & If-elif-else above several if examples are more than one branch, of course Python also supports multiple branches if:
>>> x = Int (raw_input ("Please enter a integer:")) Please enter an integer:42>>> if x < 0: ... x = 0 ... print ' negative changed to zero ' ... elif x = = 0: ... print ' Zero ' ... elif x = = 1: ... print ' single ' ... else: ... print ' More ' ... More
Loop structure
python loops have for and while two kinds, there is no do-while, there is no loop-until. Forpython's for loop differs from C in that it is more like the new for loop in C++,java:
>>> a = [1, ' II ', 3.0]>>> for I in a: ... Print I ... 1two3.0
This set of for iterations is convenient. But what if you want to iterate over an integer range like a typical C language for loop? Don't be afraid, Python provides a built-in (built-in) function range (), which returns a list of integer ranges that you can iterate over, and which is handy:
>>> for I in range (1, 6): ... Print I ... 12345>>> for I in range (ten, +): ... Print I ... 102030405060
This shows the two invocation forms of range, a range (A, b), which returns a list of integers from a (containing a) to B (not included), and another range (a, B, s), which returns a a~b, S-Step list:
>>> Range (1, 6) [1, 2, 3, 4, 5]>>> range (10, 65, 10) [10, 20, 30, 40, 50, 60]
The while loop of the Whilepython is the same as the C while:
>>> i = 1>>>>>> while I < 5: ... i = i+1 ... Print I ... 2345
By the way, i=i+1 in Python cannot be written I++,python does not support this syntax, but can be written as i + = 1:
>>> i5>>> i + = 1>>> i6>>> i++ File "<stdin>", line 1 i++ ^ Syntaxerror:invalid syntax>>> ++i6>>> I6
You may wonder why ++i can do that? Because Pyhon supports the pre-set + (sign) operation, + + is treated as two positive operations; the same is true for +++i,++++i; we can measure the minus sign operation by the way:
>>> i6>>> +++i6>>> ++++i6>>>-i-6>>>--i6>>>---i-6
Consistent with the imagined results, great!
Input/output (IO)
When you want to write a "more interesting" small program, you will find that in addition to the three basic control structures and data types, the most you need is the IO function. Q: The output can be printed with print, so what is the input? Is it input? A:input yes, but more often than not, the two built-in function may be raw_input and ReadLine, but ReadLine is only available for UNIX platforms. Q: So what's the difference between input and raw_input? A: Take a look at the next interaction between me and the interpreter to see if you can find out for yourself.
>>> VarA = raw_input (' Please input: ') * input:life is too short, you need python!>>> o Short, you need python! ' >>> type (raw_input (' Input something: ')) input something:asdf<type ' str ' >>>> type (raw_input (' Input something: ') input something:123<type ' str ' >
A: You see, Raw_input returns the STR type regardless of what you type, which is why it's called Raw_input. A: Continue down and you'll see input:
>>> type (input (' input sth: ')) input sth:123<type ' int ' >>>> type (input (' input sth: ')) input sth: Asdftraceback (most recent): file "<stdin>", line 1, in <module> file "<string>", Lin E 1, in <module>nameerror:name ' asdf ' are not defined>>> type (input (' input sth: ')) input Sth:vara<type ' s TR ' >>>> input (' sth: ') Sth:vara ' life are too short, you need python! ' >>> input (' Try some input like your code: ') Try some input like your code:[1, ' both ', 3.0][1, ' both ', 3.0]>>&G T Input (' Try again: ') Try again: ' Oh!!! ' OH!!! '
Python data types and control structures