Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Mikkel Bielefeldt
Mikkel Bielefeldt
3,227 Points

Why doesn't it import variable "user_name"?

I have tried a little bit of everything. I have been searching on the internet, but couldn't really find an answer to my specific question. So I'm wondering why it won't use the "user_name" variable in function "name_information" in the "address_information" function.

import sys

def name_information():
    user_name = input("What's your name? ")

    if any(char.isdigit() for char in user_name):
        print("You can't put a number in your name.")
        sys.exit()
    else:
        pass


def address_information(user_name):
    address = input("What's your address {}".format(user_name))

    try:
        if len(address) <= 5:
            print("That's too short.")
            sys.exit()
        else:
            pass
    except ValueError:
        print("There occurred an error.")

name_information()
address_information()

1 Answer

Steven Parker
Steven Parker
229,732 Points

This is due to the concept known as "scope". Normally, a variable created inside a function is only available to other code inside that same function. From the main program, or from any other function, that variable does not exist.

If you want the variable to exist outside the function, you can put the word "global" in front of the name when you create it.