Comma Code - Automate the Boring Stuff with PythonImplement selection from array by 'random' or 'if/elif...
How to justify a team increase when the team is doing good?
while loop factorial only works up to 20?
Writing a letter of recommendation for a mediocre student
Is it really necessary to have a four hour meeting in Sprint planning?
Social leper versus social leopard
When is it acceptable to write a bad letter of recommendation?
Why does (inf + 0j)*1 evaluate to inf + nanj?
What is the difference between an astronaut in the ISS and a freediver in perfect neutral buoyancy?
Are lawyers allowed to come to agreements with opposing lawyers without the client's knowledge or consent?
Why does this image of Jupiter look so strange?
My manager quit. Should I agree to defer wage increase to accommodate budget concerns?
What benefits does the Power Word Kill spell have?
Is there a difference between equality and identity?
Could Apollo astronauts see city lights from the moon?
Is "ln" (natural log) and "log" the same thing if used in this answer?
Do we know the situation in Britain before Sealion (summer 1940)?
A simple game that keeps track of the number of questions asked
2000s Animated TV show where teenagers could physically go into a virtual world
How do you use the interjection for snorting?
Basic digital RC approximation filter in python (Micropython)
How can I repair this gas leak on my new range? Teflon tape isn't working
Does Sitecore have support for Sitecore products in containers?
practicality of 30 year fix mortgage at 55 years of age
Can you cast Dispel Magic on a Shadow Monk's Silence?
Comma Code - Automate the Boring Stuff with Python
Implement selection from array by 'random' or 'if/elif conditionals'Python code for Mad LibsProgram to print a Python list as “a, b, and c”Comma Code (project from “Automate the Boring Stuff with Python”)Comma Code (Python)Comma Code - Automate the Boring StuffAutomate the Boring Stuff with Python - The Collatz sequence projectComma Code - Ch. 4 Automate the Boring StuffRegex Version of strip()Python - The Collatz Sequence
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ margin-bottom:0;
}
$begingroup$
Below is my code for the Comma Code problem from Chapter 4 of Automate the Boring Stuff with Python. Is there anything I can do to make it cleaner?
Comma Code
Say you have a list value like this:
spam = ['apples', 'bananas', 'tofu', 'cats']
Write a function that takes a list of values as an argument and returns a string with all the items separated by a comma and a space, with 'and' inserted before the last item. For example, passing the previous spam list to the function would return 'apples, bananas, tofu, and cats'. But your function should be able to work with any list passed to it.
The output of this program could look something like this:
apples, bananas, tofu, and cats
import sys
spam = ['apples', 'bananas', 'tofu', 'cats']
def print_list(list):
for item in list:
if len(list) == 1:
print(list[0])
elif item != list[-1]:
print(item + ', ', end='')
else:
print('and ' + list[-1])
print_list(spam)
python beginner python-3.x strings formatting
New contributor
$endgroup$
add a comment
|
$begingroup$
Below is my code for the Comma Code problem from Chapter 4 of Automate the Boring Stuff with Python. Is there anything I can do to make it cleaner?
Comma Code
Say you have a list value like this:
spam = ['apples', 'bananas', 'tofu', 'cats']
Write a function that takes a list of values as an argument and returns a string with all the items separated by a comma and a space, with 'and' inserted before the last item. For example, passing the previous spam list to the function would return 'apples, bananas, tofu, and cats'. But your function should be able to work with any list passed to it.
The output of this program could look something like this:
apples, bananas, tofu, and cats
import sys
spam = ['apples', 'bananas', 'tofu', 'cats']
def print_list(list):
for item in list:
if len(list) == 1:
print(list[0])
elif item != list[-1]:
print(item + ', ', end='')
else:
print('and ' + list[-1])
print_list(spam)
python beginner python-3.x strings formatting
New contributor
$endgroup$
add a comment
|
$begingroup$
Below is my code for the Comma Code problem from Chapter 4 of Automate the Boring Stuff with Python. Is there anything I can do to make it cleaner?
Comma Code
Say you have a list value like this:
spam = ['apples', 'bananas', 'tofu', 'cats']
Write a function that takes a list of values as an argument and returns a string with all the items separated by a comma and a space, with 'and' inserted before the last item. For example, passing the previous spam list to the function would return 'apples, bananas, tofu, and cats'. But your function should be able to work with any list passed to it.
The output of this program could look something like this:
apples, bananas, tofu, and cats
import sys
spam = ['apples', 'bananas', 'tofu', 'cats']
def print_list(list):
for item in list:
if len(list) == 1:
print(list[0])
elif item != list[-1]:
print(item + ', ', end='')
else:
print('and ' + list[-1])
print_list(spam)
python beginner python-3.x strings formatting
New contributor
$endgroup$
Below is my code for the Comma Code problem from Chapter 4 of Automate the Boring Stuff with Python. Is there anything I can do to make it cleaner?
Comma Code
Say you have a list value like this:
spam = ['apples', 'bananas', 'tofu', 'cats']
Write a function that takes a list of values as an argument and returns a string with all the items separated by a comma and a space, with 'and' inserted before the last item. For example, passing the previous spam list to the function would return 'apples, bananas, tofu, and cats'. But your function should be able to work with any list passed to it.
The output of this program could look something like this:
apples, bananas, tofu, and cats
import sys
spam = ['apples', 'bananas', 'tofu', 'cats']
def print_list(list):
for item in list:
if len(list) == 1:
print(list[0])
elif item != list[-1]:
print(item + ', ', end='')
else:
print('and ' + list[-1])
print_list(spam)
python beginner python-3.x strings formatting
python beginner python-3.x strings formatting
New contributor
New contributor
edited 8 hours ago
cyberprogrammer
New contributor
asked 8 hours ago
cyberprogrammercyberprogrammer
607 bronze badges
607 bronze badges
New contributor
New contributor
add a comment
|
add a comment
|
2 Answers
2
active
oldest
votes
$begingroup$
You've got an odd bug with your code.
Given the 8th menu item from the greasy spoon café:
spam = ["Spam", "Spam", "Spam", "egg", "Spam"]
You will get:
and Spam
and Spam
and Spam
egg, and Spam
since you are not testing whether you are at the last item in your list, but rather if the current item is the same as the last item in the list.
Testing for a length 1 list should not be done inside the loop of all items; it should be done exactly once, outside the loop. Ie (but still with the above bug):
if len(list) == 1: # Test outside of loop
print(list[0])
else:
for item in list:
if item != list[-1]:
print(item + ', ', end='')
else:
print('and ' + list[-1])
Want you really want to do is print all but the last item in the list one way, and the last item a different way:
# If there are more than 1 items in the list...
if len(list) > 1:
# Print all but the last item, with a comma & space after each
for item in list[:-1]:
print(item + ', ', end='')
# with "and " printed at the very end, just before ...
print("and ", end='')
# print the last (or only) item in the list.
print(list[-1])
although this still assumes at least one item in the list.
Alternately, you could join()
all but the last item, and then add ", and "
along with the final item.
msg = list[-1]
if len(list) > 1:
msg = ", ".join(list[:-1]) + ", and " + msg
print(msg)
You are doing import sys
, but not using sys
anywhere. You can remove the import.
$endgroup$
$begingroup$
Why is it better to test for a length of zero in the outside loop? Thanks for your help :)
$endgroup$
– cyberprogrammer
7 hours ago
$begingroup$
Also, just a question I have had for a while. Why does the iterator not have to be defined before being called? For example "item" in your loop?for item in list[:-1]:
$endgroup$
– cyberprogrammer
7 hours ago
$begingroup$
The test is more efficient outside the loop, because it is done only once, instead of dozens or possibly hundreds of times, if you are looping over dozens or hundreds of entries.
$endgroup$
– AJNeufeld
5 hours ago
1
$begingroup$
Python doesn’t declare any variables. You can assignx = 5
without previously declaring thatx
exists. Thefor
statement just repeatedly assigns new values to the loop variable. It doesn’t care if the variable existed before the loop. It doesn’t even care if the variable is deleted inside the loop; it will just recreate it on the next iteration.
$endgroup$
– AJNeufeld
5 hours ago
add a comment
|
$begingroup$
Unused import statement: that should be cleaned up.
import sys
Bad parameter name: def print_list(list):
The keyword list()
is a built-in function, you don't want your variable/parameter/function/method/class named like built-ins because later when you start relying on such keywords, this will create problems.
Example: (run this interactively)
>>> word = 'mouse'
>>> letters = list(word)
>>> letters
['m', 'o', 'u', 's', 'e']
>>> list = 5
>>> new_letters = list(word)
Troubles ...
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
list(word)
TypeError: 'int' object is not callable
I think the example is self-explanatory why you shouldn't use built-ins in your naming.
def print_list(list):
Docstrings: Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods. ... A docstring is simply a multi-line string, that is not assigned to anything. It is specified in source code that is used to document a specific segment of code. You should include a docstring to your public functions indicating what they do and type hints if necessary.
This is a bit complicated
for item in list:
if len(list) == 1:
print(list[0])
elif item != list[-1]:
print(item + ', ', end='')
else:
print('and ' + list[-1])
The whole function can be simplified and written properly:
def separate(items: list):
"""Return a string of the words in items separated by a comma."""
if len(items) > 1:
return ', '.join(items[:-1]) + ', and ' + items[-1]
if len(items) == 1:
return items[0]
if not items:
raise ValueError('Empty list')
then use if __name__ == '__main__':
guard at the end of your script which allows it to be imported by other modules without running the whole script.
if __name__ == '__main__':
spam = ['apples', 'bananas', 'tofu', 'cats']
print(separate(spam))
$endgroup$
1
$begingroup$
You get the wrong result with a list of one item. (Plus, it doesn't match the problem requirement of the final comma before "and". You have"..., tofu and cats"
instead of"..., tofu, and cats"
.)
$endgroup$
– AJNeufeld
7 hours ago
$begingroup$
Thanks for pointing this out, I'll edit the code
$endgroup$
– Emad Boctor
7 hours ago
$begingroup$
@EmadBoctor Thanks for your answer. How does the if name == 'main': work?
$endgroup$
– cyberprogrammer
7 hours ago
1
$begingroup$
You place the main guard at the end of your script and call your functions from there. And there are many cases where your module is imported by outside modules, for simplicity suppose you want to use that word separator from another script that let's say that organizes text or whatever, you will import your_script_name and use it accordingly.
$endgroup$
– Emad Boctor
7 hours ago
add a comment
|
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "196"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
cyberprogrammer is a new contributor. Be nice, and check out our Code of Conduct.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f229404%2fcomma-code-automate-the-boring-stuff-with-python%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
$begingroup$
You've got an odd bug with your code.
Given the 8th menu item from the greasy spoon café:
spam = ["Spam", "Spam", "Spam", "egg", "Spam"]
You will get:
and Spam
and Spam
and Spam
egg, and Spam
since you are not testing whether you are at the last item in your list, but rather if the current item is the same as the last item in the list.
Testing for a length 1 list should not be done inside the loop of all items; it should be done exactly once, outside the loop. Ie (but still with the above bug):
if len(list) == 1: # Test outside of loop
print(list[0])
else:
for item in list:
if item != list[-1]:
print(item + ', ', end='')
else:
print('and ' + list[-1])
Want you really want to do is print all but the last item in the list one way, and the last item a different way:
# If there are more than 1 items in the list...
if len(list) > 1:
# Print all but the last item, with a comma & space after each
for item in list[:-1]:
print(item + ', ', end='')
# with "and " printed at the very end, just before ...
print("and ", end='')
# print the last (or only) item in the list.
print(list[-1])
although this still assumes at least one item in the list.
Alternately, you could join()
all but the last item, and then add ", and "
along with the final item.
msg = list[-1]
if len(list) > 1:
msg = ", ".join(list[:-1]) + ", and " + msg
print(msg)
You are doing import sys
, but not using sys
anywhere. You can remove the import.
$endgroup$
$begingroup$
Why is it better to test for a length of zero in the outside loop? Thanks for your help :)
$endgroup$
– cyberprogrammer
7 hours ago
$begingroup$
Also, just a question I have had for a while. Why does the iterator not have to be defined before being called? For example "item" in your loop?for item in list[:-1]:
$endgroup$
– cyberprogrammer
7 hours ago
$begingroup$
The test is more efficient outside the loop, because it is done only once, instead of dozens or possibly hundreds of times, if you are looping over dozens or hundreds of entries.
$endgroup$
– AJNeufeld
5 hours ago
1
$begingroup$
Python doesn’t declare any variables. You can assignx = 5
without previously declaring thatx
exists. Thefor
statement just repeatedly assigns new values to the loop variable. It doesn’t care if the variable existed before the loop. It doesn’t even care if the variable is deleted inside the loop; it will just recreate it on the next iteration.
$endgroup$
– AJNeufeld
5 hours ago
add a comment
|
$begingroup$
You've got an odd bug with your code.
Given the 8th menu item from the greasy spoon café:
spam = ["Spam", "Spam", "Spam", "egg", "Spam"]
You will get:
and Spam
and Spam
and Spam
egg, and Spam
since you are not testing whether you are at the last item in your list, but rather if the current item is the same as the last item in the list.
Testing for a length 1 list should not be done inside the loop of all items; it should be done exactly once, outside the loop. Ie (but still with the above bug):
if len(list) == 1: # Test outside of loop
print(list[0])
else:
for item in list:
if item != list[-1]:
print(item + ', ', end='')
else:
print('and ' + list[-1])
Want you really want to do is print all but the last item in the list one way, and the last item a different way:
# If there are more than 1 items in the list...
if len(list) > 1:
# Print all but the last item, with a comma & space after each
for item in list[:-1]:
print(item + ', ', end='')
# with "and " printed at the very end, just before ...
print("and ", end='')
# print the last (or only) item in the list.
print(list[-1])
although this still assumes at least one item in the list.
Alternately, you could join()
all but the last item, and then add ", and "
along with the final item.
msg = list[-1]
if len(list) > 1:
msg = ", ".join(list[:-1]) + ", and " + msg
print(msg)
You are doing import sys
, but not using sys
anywhere. You can remove the import.
$endgroup$
$begingroup$
Why is it better to test for a length of zero in the outside loop? Thanks for your help :)
$endgroup$
– cyberprogrammer
7 hours ago
$begingroup$
Also, just a question I have had for a while. Why does the iterator not have to be defined before being called? For example "item" in your loop?for item in list[:-1]:
$endgroup$
– cyberprogrammer
7 hours ago
$begingroup$
The test is more efficient outside the loop, because it is done only once, instead of dozens or possibly hundreds of times, if you are looping over dozens or hundreds of entries.
$endgroup$
– AJNeufeld
5 hours ago
1
$begingroup$
Python doesn’t declare any variables. You can assignx = 5
without previously declaring thatx
exists. Thefor
statement just repeatedly assigns new values to the loop variable. It doesn’t care if the variable existed before the loop. It doesn’t even care if the variable is deleted inside the loop; it will just recreate it on the next iteration.
$endgroup$
– AJNeufeld
5 hours ago
add a comment
|
$begingroup$
You've got an odd bug with your code.
Given the 8th menu item from the greasy spoon café:
spam = ["Spam", "Spam", "Spam", "egg", "Spam"]
You will get:
and Spam
and Spam
and Spam
egg, and Spam
since you are not testing whether you are at the last item in your list, but rather if the current item is the same as the last item in the list.
Testing for a length 1 list should not be done inside the loop of all items; it should be done exactly once, outside the loop. Ie (but still with the above bug):
if len(list) == 1: # Test outside of loop
print(list[0])
else:
for item in list:
if item != list[-1]:
print(item + ', ', end='')
else:
print('and ' + list[-1])
Want you really want to do is print all but the last item in the list one way, and the last item a different way:
# If there are more than 1 items in the list...
if len(list) > 1:
# Print all but the last item, with a comma & space after each
for item in list[:-1]:
print(item + ', ', end='')
# with "and " printed at the very end, just before ...
print("and ", end='')
# print the last (or only) item in the list.
print(list[-1])
although this still assumes at least one item in the list.
Alternately, you could join()
all but the last item, and then add ", and "
along with the final item.
msg = list[-1]
if len(list) > 1:
msg = ", ".join(list[:-1]) + ", and " + msg
print(msg)
You are doing import sys
, but not using sys
anywhere. You can remove the import.
$endgroup$
You've got an odd bug with your code.
Given the 8th menu item from the greasy spoon café:
spam = ["Spam", "Spam", "Spam", "egg", "Spam"]
You will get:
and Spam
and Spam
and Spam
egg, and Spam
since you are not testing whether you are at the last item in your list, but rather if the current item is the same as the last item in the list.
Testing for a length 1 list should not be done inside the loop of all items; it should be done exactly once, outside the loop. Ie (but still with the above bug):
if len(list) == 1: # Test outside of loop
print(list[0])
else:
for item in list:
if item != list[-1]:
print(item + ', ', end='')
else:
print('and ' + list[-1])
Want you really want to do is print all but the last item in the list one way, and the last item a different way:
# If there are more than 1 items in the list...
if len(list) > 1:
# Print all but the last item, with a comma & space after each
for item in list[:-1]:
print(item + ', ', end='')
# with "and " printed at the very end, just before ...
print("and ", end='')
# print the last (or only) item in the list.
print(list[-1])
although this still assumes at least one item in the list.
Alternately, you could join()
all but the last item, and then add ", and "
along with the final item.
msg = list[-1]
if len(list) > 1:
msg = ", ".join(list[:-1]) + ", and " + msg
print(msg)
You are doing import sys
, but not using sys
anywhere. You can remove the import.
answered 7 hours ago
AJNeufeldAJNeufeld
12.4k1 gold badge12 silver badges39 bronze badges
12.4k1 gold badge12 silver badges39 bronze badges
$begingroup$
Why is it better to test for a length of zero in the outside loop? Thanks for your help :)
$endgroup$
– cyberprogrammer
7 hours ago
$begingroup$
Also, just a question I have had for a while. Why does the iterator not have to be defined before being called? For example "item" in your loop?for item in list[:-1]:
$endgroup$
– cyberprogrammer
7 hours ago
$begingroup$
The test is more efficient outside the loop, because it is done only once, instead of dozens or possibly hundreds of times, if you are looping over dozens or hundreds of entries.
$endgroup$
– AJNeufeld
5 hours ago
1
$begingroup$
Python doesn’t declare any variables. You can assignx = 5
without previously declaring thatx
exists. Thefor
statement just repeatedly assigns new values to the loop variable. It doesn’t care if the variable existed before the loop. It doesn’t even care if the variable is deleted inside the loop; it will just recreate it on the next iteration.
$endgroup$
– AJNeufeld
5 hours ago
add a comment
|
$begingroup$
Why is it better to test for a length of zero in the outside loop? Thanks for your help :)
$endgroup$
– cyberprogrammer
7 hours ago
$begingroup$
Also, just a question I have had for a while. Why does the iterator not have to be defined before being called? For example "item" in your loop?for item in list[:-1]:
$endgroup$
– cyberprogrammer
7 hours ago
$begingroup$
The test is more efficient outside the loop, because it is done only once, instead of dozens or possibly hundreds of times, if you are looping over dozens or hundreds of entries.
$endgroup$
– AJNeufeld
5 hours ago
1
$begingroup$
Python doesn’t declare any variables. You can assignx = 5
without previously declaring thatx
exists. Thefor
statement just repeatedly assigns new values to the loop variable. It doesn’t care if the variable existed before the loop. It doesn’t even care if the variable is deleted inside the loop; it will just recreate it on the next iteration.
$endgroup$
– AJNeufeld
5 hours ago
$begingroup$
Why is it better to test for a length of zero in the outside loop? Thanks for your help :)
$endgroup$
– cyberprogrammer
7 hours ago
$begingroup$
Why is it better to test for a length of zero in the outside loop? Thanks for your help :)
$endgroup$
– cyberprogrammer
7 hours ago
$begingroup$
Also, just a question I have had for a while. Why does the iterator not have to be defined before being called? For example "item" in your loop?
for item in list[:-1]:
$endgroup$
– cyberprogrammer
7 hours ago
$begingroup$
Also, just a question I have had for a while. Why does the iterator not have to be defined before being called? For example "item" in your loop?
for item in list[:-1]:
$endgroup$
– cyberprogrammer
7 hours ago
$begingroup$
The test is more efficient outside the loop, because it is done only once, instead of dozens or possibly hundreds of times, if you are looping over dozens or hundreds of entries.
$endgroup$
– AJNeufeld
5 hours ago
$begingroup$
The test is more efficient outside the loop, because it is done only once, instead of dozens or possibly hundreds of times, if you are looping over dozens or hundreds of entries.
$endgroup$
– AJNeufeld
5 hours ago
1
1
$begingroup$
Python doesn’t declare any variables. You can assign
x = 5
without previously declaring that x
exists. The for
statement just repeatedly assigns new values to the loop variable. It doesn’t care if the variable existed before the loop. It doesn’t even care if the variable is deleted inside the loop; it will just recreate it on the next iteration.$endgroup$
– AJNeufeld
5 hours ago
$begingroup$
Python doesn’t declare any variables. You can assign
x = 5
without previously declaring that x
exists. The for
statement just repeatedly assigns new values to the loop variable. It doesn’t care if the variable existed before the loop. It doesn’t even care if the variable is deleted inside the loop; it will just recreate it on the next iteration.$endgroup$
– AJNeufeld
5 hours ago
add a comment
|
$begingroup$
Unused import statement: that should be cleaned up.
import sys
Bad parameter name: def print_list(list):
The keyword list()
is a built-in function, you don't want your variable/parameter/function/method/class named like built-ins because later when you start relying on such keywords, this will create problems.
Example: (run this interactively)
>>> word = 'mouse'
>>> letters = list(word)
>>> letters
['m', 'o', 'u', 's', 'e']
>>> list = 5
>>> new_letters = list(word)
Troubles ...
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
list(word)
TypeError: 'int' object is not callable
I think the example is self-explanatory why you shouldn't use built-ins in your naming.
def print_list(list):
Docstrings: Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods. ... A docstring is simply a multi-line string, that is not assigned to anything. It is specified in source code that is used to document a specific segment of code. You should include a docstring to your public functions indicating what they do and type hints if necessary.
This is a bit complicated
for item in list:
if len(list) == 1:
print(list[0])
elif item != list[-1]:
print(item + ', ', end='')
else:
print('and ' + list[-1])
The whole function can be simplified and written properly:
def separate(items: list):
"""Return a string of the words in items separated by a comma."""
if len(items) > 1:
return ', '.join(items[:-1]) + ', and ' + items[-1]
if len(items) == 1:
return items[0]
if not items:
raise ValueError('Empty list')
then use if __name__ == '__main__':
guard at the end of your script which allows it to be imported by other modules without running the whole script.
if __name__ == '__main__':
spam = ['apples', 'bananas', 'tofu', 'cats']
print(separate(spam))
$endgroup$
1
$begingroup$
You get the wrong result with a list of one item. (Plus, it doesn't match the problem requirement of the final comma before "and". You have"..., tofu and cats"
instead of"..., tofu, and cats"
.)
$endgroup$
– AJNeufeld
7 hours ago
$begingroup$
Thanks for pointing this out, I'll edit the code
$endgroup$
– Emad Boctor
7 hours ago
$begingroup$
@EmadBoctor Thanks for your answer. How does the if name == 'main': work?
$endgroup$
– cyberprogrammer
7 hours ago
1
$begingroup$
You place the main guard at the end of your script and call your functions from there. And there are many cases where your module is imported by outside modules, for simplicity suppose you want to use that word separator from another script that let's say that organizes text or whatever, you will import your_script_name and use it accordingly.
$endgroup$
– Emad Boctor
7 hours ago
add a comment
|
$begingroup$
Unused import statement: that should be cleaned up.
import sys
Bad parameter name: def print_list(list):
The keyword list()
is a built-in function, you don't want your variable/parameter/function/method/class named like built-ins because later when you start relying on such keywords, this will create problems.
Example: (run this interactively)
>>> word = 'mouse'
>>> letters = list(word)
>>> letters
['m', 'o', 'u', 's', 'e']
>>> list = 5
>>> new_letters = list(word)
Troubles ...
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
list(word)
TypeError: 'int' object is not callable
I think the example is self-explanatory why you shouldn't use built-ins in your naming.
def print_list(list):
Docstrings: Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods. ... A docstring is simply a multi-line string, that is not assigned to anything. It is specified in source code that is used to document a specific segment of code. You should include a docstring to your public functions indicating what they do and type hints if necessary.
This is a bit complicated
for item in list:
if len(list) == 1:
print(list[0])
elif item != list[-1]:
print(item + ', ', end='')
else:
print('and ' + list[-1])
The whole function can be simplified and written properly:
def separate(items: list):
"""Return a string of the words in items separated by a comma."""
if len(items) > 1:
return ', '.join(items[:-1]) + ', and ' + items[-1]
if len(items) == 1:
return items[0]
if not items:
raise ValueError('Empty list')
then use if __name__ == '__main__':
guard at the end of your script which allows it to be imported by other modules without running the whole script.
if __name__ == '__main__':
spam = ['apples', 'bananas', 'tofu', 'cats']
print(separate(spam))
$endgroup$
1
$begingroup$
You get the wrong result with a list of one item. (Plus, it doesn't match the problem requirement of the final comma before "and". You have"..., tofu and cats"
instead of"..., tofu, and cats"
.)
$endgroup$
– AJNeufeld
7 hours ago
$begingroup$
Thanks for pointing this out, I'll edit the code
$endgroup$
– Emad Boctor
7 hours ago
$begingroup$
@EmadBoctor Thanks for your answer. How does the if name == 'main': work?
$endgroup$
– cyberprogrammer
7 hours ago
1
$begingroup$
You place the main guard at the end of your script and call your functions from there. And there are many cases where your module is imported by outside modules, for simplicity suppose you want to use that word separator from another script that let's say that organizes text or whatever, you will import your_script_name and use it accordingly.
$endgroup$
– Emad Boctor
7 hours ago
add a comment
|
$begingroup$
Unused import statement: that should be cleaned up.
import sys
Bad parameter name: def print_list(list):
The keyword list()
is a built-in function, you don't want your variable/parameter/function/method/class named like built-ins because later when you start relying on such keywords, this will create problems.
Example: (run this interactively)
>>> word = 'mouse'
>>> letters = list(word)
>>> letters
['m', 'o', 'u', 's', 'e']
>>> list = 5
>>> new_letters = list(word)
Troubles ...
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
list(word)
TypeError: 'int' object is not callable
I think the example is self-explanatory why you shouldn't use built-ins in your naming.
def print_list(list):
Docstrings: Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods. ... A docstring is simply a multi-line string, that is not assigned to anything. It is specified in source code that is used to document a specific segment of code. You should include a docstring to your public functions indicating what they do and type hints if necessary.
This is a bit complicated
for item in list:
if len(list) == 1:
print(list[0])
elif item != list[-1]:
print(item + ', ', end='')
else:
print('and ' + list[-1])
The whole function can be simplified and written properly:
def separate(items: list):
"""Return a string of the words in items separated by a comma."""
if len(items) > 1:
return ', '.join(items[:-1]) + ', and ' + items[-1]
if len(items) == 1:
return items[0]
if not items:
raise ValueError('Empty list')
then use if __name__ == '__main__':
guard at the end of your script which allows it to be imported by other modules without running the whole script.
if __name__ == '__main__':
spam = ['apples', 'bananas', 'tofu', 'cats']
print(separate(spam))
$endgroup$
Unused import statement: that should be cleaned up.
import sys
Bad parameter name: def print_list(list):
The keyword list()
is a built-in function, you don't want your variable/parameter/function/method/class named like built-ins because later when you start relying on such keywords, this will create problems.
Example: (run this interactively)
>>> word = 'mouse'
>>> letters = list(word)
>>> letters
['m', 'o', 'u', 's', 'e']
>>> list = 5
>>> new_letters = list(word)
Troubles ...
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
list(word)
TypeError: 'int' object is not callable
I think the example is self-explanatory why you shouldn't use built-ins in your naming.
def print_list(list):
Docstrings: Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods. ... A docstring is simply a multi-line string, that is not assigned to anything. It is specified in source code that is used to document a specific segment of code. You should include a docstring to your public functions indicating what they do and type hints if necessary.
This is a bit complicated
for item in list:
if len(list) == 1:
print(list[0])
elif item != list[-1]:
print(item + ', ', end='')
else:
print('and ' + list[-1])
The whole function can be simplified and written properly:
def separate(items: list):
"""Return a string of the words in items separated by a comma."""
if len(items) > 1:
return ', '.join(items[:-1]) + ', and ' + items[-1]
if len(items) == 1:
return items[0]
if not items:
raise ValueError('Empty list')
then use if __name__ == '__main__':
guard at the end of your script which allows it to be imported by other modules without running the whole script.
if __name__ == '__main__':
spam = ['apples', 'bananas', 'tofu', 'cats']
print(separate(spam))
edited 5 hours ago
answered 7 hours ago
Emad BoctorEmad Boctor
1,7162 silver badges23 bronze badges
1,7162 silver badges23 bronze badges
1
$begingroup$
You get the wrong result with a list of one item. (Plus, it doesn't match the problem requirement of the final comma before "and". You have"..., tofu and cats"
instead of"..., tofu, and cats"
.)
$endgroup$
– AJNeufeld
7 hours ago
$begingroup$
Thanks for pointing this out, I'll edit the code
$endgroup$
– Emad Boctor
7 hours ago
$begingroup$
@EmadBoctor Thanks for your answer. How does the if name == 'main': work?
$endgroup$
– cyberprogrammer
7 hours ago
1
$begingroup$
You place the main guard at the end of your script and call your functions from there. And there are many cases where your module is imported by outside modules, for simplicity suppose you want to use that word separator from another script that let's say that organizes text or whatever, you will import your_script_name and use it accordingly.
$endgroup$
– Emad Boctor
7 hours ago
add a comment
|
1
$begingroup$
You get the wrong result with a list of one item. (Plus, it doesn't match the problem requirement of the final comma before "and". You have"..., tofu and cats"
instead of"..., tofu, and cats"
.)
$endgroup$
– AJNeufeld
7 hours ago
$begingroup$
Thanks for pointing this out, I'll edit the code
$endgroup$
– Emad Boctor
7 hours ago
$begingroup$
@EmadBoctor Thanks for your answer. How does the if name == 'main': work?
$endgroup$
– cyberprogrammer
7 hours ago
1
$begingroup$
You place the main guard at the end of your script and call your functions from there. And there are many cases where your module is imported by outside modules, for simplicity suppose you want to use that word separator from another script that let's say that organizes text or whatever, you will import your_script_name and use it accordingly.
$endgroup$
– Emad Boctor
7 hours ago
1
1
$begingroup$
You get the wrong result with a list of one item. (Plus, it doesn't match the problem requirement of the final comma before "and". You have
"..., tofu and cats"
instead of "..., tofu, and cats"
.)$endgroup$
– AJNeufeld
7 hours ago
$begingroup$
You get the wrong result with a list of one item. (Plus, it doesn't match the problem requirement of the final comma before "and". You have
"..., tofu and cats"
instead of "..., tofu, and cats"
.)$endgroup$
– AJNeufeld
7 hours ago
$begingroup$
Thanks for pointing this out, I'll edit the code
$endgroup$
– Emad Boctor
7 hours ago
$begingroup$
Thanks for pointing this out, I'll edit the code
$endgroup$
– Emad Boctor
7 hours ago
$begingroup$
@EmadBoctor Thanks for your answer. How does the if name == 'main': work?
$endgroup$
– cyberprogrammer
7 hours ago
$begingroup$
@EmadBoctor Thanks for your answer. How does the if name == 'main': work?
$endgroup$
– cyberprogrammer
7 hours ago
1
1
$begingroup$
You place the main guard at the end of your script and call your functions from there. And there are many cases where your module is imported by outside modules, for simplicity suppose you want to use that word separator from another script that let's say that organizes text or whatever, you will import your_script_name and use it accordingly.
$endgroup$
– Emad Boctor
7 hours ago
$begingroup$
You place the main guard at the end of your script and call your functions from there. And there are many cases where your module is imported by outside modules, for simplicity suppose you want to use that word separator from another script that let's say that organizes text or whatever, you will import your_script_name and use it accordingly.
$endgroup$
– Emad Boctor
7 hours ago
add a comment
|
cyberprogrammer is a new contributor. Be nice, and check out our Code of Conduct.
cyberprogrammer is a new contributor. Be nice, and check out our Code of Conduct.
cyberprogrammer is a new contributor. Be nice, and check out our Code of Conduct.
cyberprogrammer is a new contributor. Be nice, and check out our Code of Conduct.
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f229404%2fcomma-code-automate-the-boring-stuff-with-python%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown