Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python - For Loops



Thefor loop in Python provides the ability to loop over the items of any sequence, such as a list, tuple or a string. It performs the same action on each item of the sequence. This loop starts with thefor keyword, followed by a variable that represents the current item in the sequence. Thein keyword links the variable to the sequence you want to iterate over. Acolon (:) is used at the end of the loop header, and the indented block of code beneath it is executed once for each item in the sequence.

Syntax of Python for Loop

for iterating_var in sequence:   statement(s)

Here, theiterating_var is a variable to which the value of each sequence item will be assigned during each iteration.Statements represents the block of code that you want to execute repeatedly.

Before the loop starts, the sequence is evaluated. If it's a list, the expression list (if any) is evaluated first. Then, the first item (at index 0) in the sequence is assigned toiterating_var variable.

During each iteration, the block of statements is executed with the current value ofiterating_var. After that, the next item in the sequence is assigned toiterating_var, and the loop continues until the entire sequence is exhausted.

Flowchart of Python for Loop

The following flow diagram illustrates the working offor loop −

forloop

Python for Loop with Strings

Astring is a sequence ofUnicode letters, each having a positional index. Since, it is a sequence, you can iterate over its characters using the for loop.

Example

The following example compares each character and displays if it is not a vowel ('a', 'e', 'i', 'o', 'u').

zen = '''Beautiful is better than ugly.Explicit is better than implicit.Simple is better than complex.Complex is better than complicated.'''for char in zen:   if char not in 'aeiou':      print (char, end='')

On executing, this code will produce the following output −

Btfl s bttr thn gly.Explct s bttr thn mplct.Smpl s bttr thn cmplx.Cmplx s bttr thn cmplctd.

Python for Loop with Tuples

Python's tuple object is also an indexed sequence, and hence you can traverse its items with afor loop.

Example

In the following example, the for loop traverses a tuple containing integers and returns the total of all numbers.

numbers = (34,54,67,21,78,97,45,44,80,19)total = 0for num in numbers:   total += numprint ("Total =", total)

On running this code, it will produce the following output −

Total = 539

Python for Loop with Lists

Python's list object is also an indexed sequence, and hence you can iterate over its items using afor loop.

Example

In the following example, the for loop traverses a list containing integers and prints only those which are divisible by 2.

numbers = [34,54,67,21,78,97,45,44,80,19]total = 0for num in numbers:   if num%2 == 0:      print (num)

When you execute this code, it will show the following result −

3454784480

Python for Loop with Range Objects

Python's built-inrange() function returns an iterator object that streams a sequence of numbers. This object contains integers from start to stop, separated by step parameter. You can run a for loop with range as well.

Syntax

The range() function has the following syntax −

range(start, stop, step)

Where,

  • Start − Starting value of the range. Optional. Default is 0

  • Stop − The range goes upto stop-1

  • Step − Integers in the range increment by the step value. Option, default is 1.

Example

In this example, we will see the use of range with for loop.

for num in range(5):   print (num, end=' ')print()for num in range(10, 20):   print (num, end=' ')print()for num in range(1, 10, 2):   print (num, end=' ')

When you run the above code, it will produce the following output −

0 1 2 3 410 11 12 13 14 15 16 17 18 191 3 5 7 9

Python for Loop with Dictionaries

Unlike a list, tuple or a string,dictionary data type in Python is not a sequence, as the items do not have a positional index. However, traversing a dictionary is still possible with the for loop.

Example

Running a simple for loop over the dictionary object traverses the keys used in it.

numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}for x in numbers:   print (x)

On executing, this code will produce the followingoutput

10203040

Once we are able to get the key, its associated value can be easily accessed either by using square brackets operator or with theget() method.

Example

The following example illustrates the above mentioned approach.

numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}for x in numbers:   print (x,":",numbers[x])

It will produce the followingoutput

10 : Ten20 : Twenty30 : Thirty40 : Forty

The items(), keys() and values() methods of dict class return the view objects dict_items, dict_keys and dict_values respectively. These objects are iterators, and hence we can run a for loop over them.

Example

The dict_items object is a list of key-value tuples over which a for loop can be run as follows −

numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}for x in numbers.items():   print (x)

It will produce the followingoutput

(10, 'Ten')(20, 'Twenty')(30, 'Thirty')(40, 'Forty')

Using else Statement with For Loop

Python supports to have an else statement associated with a loop statement. However, theelse statement is executed when the loop has exhausted iterating the list.

Example

The following example illustrates the combination of an else statement with a for statement that searches for prime numbers from 10 to 20.

#For loop to iterate between 10 to 20for num in range(10, 20):     #For loop to iterate on the factors    for i in range(2,num):       #If statement to determine the first factor      if num%i == 0:               #To calculate the second factor         j=num/i                   print ("%d equals %d * %d" % (num,i,j))         #To move to the next number         break       else:                           print (num, "is a prime number")         break

When the above code is executed, it produces the following result −

10 equals 2 * 511 is a prime number12 equals 2 * 613 is a prime number14 equals 2 * 715 equals 3 * 516 equals 2 * 817 is a prime number18 equals 2 * 919 is a prime number
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp