Home > Mobile >  Variable referenced before assignemnt in for loop
Variable referenced before assignemnt in for loop

Time:04-12

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:

  1. 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
  1. Create local varialbe pw inside the generatePass 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.

  1. 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)
  • Related