I just started working with loops and somehow this is giving me an error, something with the variable pw is not right but I don't see anything wrong with it.
import random
import string
letters= string.printable
length= int(input( "How long do you want your password to be? "))
pw= ""
def generatePass():
for i in range(length):
pw = pw random.choice(letters) #Error here
print(pw)
generatePass()
Any help is appreciated Nick
CodePudding user response:
Your problem is not in the loop, but in the communication between your function (def generatePass) and your main execution. The following works:
import random
import string
letters= string.printable
def generatePass(length):
pw = ""
for i in range(length):
pw = pw random.choice(letters) #Error here
return pw
length= int(input( "How long do you want your password to be? "))
print(generatePass(length))
CodePudding user response:
So the thing is that pw
variable is not in your function. generatePass
does not see it. In python, functions can't access any variable outside of the function unless its a parameter or is declared global. So there are 3 ways that you can make your code working:
- Pass
pw
as a parameter to your function:
import random
import string
letters = string.printable
length = int(input("How long do you want your password to be? "))
pw = ""
def generatePass(pw):
for i in range(length):
pw = pw random.choice(letters)
return pw
print(generatePass(pw)) # here you pass the variable to a function
- Create local varialbe
pw
inside thegeneratePass
function:
import random
import string
letters = string.printable
length = int(input("How long do you want your password to be? "))
def generatePass():
pw = "" # here you create local variable inside a function (it is not visible outside of it)
for i in range(length):
pw = pw random.choice(letters)
return pw
print(generatePass())
Thanks to it you do not have to pass pw
as a parameter to a function.
- Make your variable
global
import random
import string
letters = string.printable
length = int(input("How long do you want your password to be? "))
pw = ""
def generatePass():
global pw # here you make pw as a global variable
for i in range(length):
pw = pw random.choice(letters)
return pw
generatePass()
print(pw)