Cheap VPS host selection
Provide server host evaluation information

Introduction to the use of for loop in python

In Python, The for loop is used to iterate through elements in iterable objects (such as lists, tuples, strings, etc.). Here are some common uses of the for loop:

Traversal list:

 numbers = [ one , two , three , four , five ] for num in numbers: print (num) #Export the elements in the list one by one

Traversal tuple:

 fruits = ( "apple" , "banana" , "orange" ) for fruit in fruits: print (fruit) #Output elements in tuples one by one

Traversal string:

 message = "Hello,  World! "
 for char in message: print (char) #Output the characters in the string one by one

Traversal dictionary:

 student_scores = { "Alice" : eighty-five , "Bob" : ninety-two , "Charlie" : seventy-eight } for name, score in student_scores.items(): print (name,  score) #Keys and values in the output dictionary

Use the range() function to traverse:

 for i in  range ( one , six ): print (i) #Output integers from 1 to 5

Filter by combining conditional statements:

 numbers = [ one , two , three , four , five ] for num in numbers: if num % two == zero : print (num) #Even number in output list

Combined with else clause:

 numbers = [ one , two , three , four , five ] for num in numbers: print (num) else : print ( "Loop finished." ) #Code block executed after the loop ends

These are some common uses of the for loop. The for loop can be used to easily traverse and operate the iterable objects, and can be combined with other statements and functions for more flexible control and processing as required.

Do not reprint without permission: Cheap VPS evaluation » Introduction to the use of for loop in python