Discussion:
[Tutor] Loop not iterating
Alan Gauld
2015-06-28 23:56:17 UTC
Permalink
import csv
domains = open('top500domains.csv')
domainsReader = csv.reader(domains)
domainLists = list(domainsReader)
something = ("www." + str(domain))
You overwrite something each time round the loop.
print(something)
And because this is outside the loop it will only ever print the last
item. But since you have only stored one item thats OK...
My program reads in a CSV file that has 500 list of domains. However,
when I save the output of my loop to the variable name "something"
Ypu are saving each item into something but then next time round you
throw away the old one and replace it wotyh the next.

You should create a list and store it there. But you already
have that list, its called domainLists. I'm not sure what you
think you are achieving here?
- and later print "something" it contains only 1 entry from my csv file.
Because the print is outside the loop and only prints the value
of something after the loop completes. That will be the last entry.
On the other hand, instead of saving of loop output to the variable
"something" - if I just print, I get all 500 entries displayed.
Because you are printing inside the loop. So it prints each item.

HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Mark Lawrence
2015-06-29 00:06:57 UTC
Permalink
Hello,
| 2
3
4
5
6
7 | import csv
domains = open('top500domains.csv')
domainsReader = csv.reader(domains)
domainLists = list(domainsReader)
something = ("www." + str(domain))
print(something)
|
My program reads in a CSV file that has 500 list of domains. However, when I save the output of my loop to the variable name "something" - and later print "something" it contains only 1 entry from my csv file.
On the other hand, instead of saving of loop output to the variable "something" - if I just print, I get all 500 entries displayed.
Please advise. Thanks!
You are not saving your loop output to anything. The above code simply
sets 'something' every time around the loop, and only prints 'something'
once when the loop has finished. Try something like this.

urls = [] # a Python list in case you didn't know.
for domain in domainLists:
urls.append("www." + str(domain)) # add to the end of the list

for url in urls:
doWhatever(url)
--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Steven D'Aprano
2015-06-29 02:52:07 UTC
Permalink
Hi Nym, and welcome,

On Sun, Jun 28, 2015 at 07:32:40PM +0000, Nym City via Tutor wrote:

[...]
something = ("www." + str(domain))
print(something)
My program reads in a CSV file that has 500 list of domains. However,
when I save the output of my loop to the variable name "something" -
and later print "something" it contains only 1 entry from my csv file.
Of course it does. Each time you go through the loop, you change the
value of "something" to the new value.

If you do this:

x = 23
x = 42
print(x)


What do you expect to print? Hopefully 42.

If you want multiple values, you need something like a list:

x = []
x.append(23)
x.append(42)
print(x)


Of course, in *this* case, there is an easier way to create a list with
two values:

x = [23, 42]

but in the general case where you don't know how many values you will
have, you need to add them using append inside a loop.
--
Steve
_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Steven D'Aprano
2015-06-30 02:19:01 UTC
Permalink
Hello all,
Thank you for your time and tips. The reason why I decided to create a
loop is because the output is cleaner and did not require any
formatting. However, based on what I have learned from all of your
responses, that is not going to work with what I am trying to do.
There's no reason why a loop wouldn't work, although there may be better
solutions, and a loop is a much better solution to what you have below.
import csvdomains = open('top500domains.csv')domainsReader =
csv.reader(domains)domainLists =
list(domainsReader)print('\n'.join(["https://www ." + str(lst) for lst
in domainLists]), sep='\n')
Please ensure you post as *plain text*, not HTML (so called "rich text"
or "formatted text"). When you post as HTML, many mail programs mangle
the code and destroy the formatting, as you can see above.

Reconstructing what the code should look like on five separate lines:

import csv
domains = open('top500domains.csv')
domainsReader = csv.reader(domains)
domainLists = list(domainsReader)
print('\n'.join(["https://www ." + str(lst) for lst in domainLists]), sep='\n')


The first three lines seem to be correct, but the next:

domainLists = list(domainsReader)

is unnecessary and should be deleted. However, the last line does too
much, and the wrong thing too. A simple loop is *much* better here,
since you just print the domains and don't need to keep them for further
processing:

for row in domainLists:
# row is a list of *one or more* fields; in this case, there
# is only one field per row, the domain name
domain = "https://www." + row[0]
print(domain)

Suppose that you do need to keep the domains for later, as well as print
them. Then you can do this instead:


import csv
domains = open('top500domains.csv')
domainsReader = csv.reader(domains)
# Make a list of the domains.
domains = ["https://www." + row[0] for row in domainsReader]
# Print each domain.
for domain in domains:
print(domain)
# Now continue to do more work on the list of domains...
--
Steve
_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Steven D'Aprano
2015-07-05 06:08:44 UTC
Permalink
Hi Nym, sorry your code's formatting is broken again. I've tried my best
import csv
domains = open('top500domains.csv')
domainsReader = csv.reader(domains)
domains = ["https://www." + row[1] for row in domainsReader]
    print(domain) 
The above solution is perfect and simple. It allows me to easily
insert text such as "https://www."  in the beginning of my strings or
at the end.
However, something else that came to mind was how would you break the
string and insert new text in the middle. For
example:"www.lovepython.com" I want to insert "lesson1." after the
"www.lovepython.lesson1.com"
The most general way to do this is with string slicing. You have to
build a new string:

s = "www.lovepython.com"
# find the 1st period
i = s.find('.')
# and the second:
i = s.find('.', i+1)
# slice just before the second dot
new_s = s[:i] + ".lesson1" + s[i:]
print(new_s)
First I thought row[1] in the code above
referred to the first place in the beginning of the string. So I tried
to change that number around but it did not work. I have a feeling I
might be mixing few concepts together... Thank you.
row[1] refers to item 1 in the list row, it has nothing to do with dots
in the string.

The best tool for learning Python is to play with the interactive
interpeter. Start up Python to get a command prompt. By default, the
prompt is ">>> " but I prefer to use "py> ". Now just type commands as
needed. Python will automatically display them, or you can use print.


py> row = ["This", "that", "www.lovepython.com.au/", "blah blah"]
py> row[0]
'This'
py> row[2]
'www.lovepython.com.au/'
py> s = row[2]
py> s.find(".") # first dot
3
py> s.find(".", 4) # second dot
14
py> s[:14] # slice up to the second dot
'www.lovepython'
py> s[14:] # and from the second dot onwards
'.com.au/'


Here's another way to do it:

py> s = row[2]
py> L = s.split(".")
py> print(L)
['www', 'lovepython', 'com', 'au/']
py> L.insert(2, "lesson999")
py> print(L)
['www', 'lovepython', 'lesson999', 'com', 'au/']
py> s = '.'.join(L)
py> print(s)
www.lovepython.lesson999.com.au/
--
Steve
_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Loading...