How to Use python conditions and loops

Source: Internet
Author: User

We have already introduced several basic statements (print, import, and value assignment statements). Next we will introduce conditional statements and cyclic statements.
I. More information about print and import
1.1 output with commas
A. print multiple expressions separated by commas. A space character is inserted between each parameter:
Copy codeThe Code is 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 codeThe Code is as follows:
>>> Name = 'Peter'
>>> Greeting = 'hello'
>>> Print greeting, ',', name
Hello, Peter

In the preceding example, a space is added before the comma, which can be optimized as follows:
Copy codeThe Code is as follows:
>>> Print greeting + ',', name
Hello, Peter

Note: If you add a comma at the end, the following statement is printed in the same line as the previous statement:
Copy codeThe Code is as follows:
>>> Print 'hello ,',
Print 'World'
Hello, world
 
1.2 import one thing as another
When importing functions from a module, you can use:
Import the entire module: import somemodule
Import one of the functions: from somemodule import somefunction
Import several functions: from somemodule import somefunction, anotherfunction, yetanotherfunction
Import all functions: from somemodule import *
If two modules have functions with the same name, for example, open functions, You can provide aliases for functions or modules as follows:
Copy codeThe Code is as follows:
>>> Import math
>>> Import math as foobar
>>> Foobar. sqrt (4)
2.0
>>> From math import sqrt as foobar2
>>> Foobar2 (4)
2.0


2. assign values to magic
Even a humble assignment statement has some special skills.
2.1 Sequence unpacking
Sequence unpacking is to unbind the sequences of multiple values and place them in the sequence of variables.

>>># 'Perform multiple assignment operations simultaneously'
>>> X, y, z = 1, 2, 3
>>> Print x, y, z
1 2 3
>>># 'SWAp two or more variables'
>>> X, y = y, x
>>> Print x, y
2 1
>>># 'When a function or method returns a tuples'
>>> S = {'A': 1, 'B': 2, 'C': 3}
>>> Key, value = s. popitem ()
>>> Print key, value
A 1
The last example shows that it allows the function to return more than one value and package it into a metagroup. Then, it can be easily accessed through a copy statement.
Note: The number of elements in the unwrapped sequence must be exactly the same as the number of variables placed on the left that match the value assignment. Otherwise, an exception is thrown.

2.2 chain assignment
Chained assignment is a shortcut to assign the same value to multiple variables.
>>> X = y = 'ss'

2.3 Incremental assignment
Incremental assignment makes the code more compact and concise.
Applicable to +,-, *,/, %, and other standard operators:

>>> X = 2
>>> X + = 1
>>> X * = 2
>>> X
6
>>># Applicable to other data types
>>> F = 'foo'
>>> F + = 'bar'
>>> F
'Foobar'

III. Statement block: ease of play
A statement block is a group of statements that are executed once or multiple times when the condition is true. In python, the colon (:) is used to mark the beginning of the statement block. Each statement in the block is indented. When it is rolled back to the same indentation as the closed block, it indicates that the current block has ended.

Iv. Condition and condition statements
4.1 This is the role of a Boolean variable
When the following value is used as a Boolean expression, it will be spoofed by the interpreter (False ):
False None 0 "" () [] {}
All other values are interpreted as True, including special values as True.

4.2 conditional execution and if statement
If the condition is true, the subsequent statement blocks are executed. You can also add elif to perform multiple condition checks. As part of if, there is an else clause.
Of course, we can use the if statement nested in the if statement.
Copy codeThe Code is 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
Next we will return to the condition itself, because they are really interesting parts of conditional execution.
4.3.1. Comparison Operators
Copy codeThe Code is as follows:
X = y; x <y; x> = y; x <= y;
X! = Y; x is not y; x in y; x not in y;


4.3.2. is: identity Operator
Copy codeThe Code is as follows:
>>> X = y = [1, 2, 3]
>>> Z = [1, 2, 3]
>>> X is y
True
>>> X is z
False
>>> X = z
True

We can see that the = Operator is used to determine whether two objects are equal, and the is operator is used to determine whether the two objects are the same.

4.3.3. in: Membership Operator
Copy codeThe Code is 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. Comparison of strings and Sequences
Strings can be sorted in character order for comparison.
>>> 'Alpha' <'beta'
True
Characters are arranged according to their own sequential values. You can use the ord function to check the sequential values of a letter.
Other sequences can be compared in the same way, but compared with other types of elements.
Copy codeThe Code is as follows:
>>> [1, 2]> [2, 1]
False
>>> [1, [2, 3] <[1, [3, 2]
True
 
4.3.5. boolean operator
The and operator is a so-called boolean operator. It connects two boolean values and returns true if both values are true. Otherwise, false is returned. There are two operators like this, or and not.
Copy codeThe Code is as follows:
Number = raw_input ("enter a number? ")
If number <= 10 and number> = 1:
Print "great! "

4.3.6. Assertions
The if statement has a close relative, which works in the following way:
Copy codeThe Code is as follows:
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. The keyword used in the statement is assert. It ensures that the program works normally only when a condition in the program is true.
Copy codeThe Code is 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
 
V. Loop
5.1 while LOOP
The while statement is very flexible. You can execute a code block repeatedly when any condition is true.
Copy codeThe Code is as follows:
Name =''
While not name:
Name = raw_input ('Please enter your name :')
Print 'hello, % s! '% Name

5.2 for Loop
To execute a code block for each element of a set (sequence and other iteratable objects), we need a for loop.
5.2.1. cyclically traverse 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, 'correnames ds to ', d [key]
5.2.2. Some iteration tools
A. Parallel Iteration
Copy codeThe Code is as follows:
Names = ['A', 'B', 'C', 'D']
Ages = [12, 23, 45, 32]
# Loop index Iteration
For I in range (len (names )):
Print names [I], 'is, ages [I], 'ears old .'
# Built-in zip Function Iteration
For name, age in zip (names, ages ):
Print name, 'is ', age, 'ears old .'

B. Number Iteration
Sometimes, the index of the current object must be obtained when an object in the iteration sequence is used.
Copy codeThe Code is as follows:
# Index count
Index = 0
For string in strings:
If 'xxx' in string:
String [index] = 'ss'
Index + = 1

# Nested enumerate Function Iteration
For index, string in strings:
If 'xxx' in string:
String [index] = 'ss'

C. Flip and sort Iteration
The reversed and sorted Functions Act on any sequence or iteratable object. Instead of modifying the object in the original place, they return the flipped or sorted version:
Copy codeThe Code is as follows:
>>> Sorted ([2, 6, 3, 7])
[2, 3, 6, 7]
>>> List (reversed ('hello '))
['O', 'l', 'l', 'E', 'E', 'H']

5.3 skip Loop
In general, the loop continues until the condition is false or when the sequence element is used up. But sometimes a loop needs to be interrupted in advance.
5.3.1.break
You can use the break statement to end the loop.
Copy codeThe Code is as follows:
For I in range (0, 10 ):
If I = 5:
Print 'quit'
Break
Print I

5.3.2.continue
The continue statement will end the current iteration and jump to the start of the next loop.
Copy codeThe Code is as follows:
For I in range (0, 10 ):
If I % 2 = 0:
Continue
Print I

5.3.3.while True/break
For example, when a user enters a word at a prompt, the cycle ends after the user does not enter the word.
Copy codeThe Code is as follows:
While True:
Word = raw_input ('enter a word :')
If not word:
Break
Print 'the word is '+ word

6. List derivation-lightweight Loop
The list derivation is a way to create a new list using another list, working in a way similar to a for Loop:
Copy codeThe Code is as follows:
>>> [X ** 2 for x in range (10) 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), (2, 2)
 
VII. threesome
Finally, let's look at three statements: pass, del, and exec.
Pass: Do nothing. It is used as a placeholder in the Code to facilitate code debugging.
Copy codeThe Code is as follows:
If a = 'A ':
Print 'yes'
Elif a = 'B ':
Pass
Else:
Print 'no'

Del: delete objects that are no longer in use, that is, used for garbage collection.
Copy codeThe Code is 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 only deletes the name, not the List itself. Therefore, in the preceding example, deleting x does not affect y.
Exec: dynamically create python code and execute it as a statement or as an expression. However, this may cause serious potential security vulnerabilities. If a program uses a part of the user-provided string as code execution, the program may lose control over code execution.
Copy codeThe Code is 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.