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 trial
Antonio Rodrigues
1,218 PointsHow can I use the def function to shorten my code?
can you please show me how i could use the def function for the hello.py code.
2 Answers
Steven Parker
243,228 PointsIt might be tough to make this code more compact because strings take up most of the space, and also because of how the strings are being used in slightly different ways each time.
But if each question was always followed by a message that included the answer you could create a function to handle the basic logic and avoid repeating code. Here's an example with slightly different program operation:
def AskRespond(question, message):
answer = input(question)
print(message.format(answer))
return answer
first_name = AskRespond("what is your first name? ", "nice to meet you, {}.")
favorite_color = AskRespond("what is your favorite color? ", "the color {} is a great choice!")
if favorite_color=="blue":
AskRespond("What food do you like to eat the most? ", "I like {} also.")
else:
print("but my favorite color is blue.")
print("thank you for your time and info, and have a great day {}!".format(first_name))
wayne ross
3,225 PointsSteven is on point