0% found this document useful (0 votes)
8 views14 pages

Python For Loops Explained

The document discusses for loops in Python. A for loop iterates over each item in a collection like a list, tuple, or string. The document provides an example of using a for loop to print each name in a list of linguists on a separate line. It also discusses using for loops with the range() function to iterate over a range of numbers, and using zip() to loop through multiple lists simultaneously. The document concludes with examples of using for loops to read and write to files.

Uploaded by

shani
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views14 pages

Python For Loops Explained

The document discusses for loops in Python. A for loop iterates over each item in a collection like a list, tuple, or string. The document provides an example of using a for loop to print each name in a list of linguists on a separate line. It also discusses using for loops with the range() function to iterate over a range of numbers, and using zip() to loop through multiple lists simultaneously. The document concludes with examples of using for loops to read and write to files.

Uploaded by

shani
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

For Loops

42
Motivating problem

 Given the following list


 >>> linguists = [“Amanda”, “Claire”, “Holly”, “Luis”,
“Nick”, “Sophia”]

 How do I print each name on a separate


line?
 >>> print linguists[0] + ‘\n’
 >>> print linguists[1] + ‘\n’
 >>> print linguists[2] + ‘\n’
 >>> print linguists[3] + ‘\n’
 >>> print linguists[4] + ‘\n’
 >>> print linguists[5] + ‘\n’

BASED on Martha Palmer’s python


LING 5200, 2006 43 slides
For Loops 1
 A for-loop steps through each of the items in a list, tuple,
string, or any other type of object which the language
considers an “iterator.”
for <item> in <collection>:
<statements>
 When <collection> is a list or a tuple, then the loop steps
through each element of the container.
 When <collection> is a string, then the loop steps through
each character of the string.
for someChar in “Hello World”:
print someChar

BASED on Martha Palmer’s python


LING 5200, 2006 44 slides
For Loops 2

 The <item> part of the for loop can also be more


complex than a single variable name.
 When the elements of a container <collection> are also
containers, then the <item> part of the for loop can
match the structure of the elements.
 This multiple assignment can make it easier to access
the individual parts of each element.

for (x, y) in [(‘a’,1), (‘b’,2), (‘c’,3), (‘d’,4)]:


print x

BASED on Martha Palmer’s python


LING 5200, 2006 45 slides
Solution to our problem

 >>> linguists = [“Amanda”, “Claire”, “Holly”, “Luis”,


“Nick”, “Sophia”]
 >>> for linguist in linguists:
print linguist

BASED on Martha Palmer’s python


LING 5200, 2006 46 slides
Exercise

 How do we take the sentence “Python is a


great text processing language” and print
one word on each line?

BASED on Martha Palmer’s python


LING 5200, 2006 47 slides
For loops and range() function

 Since we often want to range a variable over


some numbers, we can use the range() function
which gives us a list of numbers from 0 up to but
not including the number we pass to it.
 range(5) returns [0,1,2,3,4]
 So we could say:
for x in range(5):
print x

BASED on Martha Palmer’s python


LING 5200, 2006 48 slides
Exercise

 Suppose we have a list of integers


>>> numbers = [1, 2, 3, 4, 5, 6]

 What do we need to do add 5 to each number?


 What if we want to add 5 to only the second to
the fifth number?
 What if we want to add 5 to numbers with an
even-numbered offsets?

BASED on Martha Palmer’s python


LING 5200, 2006 49 slides
Loop through multiple lists at the same
time
>>> courses = [“syntax”, “phonoloy”,
“compling”]
>>> rooms = [‘232’, ‘303’, ‘534’]
>>> time = [‘2pm’, ‘10am’, ‘noon’]
>>> for (x,y,z) in zip(courses, rooms, time)
print x, y, z

BASED on Martha Palmer’s python


LING 5200, 2006 50 slides
files

51
Read from a file

#!/usr/local/bin/python

input_file = open(“[Link]”, “r”)


lines = input_file.readlines()
#use a for loop to access the lines
for line in lines
print line

Open a file for reading

BASED on Martha Palmer’s python


LING 5200, 2006 52 slides
Read a file from command line

What if you want to read a different file each time


you run your program?

#!/usr/local/bin/python
import sys
input_file = open([Link][1], “r”)
lines = input_file.readlines()
#use a for loop to access the lines
for line in lines:
print line

File from command line

BASED on Martha Palmer’s python


LING 5200, 2006 53 slides
Writing to a file
Open a file for reading

#!/usr/local/bin/python

input_file = open(“[Link]”, “r”)


output_file = open(“[Link]”, “w”)

lines = input_file.readlines()
#use a for loop to access the lines
for line in lines
output_file.write(line)
input_file.close() Open a file for writing
output_file.close()

BASED on Martha Palmer’s python


LING 5200, 2006 54 slides
Exercise

 Find a file, open it and print its each line


with its line number at the beginning

BASED on Martha Palmer’s python


LING 5200, 2006 55 slides

Common questions

Powered by AI

To read a file and print each line formatted, you would open the file, read its lines into a list, and iterate over this list using a for-loop. For instance: input_file = open('emails.txt', 'r'); lines = input_file.readlines(); for line in lines: print(line) reads and prints each line. If you want to add formatting, such as line numbers, you can enhance the loop: for i, line in enumerate(lines): print(f'{i+1}: {line.strip()}').

Using the enumerate() function with a for-loop is preferred when both index and element are needed during iteration. It provides a counter along with the value, simplifying access to the element's index in the list. For instance, if updating specific elements or printing their positions with results, as in for i, value in enumerate(list): print(i, value), this allows you to handle elements based on their position more explicitly than a regular for-loop .

The range() function in Python generates a sequence of numbers, which can be used in a for-loop to iterate over numeric ranges. For example, range(5) produces numbers from 0 to 4, and the for-loop for x in range(5): print(x) will print these numbers each on a new line. This is useful when you need to perform actions a specific number of times or when you need to access list elements by their index .

To conditionally add a value to certain elements in a list based on their position, you can use a for-loop with the enumerate() function to track indices. For example, to add 5 only to the second to fifth elements of numbers = [1, 2, 3, 4, 5, 6], use: for i in range(1, 5): numbers[i] += 5. This modifies elements at index 1 through 4 .

To write a Python script that reads a filename from the command line and prints all lines, you would use the sys module to access command line arguments: import sys; input_file = open(sys.argv[1], 'r'); lines = input_file.readlines(); for line in lines: print(line). sys.argv[1] represents the first argument passed to the script, which should be the path to the file to be read .

Reading from a file in Python involves opening a file using open() in read mode ('r'), then reading its contents with methods like read() or readlines(), and finally closing the file. Writing, on the other hand, requires opening the file in write mode ('w'), using write() to output content, and then closing the file. Syntax differences include specifying 'r' for reading and 'w' for writing, and operations differ as reading methods fetch content while writing methods modify or create file content .

In Python, you can iterate through multiple collections at the same time using the zip() function in a for-loop. Zip combines multiple lists into a single iterator of tuples. For example, using for (x, y, z) in zip(courses, rooms, time): print(x, y, z) will pair elements from each list at the same index, allowing you to iterate over these tuples simultaneously and print each set of paired elements on a new line .

To print only elements at even-numbered offsets (0-based index) from a list of numbers using loops, you can utilize a for-loop with range(): for i in range(0, len(numbers), 2): print(numbers[i]). This loop iterates over indices 0, 2, 4, etc., printing each corresponding element .

Using a tuple in the 'in' part of a for-loop lets you directly unpack and access elements within nested collections. This is useful when the elements of your iterable (like a list or zip object) are themselves sequences. For instance, if iterating over [(‘a’,1), (‘b’,2), (‘c’,3)], using for (x, y) in list: print(x) breaks each tuple into x and y directly, printing each first element ('a', 'b', 'c') without needing further indexing .

To print each name from the list 'linguists' on a separate line using a for-loop in Python, you should iterate over each element of the list and print it. This can be done with the code: for linguist in linguists: print(linguist). This for-loop will step through each name in the list and print it on a new line .

You might also like