2017-10-19 24 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