Python basic tutorial _ study note 7: conditions, loops, and other statements

Source: Internet
Author: User

Condition, loop, other statements print and import

As you learn python more deeply, you may feel that some of the points you think you have learned are hidden with surprising features.

Output with commas

Print multiple expressions, as long as they are separated by commas:

>>> Print "age:", 28

Age: 28

A space character is inserted between parameters.

If a comma is added to the end, the following statement is printed in the same line as the previous statement:

Print "Hello ,",

Print "World! "

Result:

Hello, World!

Import one thing as another

When importing functions from a module, you can use:

Import somemodule

Or

From somemodule import somefunction

Or

From sommodule import somefunction, anotherfunction, yetanotherfunction

Or

From somemodule import *

The last version should be used only when you are sure that you want to import all functions from a given module.

What should I do if both modules have open functions?

You only need to use the first method for import and then use the function as follows:

Module1.open (...)

Module2.open (...)

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

>>> Import math as foobar

>>> Foobar. sqrt (4)

2.0

You can also provide aliases for functions:

>>> From math import sqrt as foobar

>>> Foobar (4)

2.0

For open functions, you can use them as follows:

From module1 import open as open1

From module2 import open as open2

Unpack a magic sequence with values

Multiple assignment operations can be performed simultaneously:

>>> X, y, z = 456

>>> Print x, y, z

1 23 456

Use it to exchange two or more variables:

>>> X, y = y, x

>>> Print x, y

23 1

>>> X, y, z = y, z, x

>>> Print x, y, z

1 456 23

In fact, what we do here is sequential unpacking or iterative unpacking-Unlocking the sequences of multiple values and placing them in the sequence of variables.

>>> Values = 1, 2, 3

>>> Values

(1, 2, 3)

>>> X, y, z = values

>>> Print x, y, z

1 2 3

This feature is particularly useful when a function or method returns tuples (or other sequences or iteratable objects. If you want to obtain (and delete) any key-value pairs in the dictionary, you can use the popitem method. This method returns the key-value pairs as tuples, therefore, this tuples can be directly assigned to two variables:

>>> People = {'name': 'signature', 'age': '28', 'weight': '72 '}

>>> X, y = people. popitem ()

>>> Print x, y

Age 28

>>> X, y = people. popitem ()

>>> Print x, y

Name signjing

>>> X, y = people. popitem ()

>>> Print x, y

Weight 72

It allows the function to return more than one value and package it into a metagroup. Then, it can be easily accessed through a value assignment statement. The number of elements in the sequence to be decompressed must be exactly the same as the number of variables placed on the left of the Value Pair =; otherwise, python will cause an exception when assigning values:

>>> X, y = 1, 3, 4

Traceback (most recent call last ):

File" ", Line 1, in

X, y = 1, 3, 4

ValueError: too has values to unpack

>>> X, y, z = 2, 9

Traceback (most recent call last ):

File" ", Line 1, in

X, y, z = 2, 9

ValueError: need more than 2 values to unpack

Chained assignment

Chained assignment is a shortcut to assign the same value to multiple variables.

X = y = somefunction ()

The effect is the same as that of the following statement:

Y = somefunction ()

X = y

Note: The preceding statement is not necessarily equivalent to the following statement:

X = somefunction ()

Y = somefunction ()

Incremental assignment

Place the expression operator on the left of the value assignment operator =. This method is called incremental value assignment. It is applicable to standard operators such as *,/, and %:

>>> X = 5

>>> X + = 3

>>> X * = 2

>>> X/= 4

>>> X

4

Other data types are also applicable (as long as binary operators themselves apply to these data types ):

>>> S = 'too'

>>> S + = 'signature'

>>> S * = 2

>>> S

'Toomount'

Statement Block

A statement block is a group of statements that are executed or executed multiple times when the condition is true (a Condition Statement. Place blank lines before the code to indent the statement to create the statement block.

Each line in the block must be indented to the same amount.

Many languages use special words or characters (such as begin or {) to indicate the start of a statement block, and other words or characters (such as end or}) to indicate the end of the statement block.

In python, the colon (:) is used to mark the beginning of the statement block. Each statement in the block is indented (with the same number of indentations ). When it is rolled back to the same indentation as the closed block, it indicates that the current block has ended.

Condition and Condition Statement Boolean variable

When the following value is used as a Boolean expression, it is interpreted as False ):

False None 0 "" () [] {}

In other words, that is, the standard values False and None, all types of numbers 0 (including floating point, long integer, 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.

The standard True values are True and False. In fact, True and False are just the "gorgeous" statements of 1 and 0.

>>> True

True

>>> False

False

>>> True = 0

False

>>> True = 1

True

>>> False = 0

True

>>> False = 1

False

>>> False + True + 23

24

Boolean values True and False belong to the boolean type. The bool function can be used to convert other values (like list, str, and tuple.

>>> Bool ('I think, therefore I am ')

True

>>> Bool (42)

True

>>> Bool (0)

False

>>> Bool ('')

False

>>> Bool (False)

False

>>> Bool (())

False

>>> Bool ({})

False

>>> Bool ([])

False

Because all values can be used as boolean values, there is almost no need to explicitly convert them (it can be said that python will automatically convert these values ).

Note: although [] and "" are both fake plants (that is, bool ([]) = bool ("") = False), they are not equal themselves. This is also true for other different types of dummy value objects (for example ,()! = False ).

Conditional execution and if statement

If statements can implement conditional execution. if the condition is true, the subsequent statement blocks are executed. if the condition is false, the statement blocks are not executed.

Name = raw_input ("Please input a name :")

If name. endswith ("Bob "):

Print "Hello, Bob! "

If you enter a name ending with Bob, the greeting is printed.

Else statement

An else clause (called a clause because it is not an independent statement and can only be part of an if statement) can be added.

Name = raw_input ("Please input a name :")

If name. endswith ("signjing "):

Print "Hello, signjing! "

Else:

Print "Hello, someone! "

If 1st statement blocks are not executed, 2nd statement blocks are transferred.

Elif statement

If you need to check multiple conditions, you can use elif. It is short for "else if" and is also used together by the if and else clauses -- that is, the conditional else clause.

Num = input ("Please input a num :")

If num> 0:

Print "num> 0"

Elif num <0:

Print "num <0"

Else:

Print "num = 0"

Nested code block

The if statement can be nested with the if statement:

Num = input ("Please input a num :")

If num> 0:

If num> 5:

Print "num> 5"

Elif num> 3:

Print "num> 3 and num <= 5"

Else:

Print "num <= 3 and num> 0"

Elif num <0:

If num <-10:

Print "num <-10"

Elif num <-4:

Print "num <-4 and num> =-10"

Else:

Print "num> =-4 and num <0"

Else:

Print "num = 0"

More complex condition comparison Operators

Expression description

X = y x equals y

X

X> y x greater than y

X> = y x greater than or equal to y

X <= y x 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.

Incompatible type

Theoretically, the comparison operator can be used to compare any two objects x and y with a relative size, and a Boolean value is returned. However, the comparison is meaningful only when x and y are objects of the same or approximate type.

In python, comparison operations and value assignment operations can be connected. Several operators can be connected and used together:

>>> A = 5

>>> 0

True

>>> 0

False

>>> 03

True

Equal Operators

To determine whether two things are equal, use the equal operator, that is, two equal signs =:

>>> "Abc" = "abc"

True

>>> "Abc" = "Abc"

False

A single equal operator is a value assignment operator, which is used to change the value and cannot be used for comparison.

Is: identity Operator

This operator is interesting. It looks the same as =, but actually it is different:

>>> X = y = [1, 2, 3]

>>> Z = [1, 2, 3]

>>> X = y

True

>>> X is y

True

>>> X = z

True

>>> X is z

False

X and z are equal but not the same, because the is operator determines the same identity rather than equality.

X and y are bound to the same list, while z is bound to another list with the same value and order. Their values may be equal, but they are not an object.

In: Membership Operator

I have explained it before, but it is omitted here;

String and Sequence Comparison

Strings can be sorted alphabetically for comparison.

>>> "A" <"B"

True

>>> "Abc" <"AB"

False

Note: The actual order may be different from the above example because different locale are used.

Other sequences can also be compared in the same way, but the comparison is not a character but other types of elements:

>>> [1, 2]> [1, 2, 3]

True

>>> [, [2, 'a'] <[, []

True

Boolean operator

The and operator concatenates two boolean values and returns true if both values are true. Otherwise, false is returned.

Or operator, concatenates two boolean values, and returns false when both values are false. Otherwise, returns true.

Not operator, concatenates a Boolean value. If the Boolean value of the connection is true, false is returned. If the Boolean value is false, true is returned.

Short Circuit Logic

X and y are true only when both variables are true. If x is false, x and y returns false immediately without calculating the value of y. Similarly, x or y is True if one of them is True. If x is True, x or y returns True directly without calculating the value of y. In this way, it can be used as a skill to avoid code execution without any land.

Assertions

The if statement has a very useful close relation, and its working method is somewhat like the following (pseudo code ):

If not condition:

Crash program

This is because it is better to let the program crash later than to let it crash when the error condition appears. In general, you can require certain conditions to be true. The keyword used in the statement is assert.

>>> Age = 10

>>> Assert 0

>>> Age =-2

>>> Assert 0

Traceback (most recent call last ):

File" ", Line 1, in

Assert 0

AssertionError

If you need to make sure that a certain condition in the program is true for the program to work normally, the assert statement is useful. You can set the checkpoint in the program:

After the condition, you can add a string (separated by a comma) to explain the assertion:

>>> Assert 0

Traceback (most recent call last ):

File" ", Line 1, in

Assert 0

AssertionError: make age right

Loop while LOOP

It is used to repeatedly execute a code block when any condition is true.

I = 5

While I> 0:

Print I

I-= 1

Result:

5

4

3

2

1

For Loop

List1 = list ('signature ')

For l in list1:

Print l

Result:

S

I

G

N

J

I

N

G

Numbers = [1, 2, 4]

For n in numbers:

Print n

Result:

1

2

3

4

Iterations (another statement of loops) numbers within a certain range are very common and there is a built-in function available:

For n in range (1, 5 ):

Print n

Result:

1

2

3

4

The range function works in the same way as a shard. It contains the lower limit and does not contain the upper limit. If you want the lower limit to be 0, you can only provide the upper limit.

Tip:

If you can use the for loop, try not to use the while loop.

Looping dictionary elements

A simple for statement can loop all the keys of the dictionary, just like the processing sequence:

D = {'X': 1, 'y': 2, 'z': 3}

For key in d:

Print key, d [key]

Result:

Y 2

X 1

Z 3

A major benefit of a for loop is that it can use sequence to unpack in a loop:

D = {'X': 1, 'y': 2, 'z': 3}

For key, value in d. items ():

Print key, value

Result:

Y 2

X 1

Z 3

Some iteration tools

Some functions are very useful in python for iterative sequences (or other iteratable objects. Some functions are in the itertools module, and some python built-in functions are also very useful.

Parallel Iteration

The program can iterate two sequences at the same time:

Names = ['Anne ', 'beth', 'damon ']

Ages = [13, 19, 21]

For I in range (len (names )):

Print names [I], 'is, ages [I], 'ears old .'

Result:

Anne is 13 years old.

Beth is 19 years old.

Damon is 21 years old.

The built-in zip function can be used for parallel iteration. The two sequences are "COMPRESSED" and a list of tuples is returned:

Names = ['Anne ', 'beth', 'damon ']

Ages = [13, 19, 21]

For name, age in zip (names, ages ):

Print name, "is", age, "years old ."

Result:

Anne is 13 years old.

Beth is 19 years old.

Damon is 21 years old.

The zip function can act on any number of sequences. The most important thing about it is that zip can cope with an unequal sequence: When the shortest sequence is "used up", it will stop:

>>> Zip (range (5), xrange (100 ))

[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]

>>> Zip (range (5), xrange (2 ))

[(0, 0), (1, 1)]

Number Iteration

Sometimes you want to iterate the objects in the sequence and obtain the index of the current object.

Temporarily omitted;

Flip and sort Iteration

Reversed and sorted are similar to the reverse and sort methods in the list. However, they act on any sequence or iteratable object. Instead of modifying the object in the original place, they return the flipped or sorted version:

>>> Sorted ([4, 3, 6, 8, 3])

[3, 3, 4, 6, 8]

>>> Sorted ('hello, world! ')

['! ', 'D', 'E', 'h', 'l', 'O', 'O ', 'R', 'w']

>>> List (reversed ('hello, world! '))

['! ', 'D', 'l', 'R', 'O', 'w',', ', 'O', 'l', 'l ', 'E', 'H']

>>> ''. Join (reversed ('hello, World '))

'Dlrow, olleh'

Bounce cycle break

You can use the break statement to end the loop.

For I in range (5 ):

Print I

If I> 2:

Break

Print "--"

Result:

0

--

1

--

2

--

3

Continue

The continue statement is used much less. It ends the current iteration and jumps to the beginning of the next loop. The basic meaning is: Skip the remaining loop body, but do not end the loop. It is useful when the loop body is large and complex.

For I in range (5 ):

Print I

If I> 2:

Continue

Print "--"

Result:

0

--

1

--

2

--

3

4

While True/break Idioms

While True implements a loop that never stops, but adds conditions to the if statement in the loop body to call the break statement when the conditions are met. In this way, you can terminate the loop at any point inside the loop rather than at the beginning.

Although you should be careful when using break statements frequently in code, this special technique is widely used.

Else clause in a loop

When the break statement is used inside the loop body, it is usually because something or something has been found, and it is easy to do something when jumping out, but sometimes you want to do something before you jump out. You can add an else statement in the loop -- only executed when break is not called.

For I in range (5 ):

Print I

If I> 6:

Break

Print "--"

Else:

Print "I'm here"

Result:

0

--

1

--

2

--

3

--

4

--

I'm here

You can use the continue, break statement, and else clause in both the for and while loops.

List derivation-lightweight Loop

List derivation is a method for creating a new list using other lists. The operation is similar to a for loop.

>>> [X * x for x in range (1, 6)]

[1, 4, 9, 16, 25]

The following conditions can be added:

>>> [X * x for x in range (1, 6) if x % 2 = 0]

[4, 16]

You can add more for statements:

>>> [X * y for x in range (1, 3) for y in (2, 5)]

[2, 5, 4, 10]

It can also be used together with the if statement:

>>> [X * y for x in range () for y in range () if x % 3 = 0 if y % 4 = 0]

[12, 24, 24, 48, 36, 72]

Note: There is no punctuation between the for loop and the if statement.

Nothing happened to the trio

Sometimes, the program does not need to do anything:

>>> Pass

>>>

Name = raw_input ("Please input a name :")

If name = 'signature ':

Print "I'm signjing"

Elif name = 'sj ':

Pass

Else:

Print "unknown"

Run:

Please input a name: signjing

Result:

I'm signjing

Run:

Please input a name: sj

If you comment the pass line:

If name = 'signature ':

Print "I'm signjing"

Elif name = 'sj ':

# Pass

Else:

Print "unknown"

Execution error:

File "pass. py", line 6

Else:

^

IndentationError: expected an indented block

Delete using del

In general, the python interpreter (with its infinite wisdom) automatically deletes objects that are no longer in use. Another method is to use the del statement, which not only removes the reference of an object, but also removes the name itself.

>>> X = ['hello', 'World']

>>> Y = x

>>> Y [1] = 'python'

>>> X

['Hello', 'python']

>>> Del x

>>> Y

['Hello', 'python']

In fact, there is no way to delete the value in python, because the python interpreter is responsible for memory reclaim when the value is no longer used.

Execute and evaluate strings using exec and eval

Sometimes python code is dynamically created and executed as a statement or as an expression, which is similar to "Dark Magic"-before that, be cautious and careful:

Exec

The statement for executing a string is exec:

>>> Exec "print 'hello '"

Hello

However, using simple exec statements is by no means a good thing. Most of the time, you can provide it with a namespace where variables can be placed.

>>> From math import sqrt

>>> Exec "sqrt = 1"

>>> Sqrt (4)

Traceback (most recent call last ):

File" ", Line 1, in

Sqrt (4)

TypeError: 'int' object is not callable

You can use in , Where It is the dictionary used to place the code string namespace.

>>> From math import sqrt

>>> Scope = {}

>>> Exec "sqrt = 1" in scope

>>> Sqrt (4)

2.0

>>> Scope ['sqrt ']

1

It can be seen that the potentially destructive Code does not cover the sqrt function, and the original function can work normally, while the variable sqrt assigned by exec is only valid within its scope.

Note: If you need to print the scope, you can see a lot of things, because the built-in _ builtins _ dictionary automatically contains all built-in functions and values:

>>> Len (scope)

2

>>> Scope. keys ()

['_ Builtins _', 'sqrt ']

Eval

Eval (used for "evaluate") is a built-in function similar to exec.

The exec statement executes a series of python statements, and the eval calculates the python expression and returns the result value.

The exec statement does not return any objects because it is a statement.

>>> Eval (raw_input ("Enter an arithmetic expression :"))

Enter an arithmetic expression: 2*6 + 8

20

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.