Conditions and loops in the Python entry-level article, and loops in the python entry-level article

Source: Internet
Author: User

Conditions and loops in the Python entry-level article, and loops in the python entry-level article

1. if statement

The if clause in Python looks familiar. It consists of three parts: the keyword itself, a condition expression used to determine whether the result is true or false, and a code block executed when the expression is true or not.
The syntax of the if statement is as follows:
If expression:
Expr_true_suite
The expr_true_suite code block of the if statement is executed only when the Boolean value of the result of the conditional expression is true. Otherwise, the statement following the code block is executed.

(1) multiple conditional expressions

A single if statement can use the boolean operators and, or, and not to implement multiple or negative conditions.

Copy codeThe Code is as follows:
If not warn and (system_load> = 10 ):
Print "WARNING: losing resources"
Warn + = 1

(2) code block of a single statement

If the code block of a composite Statement (such as the if clause, while, or for loop) contains only one line of code, it can be written on the same line as the preceding statement:
If make_hard_copy: send_data_to_printer ()

Although it may be convenient, it will make the code more difficult to read, so we recommend that you move this line of code to the next line and indent it properly.

2. else statement

Python provides the else statement used with the if statement. if the Boolean value of the conditional expression of the if statement is false, the program will execute the code after the else statement. you can even guess its syntax:

Copy codeThe Code is as follows:
If expression:
Expr_true_suite
Else:
Expr_false_suite

If passwd = user. passwd:
Ret_str = "password accepted"
Id = user. id valid = True
Else:
Ret_str = "invalid password entered... try again! "
Valid = False

3. elif (else-if) Statement

Elif is an else-if statement of Python. It checks whether multiple expressions are true and executes the code in a specific code block when the expressions are true. like else, The elif statement is optional. However, the difference is that the if statement can have at most one else statement, but can have any number of elif statements.

Copy codeThe Code is as follows:
If expression1:
Expr1_true_suite
Elif expression2:
Expr2_true_suite
Elif expressionN:
ExprN_true_suite
Else:
None_of_the_above_suite

4. conditional expressions (that is, "ternary operators ")

The syntax for Python 2.5 Integration is determined to be: X if C else Y.

Copy codeThe Code is as follows:
>>> X, y = 4, 3
>>> Smaller = x if x <y else y
>>> Smaller
3

5. while statement

While in Python is the first loop statement we have encountered in this chapter. in fact, it is a conditional loop statement. compared with the if statement, if the condition after if is true, a corresponding code block is executed. while the code block in while will be executed cyclically until the loop condition is no longer true.
The syntax of the while loop is as follows:

Copy codeThe Code is as follows:
While expression:
Suite_to_repeat

>>> X = 1
>>> While x <= 100:
Print x
X + = 10

6. for statement

Another Loop Mechanism provided by Python is the for statement. it provides the most powerful loop structure in Python. it can traverse sequence members and can be used in list parsing and generator expressions. It automatically calls the next () method of the iterator, capture the StopIteration exception and end the loop (all this happens internally ). unlike for statements in traditional languages, for in Python is more like a foreach loop in shell or scripting.

The for loop accesses all elements in an iteratable object (such as a sequence or iterator) and ends the loop after all entries are processed. Its syntax is as follows:

Copy codeThe Code is as follows:
For iter_var in iterable:
Suite_to_repeat

1. Used for sequence type

Copy codeThe Code is as follows:
>>> For c in 'names ':
Print 'current letter: ', c

Current letter: n
Current letter:
Current letter: m
Current letter: e
Current letter: s

There are three basic methods for iterative sequences:

1. Iteration through sequence items:

Copy codeThe Code is as follows:
>>> Namelists = ['henry', 'john', 'steven ']
>>> For eachName in namelists:
Print eachName, 'lim'

Henry Lim
John Lim
Steven Lim

2. Sequential index iteration:

Copy codeThe Code is as follows:
>>> Namelists = ['henry', 'john', 'steven ']
>>> For nameindex in range (len (namelists )):
Print 'Liu, ', namelists [nameindex]

Liu, henry
Liu, john
Liu, steven

3. Usage and index iteration:

The Best of both worlds is to use the built-in enumerate () function, which is new to Python 2.3. The Code is as follows:

Copy codeThe Code is as follows:
>>> Namelists = ['henry', 'john', 'steven ']
>>> For I, eachLee in enumerate (namelists ):
Print "% d % s Lee" % (I + 1, eachLee)

1 henry Lee
2 john Lee
3 steven Lee

2. Used for iterator type

The iterator object has a next () method, and the next entry is returned after the method is called. after all entries are iterated, The iterator raises a StopIteration exception to tell the program that the loop ends. the for statement calls next () internally and captures exceptions.

3. range () built-in functions

The built-in function range () can convert a for loop similar to foreach into a more familiar statement.

Python provides two different methods to call range (). The complete syntax requires two or three Integer Parameters:
Range (start, end, step = 1)
Range () will return a list containing all k. Here start <= k <end, from start to end, k increments step each time. step cannot be zero, otherwise an error will occur.

Copy codeThe Code is as follows:
>>> Range (2, 19, 3)
[2, 5, 8, 11, 14, 17]

If only two parameters are specified, and step is omitted, the default value is 1.

Copy codeThe Code is as follows:
>>> Range (3, 7)
[3, 4, 5, 6]

Range () has two simple syntax formats:
Range (end)
Range (start, end)

4. xrange () built-in functions

Xrange () is similar to range (). However, when you have a large range list, xrange () may be more suitable because it does not create a full copy of the list in the memory. it is used only in the for loop, and it does not make sense to use it outside the for loop. Similarly, you can think that it has a much higher performance than range () because it does not generate the entire list.

5. Sequence-related built-in functions

Sorted (), reversed (), enumerate (), zip ()

Sorted () and zip () return a sequence (list), while the other two functions reversed () and enumerate () return the iterator (similar sequence)

7. break statement

The break statement in Python can end the current loop and jump to the next statement, similar to the traditional break in C. it is often used when an external condition is triggered (usually through the if statement check) and needs to exit from the loop immediately. The break statement can be used in the while and for loops.

8. continue statement

The continue statement in Python is no different from the traditional continue statement in other advanced languages. it can be used in the while and for loops. while loops are conditional, while for loops are iterative. Therefore, continue must meet certain prerequisites before starting the next loop. Otherwise, the loop ends normally.

Copy codeThe Code is as follows:
Valid = False
Count = 3
While count> 0:
Input = raw_input ("enter password ")
# Check for valid passwd
For eachPasswd in passwdList:
If input = eachPasswd:
Valid = True
Break
If not valid: # (or valid = 0)
Print "invalid input"
Count-= 1
Continue
Else:
Break

In this example, while, for, if, break, and continue are used to verify user input. the user has three chances to enter the correct password. If the password fails, the valid variable will remain a Boolean false (0), and then we can take necessary actions to prevent the user from guessing the password.

9. pass statement

Python provides a pass statement, which does not do anything-NOP, (No OPeration, No OPeration). We borrow this concept from the assembly language. pass can also be used as a tips in development to mark the code to be completed later, for example:

Copy codeThe Code is as follows:
Def foo_func ():
Pass
# Or
If user_choice = 'do _ calc ':
Pass else:
Pass

Such a code structure is useful in development and debugging, because you may need to set the structure before writing the code, but you do not want it to interfere with other completed code. it is a good idea to put a pass when you don't need it to do anything.

10. iterator and iter () Functions

An iterator is an object with a next () method, rather than counting through indexes. when you or a Loop Mechanism (such as a for statement) needs the next item, you can obtain it by calling the next () method of the iterator. after all entries are retrieved, A StopIteration exception is thrown. This does not indicate an error. It only tells the external caller that the iteration is complete.

Restriction: you cannot move backward, return to the start, or copy an iterator.

The reversed () built-in function returns an iterator for reverse access. The enumerate () built-in function also returns the iterator. The other two new built-in functions, any () and all ()

Python also provides an entire itertools module, which contains various useful iterators.

Copy codeThe Code is as follows:
>>> Tupe = (12, '2', 45.45)
>>> I = iter (tupe)
>>> I. next ()
12
>>> I. next ()
'2'
>>> I. next ()
45.45
>>> I. next ()
Traceback (most recent call last ):
File "<pyshell #72>", line 1, in <module>
I. next ()
StopIteration

Create iterator

Call iter () on an object to get its iterator. Its syntax is as follows:
Iter (obj)
Iter (func, sentinel)
If you pass a parameter to iter (), it will check whether you pass a sequence. If yes, It is very simple: Always iterate from 0 to the end of the sequence based on the index. another method for creating an iterator is to use a class. A class that implements the _ iter _ () and next () methods can be used as an iterator.

If two parameters are passed to iter (), it repeatedly calls func until the next value of the iterator is sentinel.

11. import one thing as another

When importing functions from a module, you can use

Copy codeThe Code is as follows:
Import somemodule

Or
Copy codeThe Code is as follows:
From somemodule import somefunction

Or
Copy codeThe Code is as follows:
From somemodule import somefunction, anotherfunction, yetanotherfunction

Or
Copy codeThe Code is as follows:
From somemodule import *

If both modules have open functions, you only need to use the first method to import them, and then use the functions as follows:
Copy codeThe Code is as follows:
Module1.open (...)

Module2.open (...)

Alternatively, you can add an as clause at the end of the statement to give a name after the clause, or provide an alias for the entire module:

Copy codeThe Code is as follows:
>>> 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

What we do here is sequential unpacking-Unlocking the sequences of multiple values and placing them in the sequence of variables. A more vivid expression is as follows:

Copy codeThe Code is as follows:
>>> Values = 1, 2, 3
>>> Values
(1, 2, 3)
>>> X, y, z = values
>>> X
1
>>> Y
2
>>> Z
3


2-9 python exercises: raw

While 0 <n <100:
.. N = int (raw_input ('Please input a number :'))
.. Print 'wrong number .'
Point represents a space. Baidu knows that it will delete the space that it considers "useless.

Python looping in the list

In the previous iteration, list_name is obtained, and the value of name is obtained in the variable I.

This is similar later, but the index value is retrieved into the variable I in each iteration.

There is no big difference in use. We don't need to use the index in the previous case, but we will use the index later. The other ones actually look at my preferences.

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.