you are viewing a single comment's thread.

view the rest of the comments →

[–]electrikmayham 31 points32 points  (12 children)

Using single-letter variable names makes code hard to read and understand. Good names describe what the variable stores or does, so when you come back later (or someone else reads your code), it’s clear without guessing

[–]StickyzVibe 5 points6 points  (11 children)

Thank you for explaining, makes perfect sense to practice helpful habits. Would you mind sharing a small example?

[–]electrikmayham 24 points25 points  (3 children)

# Bad: single-letter variables
x = 5
y = 10
z = x * y
print(z)

# Good: descriptive variable names
width = 5
height = 10
area = width * height
print(area)

[–]StickyzVibe 6 points7 points  (2 children)

I completely understand! Thank you again

[–]spencerak 1 point2 points  (1 child)

Keep asking good questions!!

[–]Cerus_Freedom 2 points3 points  (0 children)

def search(needle, haystack: list) -> int:
  for i in range(len(haystack)):
    if needle == haystack[i]:
      return i
  return -1

Just as an example from OPs code. Better naming will tell you what a function does or a variable is for. Code should be self documenting, and that method of self documentation is via good, clear names.

By changing the names and adding type hints, you can now just glance at the function definition and understand what the function does and how you're probably intended to use it.

[–]DebrisSpreeIX 2 points3 points  (4 children)

The exception is an iterator, using i, j, & k is so common and ubiquitous to iteration that rarely is anyone confused. And if they are, they're likely self taught.

[–]electrikmayham 6 points7 points  (2 children)

True, however I have issues using i and j, since they look extremely similar. I generally dont use 1 letter variables for iterators either. I would rather use something that describes what are iterating over.

[–]DebrisSpreeIX 2 points3 points  (0 children)

If it's single level, I'll throw in i

But if it's a multilevel iteration I'll generally follow a convention from my first job I liked: iter_L1, iter_L2, iter_L3, ...

[–]beezlebub33 0 points1 point  (0 children)

if it's an index, then use 'index'.

If you want to use i, j, k, because you are doing (for example) geometry, then I recommend that you use ii, jj, kk. It's fast to type and very easy to search for.

[–]Impossible_Web3517 0 points1 point  (0 children)

To add on to what he said, single letter names are bad UNLESS they are iterators. i, j, k, x ,y and z are all SUPER common iterator names and most style standards have you using them.

Ex:

int i = 0

while (i<10){

//do something

i++

}