Python3 the seventh chapter-Loop statement

Source: Internet
Author: User

In order for the computer to calculate thousands of repetitions, we need to loop the statements.

The looping statements in Python have

    • For
    • While

The execution of a loop statement, such as:

While loop

The general form of a while statement in Python:

 while Judging Condition:    statement

The execution of the above syntax is:

When the condition is True, The statement that executes the statement block 1

Statement that executes statement block 2 when the condition is False

Let's do one thing with the while: Calculate the sum of all 1-100 numbers:

n =+ = 1 while counter <= N:    = sum + counter    + = 1  Print( "" and "sum of") :

The above code, output:

1 to  + the sum  is: 5050

have found, with the program to do some things, or more worry, the future of the world is "machine", "intelligent", pulled a bit far. If our loop statement is constant to true, what will happen

 while 2 > 1:  #  expression is always true    name = input (' Please enter your name:' )  print    ("", name)print ("  Good bye! ")

The above code, output:

Please enter your name: Roy Hello  Roy Please enter your name:

You should also find that the program will always require you to enter a name, the program in an infinite loop (also known as the Dead Loop).

While can also be used with else, the statement block of else is executed when the condition is false:

 while Judging Condition:    statement 1else:    statement 2

code example:

0
5:
Print (count"less than 5")
1
Else
Print (count"greater than or equal to 5")

The above code, output:

0 less than or less than the sum of less than the number of less than  5

For loop

Basic syntax:

 for inch sequence:    statement block

The execution of the above syntax is:

Takes an element from the sequence sequentially, assigns a value to the variable , and executes the statement block until all the elements of the sequence are assigned values. This is similar to foreach in other languages.

code example:

languages = ["C""+C" "Perl"  "Python"] for in languages:    Print (x)

The above code, output:

CC+ +Perlpython

For can also be used with else, when all values in the sequence have been assigned once, the statement block of else is executed, with the following syntax:

 for inch sequence:    statement block 1else:    statement block 2

Instance

 languages = [ " c   ", "  c++   ", "  perl   ", "  python   " ]  for  x in   languages:  print   (x)  else  :  print  ( "  this is else   ") 

The above code, output:

CC+ +Perlpython here is else

Range () function

If you need to traverse a sequence of numbers, you can use the built-in range () function. It generates a sequence of numbers, such as:

 for  in range (5):    print(i)

The above code, output:

01234

You can also use range to specify the value of the interval:

 for  in range (5, 9):    print(i)

The above code output:

5678

You can also make range start with a specified number and specify a different increment (even negative, sometimes referred to as a "step"):

 for  in range (0, 3):    print(i)

The above code, output:

0369

To have a negative number:

 for  in range ( -1, -10,-3):    print(i)

The above code, output:

-1-4-7



Break
In a loop, the break statement can exit the loop prematurely. For example, you would have to cycle through the number of the numbers:

n = 1 while n <= 5:    print(n)    = n + 1print('END  ')

The above code, output:

12345END

If we want to quit the loop when n=3, we can do this:

n = 1 while n <= 5:    if n = =3        :break    print(n) c10/>= n + 1print('END')

The above code, output:

END

The break statement can jump out of a for and while loop body. If you terminate from a for or while loop, any corresponding loop else blocks will not execute. Examples are as follows:

n = 1 while n <= 5:    if n = =3        :break    print(n) c10/>= n + 1else:    print('else')     Print ('END')

The above code, output:

END

continue
During a loop, you can also skip the remaining statements in the current loop block through the continue statement, and then proceed to the next round of loops. The same would have been to cycle through the number of the n=3, but I do not want to print when the:

1 n = 1 2  3 while n <= 5:  4      5     if n = = 3:  6         n = n + 1 7         continue  8     print (n) 9     n = n + 1print('END')

The above code, output:

1245END

Think about what happens if you delete the 6th line of code n = n + 1 and why?

The continue only terminates the current loop and does not terminate the loop, so the else statement will continue to execute:

n = 1 while n <= 5:    if n = =3        := n + 1        continue    print< /c9>(n)    = n + 1else:    print('else  ')print('END')

The above code, output:

1245Elseend

Note:

    • The break statement can exit the loop directly during the loop, while the continue statement can end the cycle in advance and start the next cycle directly. These two statements usually have to be used with the IF statement.
    • Be especially careful not to misuse break and continue statements. Break and continue can cause too many logical forks for code execution and error-prone. Most loops do not need to use break and continue statements. In the example above, you can rewrite the loop condition or modify the loop logic, remove the break and continue statements, and try to rewrite them yourself .

Thinking: How to print the odd number of 1~100.

Pass Statement

Pass is an empty statement in order to maintain the integrity of the program structure. Pass does not do anything, generally used as a placeholder statement, the following example:

 while True:     Pass

Then look at the following code:

n = 1 while n <= 5:    if n = =3        :pass        print('  Execute pass block ')    print(n)    = n + 1print( ' END ')

The above code, output:

Pass  block 345END

Python3 the seventh chapter-Loop statement

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.