Use 6 examples and 8 pieces of code to explain the for loop in Python in detail

Table of contents

foreword

 01 For loop using tryexcept

02 Exponential operation

03 Nested Loops

04 Use the split() function in a for loop

1. Use the split() function to do word comparison

2. Use the split() function to print the text in the specified format

3. Use the split() function to print fixed-width text

4. Use the split() function to compare text strings

05 Use the basic for loop to display the characters in the string

06 join() function


foreword

Python supports for loops, which have a slightly different syntax than other languages ​​such as JavaScript or Java. The following code block demonstrates how to use a for loop in Python to iterate over the elements of a list:

The above code segment prints three letters on separate lines. You can limit the output to be displayed on the same line by adding a comma "," after the print statement (if you specify a lot of characters to print, it will "wrap"), the code is as follows:

You can use the above form of code when you want to display the content of the text on one line instead of multiple lines. Python also provides the built-in function reversed(), which reverses the direction of the loop, for example: 

Note that the reverse traversal function is only valid when the size of the object is determined, or the object implements the _reversed_() method.

 01 For loop using tryexcept

Listing 1's StringToNums.py illustrates how to sum a set of integers converted from strings.

  • Listing 1 StringToNums.py

line = '1 2 3 4 10e abc'
sum  = 0
invalidStr = ""

print('String of numbers:',line)

for str in line.split(" "):
  try:
    sum = sum + eval(str)
  except:
    invalidStr = invalidStr + str + ' '

print('sum:', sum)
if(invalidStr != ""):
  print('Invalid strings:',invalidStr)
else:
  print('All substrings are valid numbers')

Listing 1 first initializes the variables line, sum, and invalidStr, and then displays the contents of line. Next, the content in the line is divided into words, and then the values ​​of the words are added to the variable sum one by one through the try code block. If an exception occurs, the contents of the current str are appended to the variable invalidStr.

When the loop finishes executing, Listing 1 prints the sum of the numeric words, followed by the non-numeric words. Its output looks like this:

02 Exponential operation

Listing 2's Nth_exponet.py illustrates how to calculate the power of a set of integers.

  • Listing 2 Nth_exponet.py

maxPower = 4
maxCount = 4

def pwr(num):
  prod = 1
  for n in range(1,maxPower+1):
    prod = prod*num
    print(num,'to the power',n, 'equals',prod)
  print('-----------')

for num in range(1,maxCount+1):
    pwr(num)

Listing 2 has a pwr() function that takes a numeric value as an argument. The loop in this function can print out the 1 to nth power of the parameter, and the value range of n is between 1 and maxCount+1.

The second part of the code calls the pwr() function from 1 to the value of maxCount+1 through a for loop. Its output looks like this:

03 Nested Loops

Listing 3's Triangular1.py illustrates how to print a line of consecutive integers (starting at 1), where the length of each line is 1 greater than the previous line.

  • Listing 3 Triangular1.py

max = 8
for x in range(1,max+1):
  for y in range(1,x+1):
    print(y,'', end='')
  print() 

Listing 3 first initializes the max variable to 8, and then executes a loop through the variable x from 1 to max+1. The inner loop has a loop variable y with values ​​from 1 to x+1, and prints the value of y. Its output looks like this:

04 Use the split() function in a for loop

Python supports various convenient functions related to string manipulation, including split() function and join() function. The split() function is useful when you need to tokenize (i.e. "split") a line of text into words, and then use a for loop to iterate over those words.

The join() function is the opposite of the split() function in that it "joins" two or more words into a single line. By using the split() function, you can easily remove extra spaces in the sentence, and then call the join() function so that there is only one space between each word in the line of text.

1. Use the split() function to do word comparison

Compare2.py in Listing 4 illustrates how each word in a text string is compared to another word via the split() function.

  • Listing 4 Compare2.py

x = 'This is a string that contains abc and Abc'
y = 'abc'
identical = 0
casematch = 0

for w in x.split():
  if(w == y):
    identical = identical + 1
  elif (w.lower() == y.lower()):
    casematch = casematch + 1

if(identical > 0):
 print('found identical matches:', identical)

if(casematch > 0):
 print('found case matches:', casematch)

if(casematch == 0 and identical == 0):
 print('no matches found')

Listing 4 compares each word in the string x with the word abc via the split() function. If the word matches exactly, increment the identical variable by 1; otherwise, try a case-insensitive comparison, and increment the casematch variable if it matches.

The output from Listing 4 looks like this:

2. Use the split() function to print the text in the specified format

FixedColumnCount1.py in Listing 5 illustrates how to print a set of fixed-width strings.

  • Listing 5 FixedColumnCount1.py

import string

wordCount = 0
str1 = 'this is a string with a set of words in it'

print('Left-justified strings:')
print('-----------------------')
for w in str1.split():
   print('%-10s' % w)
   wordCount = wordCount + 1
   if(wordCount % 2 == 0):
      print("")
print("\n")

print('Right-justified strings:') 
print('------------------------') 

wordCount = 0
for w in str1.split():
   print('%10s' % w)
   wordCount = wordCount + 1
   if(wordCount % 2 == 0):
      print()

Listing 5 first initializes the variables wordCount and str1, and then executes two for loops. The first for loop prints each word of str1 with left alignment, and the second for loop prints each word of str1 with right alignment. In each loop, when wordCount is an even number, a newline is output, so that a newline is printed after printing two consecutive words. The output from Listing 5 looks like this:

3. Use the split() function to print fixed-width text

Listing 6's FixedColumnWidth1.py illustrates how to print fixed-width text.

  • Listing 6 FixedColumnWidth1.py

import string

left = 0
right = 0
columnWidth = 8

str1 = 'this is a string with a set of words in it and it will be split into a fixed column width'
strLen = len(str1)

print('Left-justified column:') 
print('----------------------') 
rowCount = int(strLen/columnWidth)

for i in range(0,rowCount):
   left  = i*columnWidth
   right = (i+1)*columnWidth-1
   word  = str1[left:right]
   print("%-10s" % word)

# check for a 'partial row'
if(rowCount*columnWidth < strLen):
   left  = rowCount*columnWidth-1;
   right = strLen
   word  = str1[left:right]
   print("%-10s" % word)

Listing 6 initializes the integer variable columnWidth and the string type variable str1. The variable strLen is the length of str1, and the variable rowCount is the value of strLen divided by columnWidth. Then print rowCount lines by loop, each line contains columnWidth characters. The last part of the code outputs all "remaining" characters. The output from Listing 6 looks like this:

 

4. Use the split() function to compare text strings

Listing 7's CompareStrings1.py illustrates how to determine whether a word in one text string appears in another text string.

  • Listing 7 CompareStrings1.py

text1 = 'a b c d'
text2 = 'a b c e d'

if(text2.find(text1) >= 0):
  print('text1 is a substring of text2')
else:
  print('text1 is not a substring of text2')

subStr = True
for w in text1.split():
  if(text2.find(w) == -1):
    subStr = False
    break

if(subStr == True):
  print('Every word in text1 is a word in text2')
else:
  print('Not every word in text1 is a word in text2')

Listing 7 first initializes two string variables text1 and text2, and then judges whether the string text2 contains text1 through conditional logic (and outputs the corresponding print information).

The second half of Listing 7 loops through each word in the string text1 and checks whether it appears in text2. If it is found that there is a matching failure, set the variable subStr to False, and jump out of the loop through the break statement, and terminate the execution of the for loop in advance. Finally, print the corresponding information according to the value of the variable subStr. The output from Listing 7 is as follows:

 

05 Use the basic for loop to display the characters in the string

Listing 8's StringChars1.py illustrates how to print the characters in a text string.

  • Listing 8 StringChars1.py

text = 'abcdef'
for ch in text:
   print('char:',ch,'ord value:',ord(ch))
print

The code in Listing 8 simply and directly traverses the string text through a for loop and prints each character and its ord value (ASCII code). The output from Listing 8 looks like this:

06 join() function

Another way to remove extra spaces is to use the join() function, the code example is as follows:

The split() function "splits" a text string into a series of words, while removing redundant spaces. Next the join() function joins the words in the string text1 using a space as a delimiter. The last part of the above code performs the same concatenation operation using the string XYZ replacing spaces as delimiters. The output of the above code is as follows:

Guess you like

Origin blog.csdn.net/weixin_69333592/article/details/128315618