如何使函数在for循环中发生而不在每个循环后重复命令

2024-04-26 12:53:15 发布

您现在位置:Python中文网/ 问答频道 /正文

现在我正在处理一个文件,它可以让你自定义密码。每个部分都允许您在名称、编号以及具有一定数量的部分之间进行选择。我不知道如何在不重复文本的情况下将生成每个部分的代码放置在循环的num_of_pass for中 “您想在第#节+str(当前第#节)+”中做什么?(名称、数字、字母、符号、年、日、月) 每次它都会给出一个新密码。我怎样才能做到这一点

    names = ['Tim', 'Alex', 'Thomas', 'Katrina', 'Joshua', 'James', 'John', 'Emily', 'Mary', 'Patricia', 'Jennifer',
             'Linda', 'Elizabeth', 'Robert', 'Michael', 'William', 'David', 'Richard', 'Ashley', 'Damon', 'Max']

    options = ['name', 'number', 'letter', 'symbol', 'year', 'day', 'month']

    days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

    months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']

sections = input('How many sections would you like? ')
        num_of_pass = input('How many passwords would you like? ')
        current_section = 1
        for num in range(int(sections)):
            section_type = input('What would you like in section #' + str(current_section) + '? (name, number, letter, symbol, year, day, month) ')
            if section_type == 'name':
                section = random.choice(names)
            elif section_type == 'number':
                section = str(random.randint(1, 9))
            elif section_type == 'letter':
                section = random.choice(string.ascii_letters)
            elif section_type == 'symbol':
                section = str(random.choice(string.punctuation))
            elif section_type == 'year':
                section = str(random.randint(1000, 2020))
            elif section_type == 'day':
                section = random.choice(days)
            elif section_type == 'month':
                section = random.choice(months)
            password = password + section
            current_section += 1
        print(password)
        password = ''

Tags: namenumbertypesectionrandompasswordsymbolyear
1条回答
网友
1楼 · 发布于 2024-04-26 12:53:15

我认为您可以简单地将input语句放在循环之外,或者有一个解决方法—将它放在一个条件中:

for num in range(int(sections)):
            if count == 0:
                section_type = input('What would you like in section #' + str(current_section) + '? (name, number, letter, symbol, year, day, month) ')
                count += 1
            if section_type == 'name':
                section = random.choice(names)

相关问题 更多 >