Joseph Kim Joseph Kim - 1 year ago 47
Python Question

without def main() = O, with def main() = X

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!

Answer Source

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 Scoping Rules.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download