1

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
1
  • 7
    please don't use os as a variable name -- it's the name of a well-known module. Commented Mar 9, 2013 at 6:55

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Every time I have an issue...it's a careless mistake. Thanks!
2

In your code os is a local variable to Begin() as suggested by @nneonneo do not use standard module names.

If you are just trying to print the value you can simply do

print Begin()

if you need to use the returned value from Begin() then assign it to a variable and you can use it further.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.