Python Programming Examples Tutorial Index
Python String Programs

This tutorial will guide you in creating a Python program that generates strong passwords. A strong password is a combination of different characters. It typically includes uppercase and lowercase letters, numbers, and special characters.

Choosing a strong password is essential as it helps protect personal and sensitive information from unauthorized access. A strong password is more complex for others to guess or crack, making it more difficult for hackers to gain unauthorized access and steal personal information.


#import random module 
import random

"""function to generate a random password of given length"""
def generate_password(length: int) -> str:
    #storing letters, numbers and special characters
    charset = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()?"

    #random sampling by joining the length of the password and the variables
    return "".join(random.sample(charset, length))

#user input for password length 
pass_length = int(input("Enter the length of password : "))

#call the function
password = generate_password(pass_length)


The above python program is a function that generates a random password of a given length. The program starts by importing the "random" module, which provides functionality for generating random numbers and samples.

The "generate_password" function takes an argument "length" of type int and returns a string. The function starts by defining a variable "charset" that contains a combination of letters (lowercase and uppercase), numbers, and special characters. This variable serves as the pool of characters from which the random password will be generated.

The function then uses the "random.sample" method from the "random" module to randomly select a specified number of characters from the "charset" variable. The number of characters selected is equal to the value of the "length" argument passed to the function. The selected characters are then joined to form the final random password and returned as the function output.

The program then prompts the user to enter the desired password length using the "input" function. The user's input is then converted to an integer and passed as an argument to the "generate_password" function. The function generates the random password, printed to the console.