0

In C language Ive learned that we can write function prototype (the function declaration with ';' in the end) so we can write the main function before the functions definition

#include <stdio.h>
int addNumbers(int a, int b);         // function prototype

int main()
{
    int n1,n2,sum;

    printf("Enters two numbers: ");
    scanf("%d %d",&n1,&n2);

    sum = addNumbers(n1, n2);        // function call
    printf("sum = %d",sum);

    return 0;
}

int addNumbers(int a, int b)         // function definition   
{
    int result;
    result = a+b;
    return result;                  // return statement
}

Can I do something similar in python, I like the structure that we have all function declaration on top, then the main function , and below the functions definitions

int addNumbers(int a, int b)         // function prototype

def main():
    addNumbers(1,2)

if __name__ == "__main__":
    main()

int addNumbers(int a, int b):         // function definition   
    result = a+b
    return result                  // return statement

ill be glad for help

I tried this but it didn't wortk- couldn't find a relevant answer on the internet

def print() -> int:

def main():
    print()

if __name__ == "__main__":
    main()
def print ()->int:
    print("Hello")
    return 1
Barmar
  • 741,623
  • 53
  • 500
  • 612
Joav
  • 1
  • 1
    This is not supported because it isn't necessary for typical use cases. – Michael Butscher Oct 31 '22 at 14:10
  • 1
    This already has a good dicussion abou the topic https://stackoverflow.com/questions/1590608/how-do-i-forward-declare-a-function-to-avoid-nameerrors-for-functions-defined – Fra93 Oct 31 '22 at 14:11
  • 1
    In 99.999% of cases `if __name__ == '__main__'` is the last thing in the file anyway. – bereal Oct 31 '22 at 14:11
  • 1
    You don't *need* to forward-declare functions in Python because the references to them aren't evaluated until they're actually called. Also, you shouldn't define a function that shadows the name of a builtin function, **especially one you use inside that same function**. – Samwise Oct 31 '22 at 14:12
  • But if you really want something that mimics C-style headers for the purposes of separating interface from implementation, check out [`typing.Protocol`](https://peps.python.org/pep-0544/). – Samwise Oct 31 '22 at 14:13

0 Answers0