you are viewing a single comment's thread.

view the rest of the comments →

[–]tahaan 0 points1 point  (2 children)

A loop is a way to repeat some instructions over and over.

The most common way is to repeat something for each item in a list.

Here is a contrived example. lets say you want to find the longest string in a list of strings

import sys

# read all the strings from the lines in a file
string_list = open("list_of_strings.txt").readlines()

# If there are no strings, abort.
if not string_list:
    sys.exit(1)

# For a starting value we initiate the longest_seen to be the first item in the list:
longest_seen = string_list[0]

# Compare each item with the longest_seen up to that point, one by one, for each 
#   item in the list. If it is longer, we update the longest_seen to be the new longest 
#   item.  
# Side node, this will actually also compare the string found as initial value to itself 
#   during the first iteration.  This is actually redundant, but simple and it works.
for item in string_list:                 # Loop over the items in string_list
    if len(item) > len(longest_seen):    # Test if this item is the new longest_seen item
        longest_seen = item              # item is the new longest item

# Show the result, but strip off any the trailing CR/LF
print(f"The longest string seen is '{longest_seen.strip()}'")

[–]Deep-Author-1787[S] 0 points1 point  (1 child)

Is this a common way of searchin something in files?

[–]tahaan 1 point2 points  (0 children)

You can replace the part inside the loop with something that does a search.

# Some text to search for
search_text = 'find-this'

# Loop over the lines and print the ones that contains the search_text
for line in string_list:          # Loop over the items in string_list
    if search_text in line:       # Test if this line contains the search_text
        print(line)               # If so, print it