Learn Regular Expressions by Building a Password Generator - Step 61

Tell us what’s happening:

Describe your issue in detail here.

how to do this code with one if statement with condition list comprehension

Your code so far

import re
import secrets
import string


def generate_password(length, nums, special_chars, uppercase, lowercase):
    # Define the possible characters for the password
    letters = string.ascii_letters
    digits = string.digits
    symbols = string.punctuation

    # Combine all characters
    all_characters = letters + digits + symbols

    while True:
        password = ''
        # Generate password
        for _ in range(length):
            password += secrets.choice(all_characters)
       
        constraints = [
            (nums, r'\d'),
            (lowercase, r'[a-z]'),
            (uppercase, r'[A-Z]'),            
            (special_chars, fr'[{symbols}]')            
        ]

        # Check constraints

/* User Editable Region */

        # list comprehension
        count = 0        
        for constraint , pattern in constraints:
            
                if constraint <= len(re.findall(pattern,password)):
                       count += 1
        if count == 4:
            break
        


/* User Editable Region */

            break

    return password

# new_password = generate_password(8)
# print(new_password)

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36

Challenge Information:

Learn Regular Expressions by Building a Password Generator - Step 61

You appear to have created this post without editing the template. Please edit your post to Tell us what’s happening in your own words.

Have you tried something?

A list comprehension is like backwards syntax of a for loop. You need to transform this for loop into a list comprehension

for element in list:
    print(element)

Transforms into:

[print(element) for element in list]

I hope this helps!

More info here:
https://www.freecodecamp.org/news/list-comprehension-in-python/

https://www.w3schools.com/python/python_lists_comprehension.asp

https://www.geeksforgeeks.org/python-list-comprehension/

2 Likes

yeh , i’ve tried but doesn’t work I’m learning more about list comprehension to work it out

Post your updated code when you have some attempts or more questions

1 Like

The simplest explanation of list comprehension i have come across.!! Thanks, man

1 Like