简体   繁体   中英

Python:For loop only works once in python

I don't know why but it doesn't work.The for loop only works once and that's it

import string
import random
print ('Insert your words,m8')
letters = string.ascii_letters
words = input()
max_number = random.randint(6,10)
for i in range(0,max_number):
    randy = random.randint(0,25)
    title = letters[randy]
open(str(title),'w+').write(words)

Your code is

    import string
    import random
    print ('Insert your words,m8')
    letters = string.ascii_letters
    words = input()
    max_number = random.randint(6,10)
    for i in range(0,max_number):
        randy = random.randint(0,25)
        title = letters[randy]
    open(str(title),'w+').write(words)

Where the last statement is outside for loop which will be executed after for loop finishes .

so , if you want to write one by one in word then your code should look like

import string
import random
print ('Insert your words,m8')
letters = string.ascii_letters
words = input()
max_number = random.randint(6,10)
for i in range(0,max_number):
    randy = random.randint(0,25)
    title = letters[randy]
    open(str(title),'w+').write(words)

So , loop is excuting perfectly .

Please tell what you are trying to achieve ?

I believe the intent of the code is to generate a random title consisting of 6 - 10 letters and then writing the input obtained from the user to that file.If that is the case, set title to an empty string and then add letters to it inside the loop.

import string
import random
print ('Insert your words,m8')
letters = string.ascii_letters
title = ''
words = input()
max_number = random.randint(6,10)
for i in range(0,max_number):
    randy = random.randint(0,25)
    title += letters[randy]
open(str(title),'w+').write(words)

Try using a list comprehension instead of a loop:

import string
import random

print ('Insert your words,m8')
letters = string.ascii_letters
words = input()
title = ''.join([letters[random.randint(0, 25)] for _ in xrange(random.randint(6, 10))])
open(str(title),'w+').write(words)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM