Python Forum
New to python/coding Need help on Understanding why this code isn't working. Thanks!
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
New to python/coding Need help on Understanding why this code isn't working. Thanks!
#1
Hi all! I am new to python and coding in general. I am following along in a book and have come across code that the(interpreter/compiler **not sure which ones right) don't like. I am using VS Code in Anaconda to create and run the .py files. I don't know if that makes a difference. Anyways here is the code. Any help on understanding why this isn't working would be much appreciated. I think its the first line(def alphabetize(original_list=[])) it don't like. it has the squiggly line underneath it. I will be really thankful for any help/guidance anyone can give...

def alphabetize(original_list=[]):
    """Pass any list in square brackets, displays a string with items
    sorted"""
    #Inside the function make a working copy of the list passed in.
    sorted_list = original_list.copy()
    #Sort the working copy.
    sorted_list.sort()
    #Make a new empty string for output
    final_list = ''
    #Loop through sorted list and append name and comma and space.
    for name in sorted_list:
        final_list += name + ', '
    #Knock of last comma space if final list is long enough
    final_list = final_list[:-2]
    #Return the alphabetized list.
    return final_list
names = ['McMullen', 'Keaser', 'Maier', 'Wilson', 'Yudt', 'Gallagher', 'Jacobs']
alphabetize(names)
buran write May-08-2023, 09:28 AM:
Please, use proper tags when post code, traceback, output, etc. This time I have added tags for you.
See BBcode help for more info.
Reply
#2
(May-08-2023, 08:51 AM)mat3372 Wrote: code that the(interpreter/compiler **not sure which ones right) don't like
What that does mean exactly? Do you get error?
There are several odd things in the code that you should be aware - using mutable default arguments and also you return string, not list
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
(May-08-2023, 09:35 AM)buran Wrote:
(May-08-2023, 08:51 AM)mat3372 Wrote: code that the(interpreter/compiler **not sure which ones right) don't like
What that does mean exactly? Do you get error?
There are several odd things in the code that you should be aware - using mutable default arguments and also you return string, not list

I didn't know name of what ran the code(compiler/ interpreter **Don't know if either is right)
Yes I do get 1 error and it has squiggly line underneath "def alphabetize" on first line. When I hover over it, it says...Dangerous default value [] as argument.
Reply
#4
So, this is not error (i.e. when you run the code), nor it comes from the interpreter. It's a warning from your IDE about using mutable default argument. Read why it may surprise you
https://docs.python-guide.org/writing/go...-arguments
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
(May-08-2023, 10:21 AM)buran Wrote: So, this is not error (i.e. when you run the code), nor it comes from the interpreter. It's a warning from your IDE about using mutable default argument. Read why it may surprise you
https://docs.python-guide.org/writing/go...-arguments

Thanks for all your help!!! When I run the code "as is" nothing happens. Not totally true my interpreter(Anaconda-VS Code) lists the file that im working in but doesn't list alphabetized names. I don't know why they would put that in the book if it is the wrong way of doing it. So confusing. I read the info in the link you provided and im going to try and do it the way it lists. Thanks again for all your help. I am really green at all this and just trying to make sense of it all.
Reply
#6
You could print the return value if you want to see the results.

As for "the wrong way", using a mutable type for a default argument can cause problems, but it does not in your code. The default argument is there to protect against calling the function without any arguments. I think it makes more sense to let the function crash if no list is provided, but the author decided they would return an empty string when this happens.

A larger problem with the code is it limits you to sorting lists. You cannot sort a tuple or a set. I would rewrite to make it work with any itrator.
def alphabetize(items=[]):
    """Return sorted list as CSV string."""
    final_list = ''
    for name in sorted(items):
        final_list += name + ', '
    final_list = final_list[:-2]
    return final_list


names = {'McMullen', 'Keaser', 'Maier', 'Wilson', 'Yudt', 'Gallagher', 'Jacobs'}
print(alphabetize(names))
Using "sorted()" instead of "sort()" we don't have to copy the input list. sorted() creates the new, sorted list for us. Since we don't have to copy() the input, we don't have to pass in a list. In my example I passed in a set. I could also pass a tuple, or a generator, or any iterable (thing that can be used in a for loop).

Another problem is the function can be replaced with a single line of code.
names = {'McMullen', 'Keaser', 'Maier', 'Wilson', 'Yudt', 'Gallagher', 'Jacobs'}
print(",".join(sorted(names)))
But these are only problems if this was "production code", not if it is a coding example for learning Python. It is difficult to write code that is both well designed and demonstrates the intent of the lesson. Maybe the next lesson will point out the shortcomings of limiting the function input to a list, and the advantages of using the builtin function and standard libraries instead of writing your own.
Reply
#7
Thanks for the help. What you wrote makes a lot more sense. Also, I didn't realize there was no print() in the code in the book. I feel like an idiot. I am new to programming and I'm trying to retain as much information as I can. It's a lot to take in. I appreciated you taking time out to help!!
Reply
#8
(May-08-2023, 02:38 PM)mat3372 Wrote: Thanks for the help. What you wrote makes a lot more sense. Also, I didn't realize there was no print() in the code in the book. I feel like an idiot. I am new to programming and I'm trying to retain as much information as I can. It's a lot to take in. I appreciated you taking time out to help!!

Where would you put print() in the code in the book?
buran write May-10-2023, 05:25 AM:
Link removed
Reply
#9
(May-09-2023, 08:43 AM)zolwtilo Wrote: Where would you put print() in the code in the book?
Compare line #18 from the code in the original post (i.e. code presumably from the book) and line #11 in the deanhystad's post
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  New to Python - Not sure why this code isn't working - Any help appreciated TheGreatNinx 4 974 Jul-22-2023, 10:21 PM
Last Post: Pedroski55
  code not working when executed from flask app ThomasDC 1 904 Jul-18-2023, 07:16 AM
Last Post: ThomasDC
  Code understanding: Need help in understanding dictionary code jt123 0 478 Jul-09-2023, 01:13 PM
Last Post: jt123
  Understanding venv; How do I ensure my python script uses the environment every time? Calab 1 2,295 May-10-2023, 02:13 PM
Last Post: Calab
  I am new to python and Could someone please explain how this below code is working? kartheekdas 2 1,021 Dec-19-2022, 05:24 PM
Last Post: kartheekdas
  Understanding Python classes PythonNewbee 3 1,195 Nov-10-2022, 11:07 PM
Last Post: deanhystad
Exclamation My code is not working as I expected and I don't know why! Marinho 4 1,093 Oct-13-2022, 08:09 PM
Last Post: deanhystad
  My Code isn't working... End3r 4 1,942 Mar-21-2022, 10:12 AM
Last Post: End3r
  Understanding a piece of code Michael1 4 1,426 Jan-20-2022, 07:14 PM
Last Post: Michael1
  I don't undestand why my code isn't working. RuyCab 2 1,998 Jun-17-2021, 03:06 PM
Last Post: RuyCab

Forum Jump:

User Panel Messages

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