Python 6 loop

Source: Internet
Author: User

Cycle

To calculate 1+2+3, we can write an expression directly:

>>> 1 + 2 + 36

To calculate 1+2+3+...+10, you can barely write it.

However, to calculate 1+2+3+...+10000, it is impossible to write the expression directly.

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

There are two types of Python loops, one is the for...in loop, and each of the elements in the list or tuple is iterated in turn to see an example :

names = [‘Michael‘, ‘Bob‘, ‘Tracy‘]for name in names: print(name)

Executing this code will print names each element in turn:

MichaelBobTracy

So the for x in ...        loop is to take each element into the variable and x then execute the indented block of the statement .

For example, if we want to calculate the sum of 1-10 integers, we can use a sum variable to accumulate:

0for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: sum = sum + xprint(sum)

If you want to calculate the sum of 1-100 integers, writing from 1 to 100 is a bit difficult, but fortunately Python provides a range() function that generates a sequence of integers that list() can then be converted to a list by a function.

For example, range(5) the generated sequence is an integer starting from 0 and less than 5:

list(range(5))[0, 1, 2, 3, 4]

range(101)You can generate an integer sequence of 0-100, which is calculated as follows:

0for x in range(101):    sum = sum + xprint(sum)

Please run the above code on your own, to see if the result is 5050 of the students ' mental arithmetic.

The second loop is the while loop, which, as long as the condition is satisfied, loops continuously, exiting the loop when the condition is not satisfied. For example, we want to calculate the sum of all the odd numbers within 100, which can be implemented with a while loop:

0n = 99while n > 0:    sum = sum + n    n = n - 2print(sum)

The loop internal variable is n continuously self-reducing until -1 it becomes, and the while condition is no longer satisfied, and the loop exits.

Practice

Please use the loop to print out each name in the list in turn Hello, xxx! :

Break

In a loop, the break statement can exit the loop prematurely . For example, a number that would have been circulating to print 1~100:

<= 100:    print(n) n = n + 1print(‘END‘)

The above code can print out the 1~100.

If you want to end the loop prematurely, you can use the break statement:

1while n <= 100:    if n > 10: # 当n = 11时,条件满足,执行break语句 break # break语句会结束当前循环 print(n) n = n + 1print(‘END‘)

Execute the above code can see, after printing out 1~10, immediately after printing END , the program ends.!!!!! Because this print does not indent ah so he is not part of the loop body in the while statement block

breakthe visible effect is to end the loop prematurely.

Continue

In the loop process, You can also continue skip the current loop and start the next loop directly through the statement.

< 10:    n = n + 1 print(n)

The above program can print out the 1~10. However, if we want to print only odd numbers, we can continue skip some loops with a statement:

0while n < 10:    n = n + 1    if n % 2 == 0: # 如果n是偶数,执行continue语句 continue # continue语句会直接继续下一轮循环,后续的print()语句不会执行 print(n)

Execute the above code to see that the print is no longer 1~10, but 1,3,5,7,9.

The visible continue effect is to end the cycle in advance and start the next cycle directly.

Summary

Loops are an effective way to make a computer do repetitive tasks.

breakThe statement can exit the loop directly during the loop, and the continue statement can end the cycle in advance and start the next cycle directly. These two statements usually have to be used in conjunction with the if statement.

pay special attention to not abusing break and continue statements. breakand continue will cause the code to perform logical fork too much, error prone. Most loops do not need to use break and continue statements,

The above two examples can be modified by rewriting the loop condition or modifying the loop logic, removing break and the continue statement.

Sometimes, if the code is written with a problem, It will cause the program to fall into a "dead loop", that is, forever loop. You can then either Ctrl+C exit the program or force the end of the Python process.

Please try to write a dead loop program.

Reference source

do_for.py

do_while.py

Python 6 loop

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.