Python Forum
Help with function and sep( , ) value
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help with function and sep( , ) value
#3
I was calling 3 lists to verify if the function was coded within the specs.

My file name was called list_function

import list_function

print("\nStart Testing!")

str_list1 = ['r', 'i', 'n', 'g', 'i', 'n', 'g']
str_list2 = ['r', 'e', 'd']
empty = []

print("\nlength Test")
print("List length:", list_function.length(str_list1))
print("List length:", list_function.length(empty))
The issue was that it gave this error when calling the last print function (empty)

Error:
File line 24, in <module> print("List is:", list_function.to_string(empty)) File line 24, in to_string result += my_list[entry + 1] UnboundLocalError: local variable 'entry' referenced before assignment
This was solved by adding the line

if not my_list: 
    return result
Is this a clean way of doing things to account for the empty print function?

def length(my_list):

    loop_flag = True

    count = 0

    for entry in my_list:
        count += 1

    return count

 
def to_string(my_list, sep=', '):

    result = ''
    list_length = length(my_list)

    if not my_list:
        return result

    # Loop through indices except last entry.
    for entry in range(list_length -1):
        result += my_list[entry] + sep
        
    # Add last entry on.
    result += my_list[entry + 1]

    return result
Reply


Messages In This Thread
Help with function and sep( , ) value - by drewbty - May-31-2020, 09:20 AM
RE: Help with function and sep( , ) value - by drewbty - Jun-01-2020, 11:23 AM

Forum Jump:

User Panel Messages

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