Python chapter II

Source: Internet
Author: User
Tags case statement

1. Underline _ represents the value of the last expression. Note: Only useful in the interpreter, showing the results of the previous operation.  2. The print statement can be formatted with%, similar to C. such as: >>> print '%s is number%d! '% ("Python", 1) Python is number 1!3. Python is very flexible, so even if you pass the number to%s, it will not have the same serious consequences as other strict language requirements.  4. Symbol >> used to redirect output, the following example redirects the output to the standard error output: Import sys print >> sys.stderr, ' Fatal error:invalid input! '  Import SYS print >> sys.stderr, ' Fatal error:invalid input! '  Here is an example of redirecting output to a log file: LogFile = open ('/tmp/mylog.txt ', ' a ') print >> logfile, ' Fatal error:invalid input! ' Logfile.close () 2.1.3 built-in function input () The easiest way to get data input from the user is to use the input () built-in function. It reads the standard input and assigns the read data to the specified variable. You can use the Int () built-in function to convert a user-entered string to an integer. Example: >>> user = input (' Enter login name: ') Enter login name:root >>> print ' Your login is: ', user Y Our login Is:root above This example can only be used for text input.  Here is an example of entering a numeric string (and converting the string to an integer): >>> num = raw_input (' Now enter a number: ') now enter a number:1024 >>> print ' Doubling your number:%d '% (int (num) * 2) Doubling your number:2048raw means "write after read". Core Notes: Getting help from the interactive interpreter in learning Python, if you need to get help with a strange function, you only need to call the built-in function helper (). By using the function name as the Help () parameter can get the corresponding helpful information: >>> (Input) Python uses the # symbol to mark the comment, starting with the #, until the end of the line is a comment. The 2.2 operator 2.2.1 The standard operator +-*/Standard operator, as in C. Note that/here is called the floor except (whichever is smaller than the largest integer). % of the remainder. Floating point division takes rounding. Always performs a true division. * * exponentiation operator, priority by mathematical law. Standard comparison operators that return bool values based on True or false: <<=>>===!=<> (eliminated) True false return False note: case sensitive. Logical operators: and = &&or = | | not =! Coding style: Parentheses do not have to exist in the Python language, but it is always worthwhile to use parentheses for readability. 2.3 Variables and assignment variable names begin with a letter. Python is a dynamic type language, meaning that you do not need to declare the type of the variable beforehand. The type and value of the variable are initialized at the moment of assignment. Variable assignment is performed by an equal sign. Support for incremental assignment: n = n * 10 Change the above example to an incremental assignment: N *= 10Python does not support the self-increment 1 and decrement 1 operators in the C language. 2.4 Number 1.    Python supports five basic numeric types, three of which are integer types. int (signed integer) long (Long Integer) bool (Boolean) float (floating-point value) complex (plural) 2. Note: Python long integers are limited to the total number of virtual memory on the user's computer. Starting with Python2.3, the integer overflow error is never reported, and the result is automatically converted to a long integer. 3.bool value: Same as C 1 and 04. Decimal, used for decimal floating-point numbers. 2.5 string 1. Python supports the use of paired single or double quotes, and three quotation marks (three consecutive single or double quotes) can be used to contain special characters 2. The substring can be obtained using the index operator ([]) and the Slice operator ([:]). 3. The string has its own index rule: The index of the first character is 0, the index of the last character is-1, 4. Note: strings are not supported for single assignments by index (or change of original value). Both: The string is notChange. 2.6 Lists and tuple lists and tuples can be used as normal arrays. It can hold any number of arbitrary types of Python objects. The subscript index starts at 0 (same as C). Differences between lists and tuples: 1 The list element is wrapped in brackets ([]), the number of elements and the value of the element can be changed.  Tuple elements are wrapped in parentheses (()) and cannot be changed (although their content can).  2 "tuples can be viewed as read-only lists. 3 List The subset can be obtained by slicing operations ([] and [:]), as with string usage methods.  The result is a list and its value can be changed. 4 The tuple can also perform slicing operations, and the resulting result is still a tuple. The value is still read-only. 2.7 Dictionary 1. A dictionary is a mapping data type in Python, similar to the number of associations and hash tables, consisting of key-value (key-value) pairs. 2. Almost all types of Python objects can be used as keys, although they are generally most commonly used as numbers or strings. 3. The value can be any type of Python object, and the dictionary element is wrapped in curly braces ({}). 4. Example:>>> adict = {' Host ': ' Earth '} # Create dict>>> adict[' port ' = # Add to dict>>> adict{ ' Host ': ' Earth ', ' Port ': 80}>>> adict.keys () [' Host ', ' Port ']>>> adict[' host '] ' Earth ' >>>  For key in adict:. Print key, Adict[key]...host earthport 802.8 code The block and indent alignment code blocks express the code logic by indenting the alignment instead of using curly braces. 2.9 If statement 1. The syntax for a standard if condition statement is as follows: If Expression:if_suite if the value of the expression is not 0 or is Boolean True, the code group If_suite is executed; Otherwise, proceed to the next statement. A code group is a Python term that consists of one or more statements that represent a block of child code. NOTE: Conditional expressions do not need to be enclosed in parentheses. If ... The else combination if Expression:if_suite Else:else_suitepython also supports elif (meaning "else-if") statements with the following syntax: If Expression1:if_suite el If expression2:elif_suite else:else_suite Note: Python does not have a switch......case statement. The 2.10 while loop uses indentation to separate each child code block with the following syntax: The while Expression:while_suite2.while statement has an optional ELSE clause. 2.11 For Loop and range () built-in functions 2.11.1 For Loop 1. Similar to a foreach iteration in a shell script, iterates over one element at a time by iterating over the object as an argument. 2. For example: >>> for a in Alist:print a will print out all the contents of alist (pre-defined table). Add a comma (,) after print to cancel wrapping. 2.11.2 for Loop use range () when we have a variable loop range, you can use the built-in function range (). Range () accepts the array range and generates a list.  Example: >> for Eachnum in range (3): ... print eachnum ...  0 1 2For Each element in the loop output string: >>> foo = ' abc ' >>> for C in foo: ... print c ... a b c >>>  foo = ' abc ' >>> for I in range (len (foo)): ... print foo[i], ' (%d) '% iAnother example of a (0) B (1) C (2) for: Using the Else Item #!/usr/bin/python # Filename:for.py for I in range (1, 5): Print I Else:p Rint ' The For loop was over ' output $ python for.py 1 2 3 4 The For loop was over from here: 1) Else executes only once. 2) range is the built-in function in the left-closed-right-open [,] type range. 3) range (1,5) gives the sequence [1, 2, 3, 4]2.11.3 range () By default, range has a step of 1. If we provide a third number for range, then it will be the step size. For example, Range (1,5,2) gives [1,3]. Remember that range extends up to the second number, that is, it does not contain a second number. 2.11.3 Enumerate () lists the built-in function 1.  The enumerate () function gets both the index and the element of the loop. >>> for I, ch in enumerate (foo): ... print ch, ' (%d) '% i ... a (0) B (1) C (2) 2.12 List resolution 1. Using a For loop in a row will all Values are placed in a list: >>> squared = [x * * 2 for X in range (4)] >>> for i in squared: ... print i 0 1 4 9 can be in the column  The table is parsed to determine the assigned value. >>> Sqdevens = [x * * 2 for X in range (8) if not x% 2] #求平方 >>> >>> for i in Sqdevens: ... p Rint I 0 4 36 162.13 file and the built-in function open (), file () 2.13.1 open files () handle = open (file_name, Access_mode = ' R ') where File_nam E file name Access_mode is open mode ' R ' for Read, ' W ' indicates write, ' a ' means Add. Other possibleThe used sound is also ' + ' for reading and writing, ' B ' for binary access. Return value: File handle.  About attributes: Core notes: What are attributes? Properties are data-related items, which can be simple data values or executable objects, such as functions and methods. Which objects have properties? A lot.  Classes, modules, files and complex numbers, and so on, have properties. How do I Access object properties? Use the period property to identify the method. In other words, add a period between the object name and the property name: the Object.attributefile () function is equivalent to open (), but the name of file () can more accurately indicate that it is a factory function. (Makefile object) is similar to an int () that generates an integer object, Dict () generates a Dictionary object. 2.14 Break statement and continuebreak terminate loop. An important note is that if you terminate from a for or while loop, any corresponding loop else blocks will not execute. 3. Continue is the same as C. Applies for both while and for.
1. What: A module is a form of organization that organizes Python code that is related to each other into separate files. A module can contain executable code, functions and classes, or a combination of these things.  2. Description: 1 "The name of the module is the file name without the. py suffix. 2. Import the module to use it with an import statement.  Access module: Import module_name Imports: Once the import is complete, the properties (functions and variables) of a module can be accessed through the familiar. Period property identifier. Module.function () module.variable example: Call the SYS module: (write it yourself) >>> import sys>>> sys.platform ' linux2 ' >> > Sys.stdout.write (' hello! ') Hello!>>> sys.version

Python chapter 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.