Python 3.0 - 将范围循环输出分配给变量

时间:2017-10-19 14:24:54

标签: python loops

#Imports
import string
import random
import time


digits = string.digits
letters = string.ascii_letters
punctuation =("!\"\<>@#£$%^&*")
PasswordCode = letters+punctuation+digits

PassLenInput = input("How long should the password be?")
PassLenInput = int(PassLenInput)
for i in range(PassLenInput):
    print(random.choice(PasswordCode),end="")

我的输出如下

How long should the password be?4
GtRA

我想将此输出保存到名为pass的变量,然后将该变量保存到文本文件

由于

2 个答案:

答案 0 :(得分:1)

看看这个答案

#Imports
import string
import random
import time


digits = string.digits
letters = string.ascii_letters
punctuation =("!\"\<>@#£$%^&*")
PasswordCode = letters+punctuation+digits

PassLenInput = input("How long should the password be?")
PassLenInput = int(PassLenInput)
password = ""
for i in range(PassLenInput):
    password += random.choice(PasswordCode)
    print(password)

#Save Password
with open("password.txt", "w") as save_password:
    save_password.write(password)

答案 1 :(得分:0)

我优化了导入并将密码写入文件:

from string import digits
from string import ascii_letters as letters
import random

punctuation =("!\"\<>@#£$%^&*")
PasswordCode = letters+punctuation+digits

PassLenInput = int(input("How long should the password be?"))

password = ''

for i in range(PassLenInput):
    password += random.choice(PasswordCode)

with open('password_file.txt', 'w') as f:
    f.write(password)