-2

Another user told me this is the more correct way to structure the functions:

A program which displays user info (name, age and address).


def details(user_age, user_name, user_address):
    print(f"{user_name} is {user_age} and lives at {user_address}.")


def main():
    user_age, user_name, user_address = int(input("Enter age: ")), input("Enter name: "), input("Address: ")

    details(user_age, user_name, user_address)


if __name__ == '__main__':
    main()

Compared to:

def details():
    print(f"{user_name} is {user_age} and lives at {user_address}.")


user_age, user_name, user_address = int(input("Enter age: ")), input("Enter name: "), input("Address: ")

details()

Is code dynamic? Are there structure changes on a per project basis? Or is the above code simply the general layout/template for functions?

1 Answers1

1

Two important "things" are different in your two code samples

  1. global variable usage
  2. importability

(1) It is almost always a bad idea to use global variables in your functions. Functions should take all external data they are going to use as parameters, and return all data they produce:

# bad
foo = 42
def add1():
    global foo
    foo += 1

# better
foo = 42
def add1(n):
    return n + 1
foo = add1(foo)

(2) Executing code in global scope (outside a function) will make that code run when you import your file in another module. You generally want to control when your code executes, so always put code into functions. Then use an if __name__ == "__main__: block to execute code when you are running one file:

# bad
foo = 42
def add1(n):
    return n + 1
foo = add1(foo)

# better
FOO = 42   # global variables should be all upper case by convention

def add1(n):
    return n + 1

if __name__ == "__main__":
    FOO = add1(FOO)
thebjorn
  • 26,297
  • 11
  • 96
  • 138