-1

I made following functions but it generates errors when I use main functions despite no error without usage of main function

def setup_name():
    print("Before we start...","\n"
          "What is your name?")
    char_name = input("Name : ").strip().capitalize()
    return char_name

def intro():
    print(cname," is building great walls now")
    print()

cname = setup_name()
intro()

But below gives me error

def setup_name():
    print("Before we start...","\n"
          "What is your name?")
    char_name = input("Name : ").strip().capitalize()
    return char_name

def intro():
    print(cname," is building great walls now")
    print()

def main():
    cname = setup_name()
    intro()
main()

To me, it seems no difference exist here so I think i need some sharp eyes.

Thanks!

Joseph Kim
  • 21
  • 3

1 Answers1

2

cname is no longer scoped at the module level (its current scope is now function main) in the second version, so you'll get a NameError when intro tries to use cname.

You'll need to explicitly pass cname to intro, to make it work in the second version.

See Short Description of the Scoping Rules?.

Community
  • 1
  • 1
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
  • woah! The hyperlinked resource is something I haven't covered yet! Thanks for the resource and comment! it really helped me! – Joseph Kim Mar 12 '17 at 00:21