Python 30-minute primer-data type & Control structure

Source: Internet
Author: User

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). I have to say that Python's official documentation is quite complete, assuming that you are learning Python on windows, and that the "Python Manuals" that comes with the package is a very good learning material (basically no other material to look for); especially the tutorial, Perfect for people who have just started learning. This paper summarizes the core of Python language-data type and control structure, and on the one hand, it expresses my humble opinion of Python by contrast with other languages.


Data TypeThe 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}, and the following is demonstrated by the Python interpreter input and output instance in interactive mode (with leader >> > Or ... is the 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 used with a single argument or double-cited. In addition, you may wonder how big is int and how big is long? Here's what we'll explore:
>>> 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 + +. So, suppose 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 very many languages, and 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 ' >
but 1j do not agree to write directly j,j will be used as the name lookup, if not found will error.
tuple, list, set,Dicttuple, list, set, dict each 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 some may not be 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 ' >
be able to see (), [], {} and a series of elements enclosed in it, each representing: tuples, lists, collections . And Dict is {key1:value1, [Key2:value2, ...]} The form. The elements of the various collections listed above are of the same type, which is generally 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 Structurewhen the structured programming method is put forward, it is proved by predecessors that no matter what algorithm can be used: sequence, selection, circulation three kinds of structure expression. The following shows the basic syntax of Python, as well as selection and looping.
Sequential StructureThe sequential structure itself is nothing to say, here are some other features of Python. Statement The Python statement ends with a newline character (unlike 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 very 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.):
    1. Do not declare the type of the variable before using the variable
    2. 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 regardless of the 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, assuming that a return value is required 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 number of references:
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 execute the Python sayhello.py in the appropriate folder)
class the Python class definition starts with class, and the attribute can be declared under class and 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, which is used to manipulate the members of the object. __init__ is similar to the "construction method" of other languages.
Many of the other features of the class are related to OOP, and there is time to send a separate blog post to show it later.
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 ' >
Can imagine that the python world of Things Are "gray", the interpreter "treat them equally", never judge by appearance, just see what they are now the label is ~
Select Structure The python selection structure starts with If. BOOLif it is bound to involve a bool value, 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-elseThe above-mentioned if demo sample is more than just one branch, and of course Python 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 The Python loop has for and while two types , no do-while, and 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 intervals 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 (including a) to B (not included), and a range (a, B, s) that will return a a~b, S-Step list:
>>> Range (1, 6) [1, 2, 3, 4, 5]>>> range (10, 65, 10) [10, 20, 30, 40, 50, 60]

whilethe while loop of Python is almost identical to the while in C:
>>> i = 1>>>>>> while I < 5:     ... i = i+1     ... Print I ... 2345

By the way, i=i+1 in Python cannot be written as I++,python does not support such a 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? Since Pyhon supports pre-set + (sign) operations, + + is treated as two positive operations; in the same way, +++i,++++i are the same; we can measure the minus sign operation:
>>> 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 ainput? A:input can, but many other times it is possible to use the two built-in function for Raw_input and ReadLine, but ReadLine is only available for UNIX platforms .Q: So what is the difference between input and raw_input? A: Take a look at the following interactions 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!!! '
Q:oh, I know! Input interprets the inputs as code! A: Well, you mentioned "explain", it seems you have realized the true meaning of python, you can descend the mountain! Q:master, so you can do it? I think I know too little, don't I? A: There is a "Python cheats" for the teacher here, you can take it, all the questions you will find the answer, but the answer is not necessarily in this book (Acts a farewell master Q, began his journey of Python)
PostScript(in my humble opinion)Python is an interpreted language, and its type system is very powerful! As a learning a few C-family languages (c, C + +, Java, C #) I, tuple,list,set,dict are built-in type, is simply too beautiful! in my opinion: 1. Because of the language-level tuple, list, set, Dict,python is well suited for writing algorithms , and Python writes the algorithm must be more concise than other languages! The 2.Python syntax is simple and easy to understand, and the default provides file management, which can replace the work of most other scripts. The weak type of 3.Python (less constrained) and the interest and convenience of the interpreter interaction mode are suitable as the "first programming language" to teach children and adolescents.

Python 30-minute primer-data type &amp; Control structure

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.