Python for Loop

Source: Internet
Author: User

A Python for loop can traverse any sequence of items, such as a list or a string.

The syntax structure for the For loop is as follows:

  For Iterating_var in sequence:

  Statements(s)

The simplest form is as follows, looping 10 times.

1  for  in range:2     print("loop:", i)

Output to

1 loop:0 2 loop:1 3 loop:2 4 loop:3 5 loop:4 6 loop:5 7 Loo P:6 8 loop:7 9 loop:8 loop:9

Range () function

function Prototypes : Range (start, end, scan):

parameter meaning : Start: Count starts from start. The default is starting from 0. For example, range (5) is equivalent to range (0, 5);

End: The technology ends with end, but does not include end. For example: Range (0, 5) is [0, 1, 2, 3, 4] No 5

Scan: The distance between each jump, the default is 1, is called the "step". Example: Range (0, 5) is equivalent to range (0, 5, 1)

1 # represented from 1 to 5 (not including 5) 2 [1, 2, 3, 4]3# represents from 1 to 5, Interval 2 (not 5)4 [1, 3]5 # represented from 0 to 5 (not including 5) 6 [0, 1, 2, 3, 4]

The Len () function is used to calculate the number of elements.

For loop

For loop in can also be followed by a lot of things. Can be followed by a string, tuple, list.

1  forLetterinch 'Python':#First Instance2    Print('Current Letter:', letter)3 4Fruits = ['Banana','Apple','Mango']5  forFruitinchFruits#a second instance6    Print('Current Letter:', fruit)

Output

1 Current Letter: P 2 Current Letter: Y 3 Current Letter: T 4 Current Letter: H 5 Current Letter: o 6 Current letter: N 7 Current Letter: Banana 8 Current Letter: Apple 9 Current Letter: Mango

Continue, break, and else usages are the same as while.

 

 

Python for Loop

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.