Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

Python 

Assistance with a simple for/in loop

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
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
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.
Code
for i in range(10):
  with open("test.txt", "a") as f:
    f.write(str(i))
[Image: bitcoin.png] Be Nice For Once 15hVUVz7xA4kazHdk2BuErENGCskVwjYXP
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).
(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
[Image: 5BgQiIm.gif]

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

Much appreciated


Possibly Related Threads...
Thread / Author Replies Views Last Post
[Java] by ohxerxeFeb 4, 2018 03:26 PM 3 306 Feb 4, 2018 03:26 PM
Last Post: matt
[Java] by prodigyhfSep 1, 2017 05:22 PM 0 223 Sep 1, 2017 05:22 PM
Last Post: prodigyhf
[.NET] by EffexionJul 25, 2017 03:39 AM 1 150 Jul 25, 2017 03:39 AM
Last Post: VmX5