Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Readability issues
#1
What's the best way to separate out a line of code that runs past the right margin?

For example:

"""#practicepython.org exercise #12:  Write a program that takes a list of numbers 
(for example, a = [5, 10, 15, 20, 25]) and makes a new list of only the first and 
last elements of the given list. For practice, write this code inside a function.

Concepts to practice:  Lists and properties of lists, List comprehensions (maybe),
Functions."""
from numpy import random
list_len = random.randint(2, 100)
unorg_list = [random.randint(0, 100) for i in range(list_len)]
print(f'This unorganized list is {list_len} numbers long:  {unorg_list}')
org_list = list(set(unorg_list))
print(f'\nThe organized version (sorted and duplicates eliminated) of the same list is ',end='')
print(f'{len(org_list)} numbers long:  {org_list}')
The last two lines I separated out and used end='' to avoid a line break. This works, but can't I somehow use a backslash and continue on the next line? My problem with doing it this way is that I sometimes get EOL errors or indentation errors. If there's a proper way to do this, then please let me know.

The output is also a bit confusing:

Output:
This unorganized list is 71 numbers long: [32, 7, 67, 35, 46, 69, 93, 83, 46, 44, 0, 55, 18, 34, 38, 78, 67, 40, 80, 37, 76, 38, 24, 18, 56, 89, 98, 84, 6, 41, 23, 60, 68, 32, 20, 57, 61, 98, 89, 48, 84, 7, 31, 81, 39, 77, 46, 34, 51, 84, 10, 2, 12, 72, 9, 36, 13, 2, 43, 36, 37, 65, 89, 89, 34, 69, 14, 74, 45, 25, 14]
Actually, it looks fine here in the forum. In my JN, 84 and 14 print with the tens digit at the end of one line and the ones digit starting off the very next line. I'd rather it not split numbers like that.

Thanks!
Reply
#2
How about:

org_list_msg = """
The organized version (sorted and duplicates eliminated) of the same list is"""
print(f"{org_list_msg} {len(org_list)} numbers long: {org_list}")
Or, if you don't want to see a list object, but rather the items therein:

print(f"{org_list_msg} {len(org_list)} numbers long:", *org_list)
Or, if you'd like to see the numbers as two digits long, so that the number take up the same about of space, when displayed e.g: 00 ... 99:

org_list = [f"{n:02d}" for n in org_list]
print(f"{org_list_msg} {len(org_list)} numbers long:", *org_list)
So, what I'm saying here, is that you can display data in whatever way you choose.
Sig:
>>> import this

The UNIX philosophy: "Do one thing, and do it well."

"The danger of computers becoming like humans is not as great as the danger of humans becoming like computers." :~ Konrad Zuse

"Everything should be made as simple as possible, but not simpler." :~ Albert Einstein
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020