This is an exercise in the Automate The Boring Stuff book. I am supposed to create a function that takes a list value 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. My code also includes a loop for the user to create their list.
def add_and(alist):
if ((alist != []) & (len(alist) > 2)):
for item in alist[:-1]:
print(item + ", ",end="")
print("and", alist[-1])
elif ((alist != []) & (len(alist) == 2)):
print(alist[0], "and", alist[1])
elif ((alist != []) & (len(alist) == 1)):
print(alist[0])
else:
print("")
your_list = []
while True:
print("Enter An Item or nothing")
item = input()
if ((item) == ""):
print("")
break
else:
your_list.append(item)
continue
add_and(your_list)
I know that the code works, but I was wondering if there were any faux-pas that I am implementing, or if there is anything I could obviously do to make it cleaner. Thanks!
1 Answer 1
- Don't surround sub-predicates or predicates with parens when that isn't needed
- Use logical
and
rather than binary&
- Use
join
rather than afor
-and-concatenate - Factor out common sub-predicates for your list emptiness checks into an outer
if
- Don't
else
-after-break
- No need to continue
- Gather your input in a separate function
- Do not leave the
input
prompt blank
Suggested:
def and_add(alist):
if len(alist) > 1:
print(', '.join(alist[:-1]), 'and', alist[-1])
elif len(alist) == 1:
print(alist[0])
else:
print('')
def get_input():
while True:
item = input('Enter an item or nothing: ')
if not item:
return
yield item
and_add(list(get_input()))
-
\$\begingroup\$ Thanks! Why can't you else-after-break? \$\endgroup\$Nick– Nick2020年12月12日 20:45:22 +00:00Commented Dec 12, 2020 at 20:45
-
2\$\begingroup\$ You can, it's just redundant. \$\endgroup\$Reinderien– Reinderien2020年12月12日 20:45:43 +00:00Commented Dec 12, 2020 at 20:45
return
, the middle one would need modification, but could also be replaced. But the first two cannot be. You can only return from a function once, not multiple time in a loop; the firstreturn
executed terminates the function. \$\endgroup\$