I'm trying to add more to my code so that you are only allowed to enter specific parameters. Ever since I did that I can no longer get the code to run completely without it telling me it cannot be interpreted as an integer. I'm new to Python and would like to work it out.Tried converting range(length) to an int and str but i'm assuming i'm going about it the wrong way. Any tips appreciated.
import random
import string
def char_length():
while True:
char_length = input("How many characters would you like your password to be? ")
if char_length.isdigit() and 0 < int(char_length) < 51:
char_length = int(char_length)
return
else:
print('Response must be a number between 0 and 50')
char_length()
def random_pass(length):
while True:
spec_char = input("Would you like special characters in your password? ")
if spec_char == "Yes":
characters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choice(characters) for i in range(length))
print("Your password is: ", password)
return
elif spec_char == "No":
characters = ''.join(random.choice(string.ascii_letters) for i in range(length))
print("Your password is: ", characters)
return
else:
print("Please only type Yes or No")
random_pass(char_length)
Your functions should return the values they've generated, rather than just doing a bare return
(which implicitly returns None
). You can then get that value by actually calling the function with ()
. See the comments in the fixed code:
import random
import string
def char_length():
while True:
# don't reuse the function name for your local length variable
length = input("How many characters would you like your password to be? ")
if length.isdigit() and 0 < int(length) < 51:
return int(length) # need to actually return the converted length
else:
print('Response must be a number between 0 and 50')
def random_pass(length):
while True:
spec_char = input("Would you like special characters in your password? ")
if spec_char == "Yes":
characters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choice(characters) for i in range(length))
print("Your password is: ", password)
return password # return the password
elif spec_char == "No":
characters = ''.join(random.choice(string.ascii_letters) for i in range(length))
print("Your password is: ", characters)
return characters # again, return the password (but here it's the "characters" var)
else:
print("Please only type Yes or No")
random_pass(char_length()) # call char_length and pass the result to random_pass
The error in your original code was because you were passing char_length
(the function) as the argument to random_pass
, rather than char_length()
(the result of calling the function, which will be an int
).