
Random Password Generator with Python
The goal of this exercise is to write a code that generates a Random Password with Python.
The function is named randomPassword, and it generates a random password that takes no parameters.
The password criteria are as follows:
The password will have a random length of between 7 and 10 characters.
Each character will be randomly selected from positions 33 to 126 from the ASCII table.
Solution
# coding: utf-8
# In[46]:
def randomPassword():
"""
A function to randomly generate password with a length between 7 and 10.
Input:
No input
Return:
password - the generated password.
"""
from random import randint # Importing the random generator function
# CONSTANTS
MIN_PASSWORD_LENGTH = 7
MAX_PASSWORD_LENGTH = 10
MIN_ASCII = 33
MAX_ASCII = 126
# Obtaining a random password length within the limits specified in the constants
password_length = randint(MIN_PASSWORD_LENGTH, MAX_PASSWORD_LENGTH)
# Array for storing the randomly generated password characters
gen_chars = []
# The loop for the generation of the random characters
for _ in range(password_length):
# Obtaining an ASCII number randomly within the limit of the constants.
random_ascii = randint(MIN_ASCII, MAX_ASCII)
# Converting the ASCII number to a character
new_char = chr(random_ascii)
# Adding the new character to the array of generated password characters
gen_chars.append(new_char)
# End of Loop
# Joining all the generated characters together to form a string type object
password = ''.join(gen_chars)
return password # returning the jointed characters as the password
if __name__ == "__main__":
# Calling the created function
mypassword = randomPassword()
# Displaying the output of the function
print("Generated password: ", mypassword)
Code Explanation
This Python code defines a function randomPassword()
that generates a random password with a length between 7 and 10 characters. Let's break down the code in detail, including explanations and code snippets.
The code is structured into two main parts: the randomPassword()
function definition and the if __name__ == "__main__":
block, which demonstrates how to use the function.
1. randomPassword()
Function
This function is designed to generate a random password.
def randomPassword():
"""
A function to randomly generate password with a length between 7 and 10.
Input:
No input
Return:
password - the generated password.
"""
def randomPassword():
: This line defines a function namedrandomPassword()
. It takes no arguments.Docstring (
"""..."""
): This is a multi-line string used to explain what the function does, its inputs, and what it returns. It's good practice for documenting code.
from random import randint # Importing the random generator function
from random import randint
: This line imports therandint
function from Python's built-inrandom
module.randint(a, b)
: This function returns a random integerN
such thata <= N <= b
. This is crucial for generating random lengths and random ASCII values.
# CONSTANTS
MIN_PASSWORD_LENGTH = 7
MAX_PASSWORD_LENGTH = 10
MIN_ASCII = 33
MAX_ASCII = 126
Constants: These variables are defined in uppercase by convention to indicate that their values are not expected to change during the program's execution.
MIN_PASSWORD_LENGTH = 7
: The minimum allowed length for the generated password.MAX_PASSWORD_LENGTH = 10
: The maximum allowed length for the generated password.MIN_ASCII = 33
: The minimum ASCII (American Standard Code for Information Interchange) value to consider for password characters. ASCII 33 is the '!' character.MAX_ASCII = 126
: The maximum ASCII value to consider for password characters. ASCII 126 is the '~' character.- Why ASCII 33 to 126? This range includes printable characters, including numbers (0-9), uppercase letters (A-Z), lowercase letters (a-z), and various symbols (e.g., !, @, #, $, %, ^, &, *). This makes the generated passwords more robust than just using letters and numbers.
# Obtaining a random password length within the limits specified in the constants
password_length = randint(MIN_PASSWORD_LENGTH, MAX_PASSWORD_LENGTH)
password_length = randint(MIN_PASSWORD_LENGTH, MAX_PASSWORD_LENGTH)
: This line usesrandint
to determine the actual length of the password. It will be a random integer between 7 and 10 (10 inclusive).
# Array for storing the randomly generated password characters
gen_chars = []
gen_chars = []
: An empty list namedgen_chars
is initialized. This list will temporarily store individual characters as they are generated before they are joined together to form the final password string.
# The loop for the generation of the random characters
for _ in range(password_length):
# Obtaining an ASCII number randomly within the limit of the constants.
random_ascii = randint(MIN_ASCII, MAX_ASCII)
# Converting the ASCII number to a character
new_char = chr(random_ascii)
# Adding the new character to the array of generated password characters
gen_chars.append(new_char)
# End of Loop
for _ in range(password_length):
: This is afor
loop that iteratespassword_length
times (e.g., 7 to 10 times, depending on the randomly chosen length).- The underscore
_
is used as the loop variable when you don't need to use the actual iteration number inside the loop (it's just a placeholder).
- The underscore
random_ascii = randint(MIN_ASCII, MAX_ASCII)
: Inside each iteration, a random integer is generated betweenMIN_ASCII
(33) andMAX_ASCII
(126). This integer represents the ASCII code of a character.new_char = chr(random_ascii)
: Thechr()
built-in function is used to convert an integer (ASCII value) into its corresponding character. For example,chr(65)
returns 'A',chr(97)
returns 'a', andchr(48)
returns '0'.gen_chars.append(new_char)
: The newly generated character (new_char
) is added to thegen_chars
list.
# Joining all the generated characters together to form a string type object
password = ''.join(gen_chars)
return password # returning the jointed characters as the password
password = ''.join(gen_chars)
: After the loop finishes, all the individual characters stored in thegen_chars
list are joined together to form a single string. The''
before.join()
means that the characters will be joined with an empty string as a separator (i.e., no separation, just concatenated).return password
: The function returns the final generated password string.
2. if __name__ == "__main__":
Block
This block of code is a standard Python idiom.
if __name__ == "__main__":
# Calling the created function
mypassword = randomPassword()
# Displaying the output of the function
print("Generated password: ", mypassword)
if __name__ == "__main__":
: This condition checks if the script is being run directly (as the main program) rather than being imported as a module into another script.If you run
your_
script.py
directly,__name__
will be"__main__"
.If you import
your_
script.py
into another script (e.g.,import your_script
), then__name__
inyour_
script.py
will beyour_script
, and the code inside this block will not execute.This is useful for putting code that should only run when the script is executed as a standalone program (like testing or demonstration code).
mypassword = randomPassword()
: TherandomPassword()
function is called, and the returned password string is stored in themypassword
variable.print("Generated password: ", mypassword)
: This line prints the generated password to the console, prefixed with the label "Generated password: ".