2017-10-19 48 views
0
#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="") 

我的输出如下的Python 3.0 - 指定范围内环路输出变量

How long should the password be?4 
GtRA 

我想保存这个输出到一个叫传变量,然后该变量保存到一个文本文件

感谢

+0

仅供参考,因为它阴影蟒蛇,你不应该使用'pass'作为变量名['pass'(HTTPS://docs.python .org/3/reference/simple_stmts.html#pass)语句 – DavidG

回答

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) 
+0

您可以通过将'PassLenInput'强制转换为一个int在与输入相同的行上,例如'PassLenInput = int(input())':) – DavidG

+0

@DavidG:你说得对。我已将这些提示并入我的答案中。 – mrCarnivore

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) 
+0

您不应该使用pass作为变量。 – utengr

+0

'pass'是python中的一个特殊关键字,因此改变了它。在这种情况下,认为它并不重要。 – Stack

+0

我想说你不应该:)你已经改变了它。 – utengr