How Python conditions and loops are used _python

Source: Internet
Author: User
Tags assert garbage collection in python

Several basic statements (Print,import, assignment statements) have been introduced before, and we introduce conditional statements, circular statements.
More information on print and import
1.1 Using comma output
A. Printing multiple expressions, separated by commas, inserts a spaces between each parameter:

Copy Code code as follows:

>>> print ' Age: ', 42
Age:42

B. Output text and variable values at the same time, but do not want to use string formatting:
Copy Code code as follows:

>>> name = ' Peter '
>>> greeting = ' Hello '
>>> print greeting, ', ', name
Hello, Peter.

The above example adds a space before the comma, and we can optimize it like this:
Copy Code code as follows:

>>> Print greeting + ', ', name
Hello, Peter.

Note that if you add a comma at the end, the next statement is printed on the same line as the previous sentence:
Copy Code code as follows:

>>> print ' Hello, ',
print ' World '
Hello,world

1.2 Import something as another thing
When you import a function from a module, you can use:
Entire module import: Import Somemodule
Import one of the functions: from Somemodule import somefunction
Import several of these functions: from Somemodule import somefunction,anotherfunction,yetanotherfunction
Import all functions: from somemodule Import *
If a 2 module has a function with the same name, such as the Open function, then you can give the function or module an alias:
Copy Code code as follows:

>>> Import Math
>>> Import Math as Foobar
>>> Foobar.sqrt (4)
2.0
>>> from math import sqrt as Foobar2
>>> Foobar2 (4)
2.0


Two. Assignment Magic
Even the humble assignment statement has some special skills.
2.1 Sequence Solution Package
A sequence solution is to untie the sequence of multiple values and then place them in a sequence of variables.

>>> # ' Multiple assignment operations simultaneous '
>>> x,y,z = 1,2,3
>>> print x,y,z
1 2 3
>>> # ' Swap 2 or more variables '
>>> x,y = y,x
>>> print x,y
2 1
>>> # ' When a function or method returns a tuple '
>>> s = {' A ': 1, ' B ': 2, ' C ': 3}
>>> key,value =  s.popitem ()
>>> print Key,value
a 1
As you can see in the last example, it allows a function to return more than one value and package the infinitesimal group, which is easy to access through a copy statement.
Note: The number of elements in the unpack sequence must be exactly the same as the number of variables placed on the left side of the assignment, or an exception will be thrown.

2.2 Chain Assignment
Chained assignment is the shortest way to assign the same value to multiple variables.
>>> x = y = ' sss '

2.3 Incremental Assignment
Incremental assignment can make your code more compact and concise. The
applies for standard operators such as +,-,*,/,%:

>>> x = 2
>>> x + 1
>>> x *= 2
>>> x
6
>>> #对其他数据类型也适用
>>> f = ' foo '
>>> f + + ' bar '
>>> F
' Foobar '

Three. Statement block: The fun of indentation
A statement block is a set of statements that are executed one or more times when the condition is true. In Python, a colon (:) is used to identify the beginning of a statement block, and each statement in the block is indented. When you fall back to the same indentation as a block that has already been closed, it means that the current block is over.

Four. Conditional and conditional statements
4.1 That's what Boolean variables are for.
The following value, when used as a Boolean expression, is interpreted by the interpreter as False (false):
False None 0 "" () [] {}
All other values are interpreted as true, including special value true.

4.2 Piece execution and if statement
If the condition is true, then the subsequent statement block is executed, and the elif can be added to perform multiple condition checks. As part of If, there is also the ELSE clause.
Of course, we can nest the IF statement inside the IF statement.

Copy Code code as follows:

num = input (' Enter a number? ')
If num > 0:
If num > 50:
print "num > 50"
Elif num > 10:
print "num > 10"
Else
print "num > 0"
Else
print "num <= 0"


4.3 more complex conditions
Let's go back to the conditions themselves, because they are really interesting parts of the conditional execution.
4.3.1. Comparison operators
Copy Code code as follows:

x = = y;     x < y;      x > y;      x >= y; x <= y;
x!= y;     X is y;   X is not y;     x in Y; x not in Y;


4.3.2. is: identity operator
Copy Code code as follows:

>>> x = y = [1,2,3]
>>> z = [1,2,3]
>>> x is y
True
>>> X is Z
False
>>> x = = Z
True

This shows that the = = operator is used to determine whether two objects are equal, and use is to determine whether the two objects are the same.

4.3.3. In: Membership operator
Copy Code code as follows:

Name = Raw_input ("What is your name?")
If ' s ' in Name:
print ' Your name contains the letter S '
Else
print ' Your name does not contain the letter S '

4.3.4. String and Sequence comparisons
Strings can be compared in character order.
>>> ' alpha ' < ' beta '
True
Characters are arranged according to their order values, and the order value of a letter can be found using the ORD function.
Other sequences can be compared in the same way, but the other types of elements are compared.
Copy Code code as follows:

>>> [1,2] > [2,1]
False
>>> [1,[2,3]] < [1,[3,2]]
True

4.3.5. Boolean operator
The AND operator is the so-called Boolean operator that joins 2 Boolean values and returns True when both are true, otherwise it returns false. There are also 2 operators, or and not, of its kind.
Copy Code code as follows:

Number = Raw_input ("Enter a number?")
If number <=10 and number >= 1:
Print "great!"

4.3.6. Assert
The IF statement has a close relative that works in a similar way:
Copy Code code as follows:

If not condition:
Crash program

This is because instead of crashing the program at a later time, it is better to let it crash when the error condition appears. The keyword used in the statement is assert. It ensures that a certain condition in your program is true for the program to work correctly.
Copy Code code as follows:

>>> Age =-1
>>> assert 0 < Age < 100
Traceback (most recent call last):
File "<pyshell#52>", line 1, in <module>
Assert 0 < Age < 100
Assertionerror

Five. Cycle
5.1 While loop
The while statement is flexible enough to repeat a block of code if any condition is true.
Copy Code code as follows:

Name = '
While not name:
Name = Raw_input (' Please enter your name: ')
print ' hello,%s! '% name

5.2 For Loop
When you want to execute a block of code for each element of a set (sequence and other iterated objects), we need a for loop.
5.2.1. Iterate through the dictionary elements
A simple for statement loops through all the keys of the dictionary, just as it does with sequences:
D = {' X ': 1, ' Y ': 2, ' Z ': 3}
For key in D:
Print key, ' corrensponds to ', D[key]
5.2.2. Some iterative tools
A. Parallel iterations
Copy Code code as follows:

names = [' A ', ' B ', ' C ', ' d ']
ages = [12,23,45,32]
#循环索引迭代
For I in range (len (names)):
Print Names[i], ' is ', ages[i ', ' years old. '
#内建zip函数迭代
For name,age in Zip (names,ages):
Print name, ' is ', age, ' years old. '

B. Numbering iterations
Sometimes an object in a sequence is iterated to get the index of the current object.
Copy Code code as follows:

#index计数
index = 0
For string in strings:
If ' xxx ' in string:
String[index] = ' SSS '
Index + 1

#内建enumerate函数迭代
For index,string in strings:
If ' xxx ' in string:
String[index] = ' SSS '

C. Flip and sort iterations
Functions reversed and sorted, acting on any sequence or iteration object, not modifying the object in situ, but returning the flipped or sorted version:
Copy Code code as follows:

>>> sorted ([2,6,3,7])
[2, 3, 6, 7]
>>> list (Reversed (' Hello '))
[' O ', ' l ', ' l ', ' e ', ' H ']

5.3 Jump out of circulation
In general, the loop executes until the condition is false, or when the sequence element is exhausted. But sometimes you need to interrupt a loop ahead of time.
5.3.1.break
End loops can use the break statement.
Copy Code code as follows:

For I in Range (0,10):
if i = = 5:
print ' Quit '
Break
Print I

5.3.2.continue
The continue statement lets the current iteration end and jumps to the beginning of the next round of loops.
Copy Code code as follows:

For I in Range (0,10):
If I% 2 = 0:
Continue
Print I

5.3.3.while True/break
For example, when the user enters a word at the prompt, do something, and end the loop after the user does not enter a word.
Copy Code code as follows:

While True:
Word = raw_input (' Enter a word: ')
If not word:
Break
print ' The word is ' + word

Six. List derivation--lightweight cycle
A list derivation is a way to create a new list from another list, working in a way that is similar to a for loop:
Copy Code code as follows:

>>> [x**2 for x in range (ten) if x 3 = 0]
[0, 9, 36, 81]
>>> [(X,y) for x in range (3) for Y in range (3)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2-1)

Seven. Three people line
As a final conclusion, let's look at 3 statements: Pass,del and exec
Pass: Do nothing, used in code to do placeholder use, easy to debug code.
Copy Code code as follows:

If a = = ' a ':
print ' Yes '
elif A = = ' B ':
Pass
Else
print ' No '

Del: Deletes objects that are no longer in use, which is used as garbage collection.
Copy Code code as follows:

>>> x = [1,2]
>>> y = x
>>> del X
>>> x
Traceback (most recent call last):
File "<pyshell#62>", line 1, in <module>
X
Nameerror:name ' x ' is not defined
>>> y
[1, 2]

Del deletes only the name, not the list itself, so in the above example, removing x does not affect Y.
EXEC: Dynamically create Python code and then execute it as a statement or evaluate as an expression. However, this can be a serious potential security vulnerability, and if the program executes a portion of the string in the user-supplied section as code, the program may lose control of the execution of the code.
Copy Code code as follows:

>>> exec "print ' Hello,world '"
Hello,world

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.