Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialadrian lineweaver
Courses Plus Student 565 PointsMy code works but is it correct?
I paused the video and created the script he described. it works perfectly but is it the correct way to write it? i see other people have something completely different. just want to know if this is acceptable
'''shopping list script'''
def myshoppingcart(on, things = []):
while on >=1:
print("Commands = [shop, DONE]")
command = input("Enter a command: ")
if command == "SHOP".lower():
putitinthecart = input("Name of item? ")
things.append(putitinthecart)
print(things)
elif command == "DONE".upper():
on -=4
print(things)
print("Checking out your Items....\nThank you have a nice day!")
on -=2
else:
print("INVALID COMMAND, PLEASE LOOK AT THE 'COMMANDS' ")
myshoppingcart(5)
1 Answer
Walker Bolger
16,798 PointsYour code does indeed work so well done on figuring it out before finishing the video! I'm a bit of a pragmatist so I'd say if it works, then it's acceptable.
One of the big lesson I've learned is to try to write as little code as possible (especially if code is going to be deployed on something with limited memory like embedded microcontrollers). One specific example is on your 'while' statement. Instead of making it based off the value of 'on,' you can change it to say "while True:". This will make the loop infinite until you choose to end it. This way you can get rid of the two lines that decrease the value of 'on' (i.e. "on -=4" and "on -=2") and simply put in "break" at the end of your 'elif' command. This also eliminates the need to pass in the 'on' variable into your 'myshoppingcart' function. In this example, the extra lines don't really add a lot but it's good practice to try to make applications as stripped down as possible. Does this make sense?
Keep up the good work!
adrian lineweaver
Courses Plus Student 565 Pointsadrian lineweaver
Courses Plus Student 565 Pointsyes it does and its exactly what i did ! thank you, i am very excited to be learning a programming language. Its so fascinating to me the things you could do on a computer. yet not many people know it!