Are unused variables a problem? How can I get rid of this "error"?

Question:

I wanted to cover up a word. I get the user input.

user_input = input("Enter input: ")

After getting this value I want to represent it in asterisks.

Like if the user_input is "password" I want ********. Basically, the same number of characters as the original input.

My code for this is:

shadowed = ''
for i in range(len(user_input)):
    shadowed += '*'  

So I get shadowed as my desired keyword.

However, my editor highlights the i and says: Unused variable 'i'pylint(unused-variable)

Would this be an issue? Or do I have to fix it?

Asked By: user14493353

||

Answers:

In python, you use underscores _ for unused variables.

In your case:

shadowed = ''
for _ in range(len(user_input)):
    shadowed += '*'  

Now you shouldn’t get any lint errors anymore.

Answered By: entenfaenger17

There are a couple of things here.

To begin with, the convention is to use something like _ for a throwaway variable like this. So it would be:

for _ in range(len(user_input)):

This should get rid of the warning.

Asides from that, since you’re just performing something for each element, why not change it to

for _ in user_input:

The combination of the two is not only shorter, it makes it clearer that you just want to perform something for each element, not really caring about the index.

You could even use something shorter like

''.join('*' for _ in user_input)

or just

'*' * len(user_input)

The combination of the two is not only shorter, it makes it clearer that you just want to perform something for each element, not really caring about the index.

Answered By: Ami Tavory

No problem with your code.
But in addition, you can use:

shadowed_password = "*" * len(user_input)

Which is more Pythonic.
To deal with the lint error, change your code to:

for _ in user_input:

Because i in never used.
for i in user_input Is not Pythonic, when i is never used.

Answered By: MuxAte
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.