我正在尝试创建一个生成学生列表和随机密码的程序,然后将其写入文件,我知道我应该有返回值,但我无法弄清楚如何获得返回,这是我的代码
import random
animals = ["rat","ox","tiger","rabbit","dragon","snake","horse","sheep","monkey","rooster","dog","pig"]
colours = ["red","orange","yellow","green","blue","indigo","violet","black","white"]
def number():
number = random.randint(0,100)
return str(number)
def pw():
pw = '1'.join([random.choice(colours)+random.choice(animals)+random.choice(number())])
return pw
def student_name_and_pw():
name = 30
while name <=90:
print("student",name,":",pw())
name = name + 1
file = open("C:\\Users\\ming\\Desktop\\nameandpw.txt","w")
print(file)
file.write(str(student_name_and_pw()))
file.close()
当我打开文件时,它只是说没有。
答案 0 :(得分:1)
在方法student_name_and_pw
中构造要写入文件的字符串并将其返回
def student_name_and_pw():
name = 30
content = ""
while name <=90:
content += "student %s : %s\n" % (name, pw())
name = name + 1
return content