Why doesn't the following allow me to use the "os" variable once it's returned by the function? The "os" module isn't being imported so that shouldn't be an issue at all. When I call the Begin() function and print the os variable after the function is finished, python says the variable is not defined.

def Begin():
    os = raw_input("Choose your operating system:\n[1] Ubuntu\n[2] CentOS\nEnter '1' or     '2': ")
    if os != '1' and os != '2':
        print "Incorrect operating system choice, shutting down..."
        time.sleep(3)
        exit()
    else:
        return os

Begin()
print os
share|improve this question
2  
please don't use os as a variable name -- it's the name of a well-known module. – nneonneo 9 mins ago

1 Answer

You have to assign the returned result to an actual variable. The os in the function exists only in the function scope, and can't be used outside of it.

result = Begin()
print result

As @nneonneo mentioned, os is a part of the standard library, and a commonly used module, and using os as a variable name will confuse a reader, and if os is imported, will overwrite it.

Another suggestion:

if os != '1' and os != '2':

can be written more succintly as

if os not in ('1', '2'):

This also makes it easier when you have more similar comparisons to make.

share
Every time I have an issue...it's a careless mistake. Thanks! – user1710563 6 mins ago

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.