Python Exercise 24

Source: Internet
Author: User

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

Grammar:

The syntax format for the For loop is as follows:

For in sequence: statements(s)      

#!/usr/bin/python#-*-Coding:utf-8-*-ForLetterInch ' Python ': # The first instance of print  ' current letter: ' , letterfruits = [ ' banana ' Span class= "pun" >,  ' Apple ' ,  ' Mango ' ]for fruit Span class= "KWD" >in Fruits: # second instance  print  ' current letter: '  Fruitprint  "good bye!"     
Iterating through the sequence index

Another way to perform a loop is through an index, as in the following example:

#!/usr/bin/python#-*-Coding:utf-8-*-fruits = [ ' banana ' Span class= "pun" >,  ' Apple ' ,  ' Mango ' ]for index Span class= "KWD" >in Range (len ( fruits print  current fruit: ' , Fruits[index]print  "good bye!"     

In the above example we used the built-in function Len () and range (), and the function Len () returns the length of the list, that is, the number of elements. Range returns the number of a sequence.

Looping with Else statements

In Python, for ... else means that the statement in for is no different from normal, while the statement in else is executed when the loop is executed normally (that is, for not breaking out by break), while ... else is the same.

The following example:

#!/usr/bin/python#-*-Coding:utf-8-*-ForNumInchRange(10,20): # Iterations of numbers between 10 and 20 ForIInchRange(2,Num): # based on factor iterations IfNum%I== 0: # Determine the first factor J=num/i # calculates the second factor  print  %  (num ,i,j)  break # jump out of current loop  else: # loop else part  print Num,  ' is a prime number '     

Python Exercise 24

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.