Python:For循环只能在python中运行一次

时间:2017-11-25 09:05:30

标签: python python-3.x for-loop random

我不知道为什么但它不起作用.for循环只运行一次,就是它

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)

3 个答案:

答案 0 :(得分:2)

您的代码是

    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)

最后一个语句在for循环之外,它将在for循环结束后执行。

所以,如果你想逐个写一个字,那么你的代码应该是

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)

因此,循环完美地排除了。

请告诉您要实现的目标?

答案 1 :(得分:1)

我相信代码的意图是生成一个由6-10个字母组成的随机标题,然后将用户获得的输入写入该文件。如果是这种情况,请将title设置为空字符串然后在循环内添加字母。

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)

答案 2 :(得分:0)

尝试使用列表推导而不是循环:

2017-11-25 17:12:31.645624+0800 LeanCloudStarter[2044:84112] Task <520034AA-B195-4354-ADB6-3544C5907E22>.<69> HTTP load failed (error code: -1005 [4:-4])
2017-11-25 17:12:31.646056+0800 LeanCloudStarter[2044:83813] Task <520034AA-B195-4354-ADB6-3544C5907E22>.<69> finished with error - code: -1005