Hack Forums
[Python] Assistance with a simple for/in loop - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118)
+---- Thread: [Python] Assistance with a simple for/in loop (/showthread.php?tid=5612502)



Assistance with a simple for/in loop - Lockheed - May 1, 2017

PHP Code

<?php 
def generate
(nouns,verbs,number_of_sentence,filename):
    for 
num in range(number_of_sentence):
        
go = open(filename,"w")
        print(
random.choice(nouns).rstrip(),random.choice(verbs).rstrip(),random.choice(nouns),file=go)
        
go.close()
            
if 
__name__ == "__main__":
    
nouns = get_list("nouns.txt")
    
verbs = get_list("verbs.txt")

    
generate(nouns,verbs,100,"sentences.txt") 

Hey all, im not able to get the for in loop to work for me. Could a 2nd pair of eyes take a look and point me in the right direction? it needs to produce multiple sentences but at the moment is only producing one.


Thanks


* - Grimm Reaper - May 1, 2017

Umm #for num in range(int(number_of_sentence)). ##corrected one

U hv to convert it into int value, else it considers that as string and counts the no. Of variables in it ... say previously if numberofsentence=5 then ur code reads it as 1


* - Lockheed - May 1, 2017

PHP Code

<?php 
for num in range(int(number_of_sentence)):
        
go = open(filename,"w")
        print(
random.choice(nouns).rstrip(),random.choice(verbs).rstrip(),random.choice(nouns),file=go)
        
go.close() 

provides the same result.
number_of_sentence is an integer to begin with so it shouldn't need to be converted, Thanks for your reply though.


* - HFDone - May 1, 2017

Code
for i in range(10):
  with open("test.txt", "a") as f:
    f.write(str(i))



* - (╯°□°)╯︵ ┻━━┻ - May 1, 2017

It's because you're opening the file with "w" inside of the loop. When you open it with "w", it overwrites any previous data. Either move your open() outside of the for loop, or change it to "a" (append).


* - TheWarOwl - May 1, 2017

(May 1, 2017 09:08 AM)(╯°□°)╯︵ ┻━━┻ Wrote:  It's because you're opening the file with "w" inside of the loop. When you open it with "w", it overwrites any previous data. Either move your open() outside of the for loop, or change it to "a" (append).

EDIT : You beat me to it so I withdraw my lol


* - Lockheed - May 1, 2017

Thanks all, was indentation and placement issues with the open and close.

Much appreciated