-for cycle of Python learning notes

Source: Internet
Author: User

The For loop requires a pre-set number of cycles (n), and then executes the statement that is subordinate to the for (n) times.

The basic structure is

For element in sequence:
Statement

For example, we edit a file called fordemo.py.

For a in [3,4.4, ' Life ']:
Print a
This loop takes one element at a time from the table [3,4.4, ' life '] (recall: The table is a sequence), assigns the element to a, and then executes the action (print) that belongs to the for.

Introduces a new Python function, range (), to help you create a table.


IDX = Range (5)
Print idx
You can see that the IDX is [0,1,2,3,4]


The function is to create a new table. The elements of this table are integers, starting with 0, the next element is 1 larger than the previous one, until the upper bound is written in the function (excluding the upper bound itself)


(About range (), there is a lot of usage, interested can be consulted, Python 3, range () usage changes, see comment area)

Example

For a in range (10):
Print a**2

While loop

The use of the while IS

While condition:
Statement
The while loop executes the statement that is subordinate to it until the condition is False (false)

Example


While I < 10:
Print I
i = i + 1


Interrupt loop


Continue # in an execution of a loop, if you encounter continue, skip this execution and proceed to the next operation


Break # Stops execution of the entire loop


For I in range (10):
if i = = 2:
Continue
Print I



When the loop executes to I = 2, the If condition is set, the continue is triggered, the execution is skipped (no print is executed), and the next execution is continued (i = 3).


For I in range (10):
if i = = 2:
Break
Print I
When the loop executes to I = 2, the If condition is set, the break is triggered, and the entire loop stops.



Summarize

Range ()

For element in sequence:

While condition:

Continue

Break

-for cycle of Python learning notes

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.