Question

What does "" mean in python?

For example:

def makePassword(length) :
   password = ""

What does password become and/or what does that statement mean? Does it redefine password? Does it just reemphasize the fact that password has already been defined above (assuming it has been). FYI: This is only part of a code.

No correct solution

OTHER TIPS

The

password = ""

sets password to the empty string (that is, the string consisting of zero characters).

It is worth noting that this is different to not assigning password anything at all (in which case it won't exist) and is different to setting password to None.

Empty string (length 0). password becomes empty string.

Does it redefine password?

It does, within the scope of that function. Or if password was declared as a global.

It becomes exactly that, "". It's an 'empty' string essentially. It just becomes an object with type of string.

In generating a string, sometimes results are created one character at a time, or in chunks. From the function name I suspect that this particular algorithm was doing something like that.

If the process is iterative (happens inside a loop) a natural way to add the latest chunk to whatever has already been accumulated is to use a statement such as

password = password + new_chunk

which can nowadays be written more concisely as

password += new_chunk

This takes the existing value of the password variable and adds the new chunk to it, replacing the old value of password.

Executing this statement without having assigned a value to the password variable would cause an exception, however (specifically you would see a NameError because the statement requires you to start with the existing value of password, and it doesn't have one). So before the loop you assign the null string (the one containing no characters) to the variable, thereby avoiding an inconvenient but all too common error.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top