Python Basic Tutorial Summary 4-Statements

Source: Internet
Author: User

I. More information on print and import

Print printing multiple expressions is also possible, as long as they are separated by commas:

    1. >>> Print (' Age: ', $ )
    2. Age:

As you can see, a space character is inserted between each parameter. This feature is useful if you want to output text and variable values at the same time, but do not want to use string formatting.

When importing functions from a module, you can use the

    1. Import Somemodule

Or

    1. From Somemodule import somefunction

Or

    1. From Somemodule import somefunction, anotherfunction, Yetanotherfunction

Or

    1. From Somemodule Import *

The last version should be used only if you are sure you want to import all features from a given module. But what if there are open functions in all two of the modules? Just use the first way to import and then use the function as follows:

    1. Module1.open (...)
    2. Module2.open (...)

There is another option: You can add an as clause at the end of the statement, give a name after the clause, or provide an alias for the entire module:

    1. >>> Import Math as Foobar
    2. >>> foobar.sqrt (4)
    3. 2.0

You can also provide aliases for functions:

    1. >>> from math import sqrt as Foobar
    2. >>> Foobar (4)
    3. 2.0

For the open function, it can be used as follows:

    1. From Module1 import open as Open1
    2. From Module2 import open as Open2

Second, assign the value

1. Sequence Unpacking

Multiple assignment operations can be performed simultaneously:

    1. >>> x, y, z = 1, 2, 3
    2. >>> Print (x, y, z)
    3. 1 2 3

Swap two (or more) variables with it:

    1. >>> x, y = y, X
    2. >>> Print (x, y, z)
    3. 2 1 3

In fact, what is done here is called a sequence unpacking (sequence unpacking) or an optional surrogate--the sequence of multiple values is unpacked and then placed in the sequence of variables. This feature is especially useful when a function or method returns a tuple (or other sequence or optional iterative object). It allows the function to return more than one value and to package the Narimoto group, which is then easily accessed through an assignment statement.

    1. >>> scoundrel = {' name ':' Robin ', ' girlfriend ':' Marion '}
    2. >>> Key, value = Scoundrel.popitem ()
    3. >>> Key
    4. ' Name '
    5. >>> value
    6. ' Robin '

The number of elements in the unpacked sequence must be exactly the same as the number of variables placed on the left of the assignment symbol =, otherwise Python throws an exception when the value is assigned:

  1. >>> x, y, z = 1, 2
  2. Traceback (most recent):
  3. File "<stdin>", line 1, in <module>
  4. Valueerror:need more than 2 values to unpack
  5. >>> x, y, z = 1, 2, 3, 4
  6. Traceback (most recent):
  7. File "<stdin>", line 1, in <module>
  8. Valueerror:too Many values to unpack (expected 3)

There is another feature of the Unpacking in Python 3.0: You can use the asterisk operator as you would in a function's argument list. For example, A, B, *rest = [1, 2, 3, 4] Eventually all other parameters are collected into rest after both A and B are assigned.

2. Chained assignment

Chained assignment (chained Assignment) is a shortcut to assigning the same value to multiple variables. x = y = somefunction ()

3. Incremental assignment

Place the expression operator (in this case, +-) on the left side of the assignment operator =, written as x +=1. This notation is called incremental assignment.

    1. >>> x = 2
    2. >>> x + = 1
    3. >>> x *= 2
    4. >>> x
    5. 6

Also applicable for other data types:

    1. >>> Fnord = ' foo '
    2. >>> Fnord + = ' Bar '
    3. >>> Fnord *= 2
    4. >>> Fnord
    5. ' Foobarfoobar '

Third, statement block

A statement block is a set of statements that executes or executes multiple times (a loop statement) when the condition is true (a conditional statement). You can create a statement block by placing a space in front of the code to indent the statement.

In Python, a colon (:) is used to identify the beginning of a statement block, and each statement in the block is indented (the same indent). When you fall back to the same indent as an already closed block, it means that the current block is closed.

Iv. Conditions and conditional statements

1. Boolean variables

The following values, when used as Boolean expressions, are interpreted by the interpreter as False (false):

False None 0 "" () [] {}

In other words, the standard values are false and None, all types of numbers 0 (including floating-point, long, and other types), empty sequences (such as empty strings, tuples, and lists), and empty dictionaries are false. Everything else is interpreted as true, including the special value TRUE.

Boolean values True and False are Boolean types, and BOOL functions can be used (as with list, str, and tuple) to convert other values.

    1. >>> bool (' I think, therefore I am ')
    2. True
    3. >>> bool (a)
    4. True
    5. >>> bool (')
    6. False
    7. >>> bool (0)
    8. False

Because all values can be used as Boolean values, there is little need for them to be displayed (it can be said that Python automatically converts these values).

2. Conditional Execution (IF/ELSE/ELIF)

    1. num = input (' Enter a number: ')
    2. If num > 0:
    3. print (' The number ispositive ')
    4. Elif Num < 0:
    5. print (' The number isnegative ')
    6. Else
    7. print (' The number iszero ')


3. Nested code blocks

  1. Name = Raw_input (' What's your name? ')
  2. If Name.endswith (' Gumby '):
  3. if Name.startswith (' Mr. '):
  4. print (' Hello, Mr. Gumby ')
  5. elif name.startswith (' Mrs. '):
  6. print (' Hello, Mrs. Gumby ')
  7. Else:
  8. print (' Hello, Gumby ')
  9. Else
  10. print (' Hello, Stranger ')

4. More complex strips

4.1 Comparison operators

An expression Description
X==y X equals y
X < y x less than Y
X > Y x greater than Y
X >= y X is greater than or equal to Y
X <= y X is less than or equal to Y
X! = y X is not equal to Y
X is Y X and Y are the same object
X is not Y X and Y are different objects
X in Y X is a member of the Y container
X not in Y X is not a member of the Y container

In Python 3.0, it is no longer feasible to compare objects of incompatible types.

In Python, the comparison and assignment operations can be connected--several operators can be used together, such as: 0 < Age < 100.

4.2 Equality operators

If you want to know whether two things are equal, you should use the equality operator, which is two equals = =:

[Python]View Plaincopy
    1. >>> "foo" = ="foo"
    2. True
    3. >>> "foo" = ="Bar"
    4. False

4.3 is: identity operator

The IS operator determines identity rather than equality.

[Python]View Plaincopy
    1. >>> x = y = [ 1, 2, 3]&NBSP;&NBSP;
    2. >>> z = [1, 2,  3]&NBSP;&NBSP;
    3. >>> x ==  y  
    4. TRUE&NBSP;&NBSP;
    5. >>> x  == z  
    6. TRUE&NBSP;&NBSP;
    7. >> > x is y  
    8. true   
    9. >>> x IS&NBSP;Z&NBSP;&NBSP;
    10. FALSE&NBSP;&NBSP;

Use the = = operator to determine whether two objects are equal, using is to determine whether the two are equivalent (the same object).

4.4 In: Membership operator

4.5 String and sequence comparisons

Strings can be compared in alphabetical order.

[Python]View Plaincopy
    1. >>> "Alpha" < "Beta"
    2. True

Other sequences can be compared in the same way, but not characters but other types of elements.

[Python]View Plaincopy
    1. >>> [1, 2] < [2, 1]
    2. True

4.6 Boolean operators

The and, or, and not operators are called Boolean operators.

5. Assertions

Python Basic Tutorial Summary 4-Statements

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.