#๐Ÿ”’ How do you decide to create a function?

13 messages ยท Page 1 of 1 (latest)

pastel igloo
#

For example, I'm going to do a random walk with the Turtle module. I also want a random color for each move.

Should I put all that into one function? Or do I have one function to move the turtle and then another to change the color?

Actually this example isn't too good but I just want to know how programmers decide that a function is neccessary rather than just a loop.

balmy coralBOT
#

@pastel igloo

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

weak pollen
#

Generally, split off code into its own function once you identify that the code is doing a single task and has discrete input/output.

#

Also, if you're using the same code in multiple places, wrapping the code in a function is often better than copying and pasting the code around.

pastel igloo
weak pollen
#

Functions calling other functions is extremely common.

pastel igloo
#

is it common to have functions with just one line of code in them?

weak pollen
#

Functions can do more than one thing. You'll often have procedure functions whose entire purpose is to run a bunch of other functions in a certain order. Almost every program will have at least one procedure function (like a main).

weak pollen
# pastel igloo is it common to have functions with just one line of code in them?

That's a little small. I've certainly written functions like that, but you shouldn't overuse functions. Wrapping obscure code in a function can allow you to "name" that code and abstract away how it works. Creating too many such functions though just hides how the code works since readers need to go into a ton of functions just to understand what's going on

balmy coralBOT
#
Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.