Functions, for loops and if statments

I learned so far that a function can contain an if statement and or a for loop also. It it can even contain a for loop which have an if statement in it.
Can a for loop contain a function?
Can an if statement contain a function?
Thank you.

Sure, you can combine them however you want.
Ofcourse it should all be designed to solve whatever task you have at hand.

You can even have loops within loops (called “nesting”) and then more loops, if-statements, function calls and in the end have the thing call itself.
Which is one way to create a basic sudoku-solver. But that’s quite the advanced stuff.

1 Like

just to clarify, you saying for loops and if statements can contain function calls, but can they contain the whole function itself?
I’m just trying to distinguish what you say. thanx

They “could” contain the function OR the function call. It really depends on what you are doing. Generally you’d define the function with a name outside and then just call it.

However there are situations where you could create functions within loops or ifs.
Most notably are “nameless functions” and their variations in different languages. Those are for simple operations and can be created within a single line and used if you only need them in very specific situations and it would be a waste of names and memory to create it available for the rest of the code.

For example, imagine you got a list of x-y-coordinates as [x,y] and you want to sort them by y. You’d take a built-in sorting algorithm but that will only sort by the first value. However you could supply it with a nameless function that does nothing but take in [x,y] and returns y. This could be within an if-statement because maybe you only want to sort by y if a certain condition is true.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.