python loop function in cs

Question:

description: Python can loop functions in eachother. can cS loop function too?

Example python:

def func():
   x=input(">")
   func()

Example c# expected:

namespace f
{class f{
   static void main(string[] args){
      void stuff() {
         Console.readLine()
         stuff()
      }
   }
}}

i dont think its possible to loop function in the function in cs.

what i mean by looping function is by putting the void inside the container. here is what i mean python:

def g():
   x=input(">")
   g()

output (typer):

Python Latest Update
>h
>bruh
>new line
>new new line
>line
>infinite input lines
> repeating function

i use this because in python i added commands in the script and i do it so i wont need to retype until the python stops the input.

example:

Problem (python script):
def func():
   x=input(">")
   if x=="help":
      print("commands: help")
      x=input(">")
      if x=="help":
         #repeat

Solution (python script):
def func():
   x=input(">")
   if x=="help":
      print("commands: help")
      func()

why i put the examples in python script: idk if you can do this in c# so im not going to confuse anyone

Can this happen in C#?

Asked By: jxon

||

Answers:

I’m not familiar with C# but hopefully this page can help Recursive Function C#

What you’re trying to make is called a recursive function

Answered By: CharlieBONS

Every modern language supports recursion. The problem in your example was you had a nested function, which C# doesn’t do. You’d write it like this:

namespace f {
  class f{
    static void stuff() {
      Console.readLine();
      stuff();
    }
    static void main(string[] args){
      stuff();
    }
  }
}

But I want to reiterate that this is poor practice. There are some languages in which the compiler can catch this "tail recursion" and optimize for it, turning it into a "jump" that doesn’t use stack space. Python and C# do not do that.

The proper way is just:

namespace f {
  class f{
    static void stuff() {
      while( 1 ) {
        Console.readLine();
      }
    }
    static void main(string[] args){
      stuff();
    }
  }
}

Ordinarily, you would have some condition inside the loop signalling it was time to end, and you’d do a break to stop the loop.

Answered By: Tim Roberts
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.