简体   繁体   中英

Using def and return in python 3

i am trying to use def and return in python 3, which will check if a number is higher than another and then return status as either True or False. However, i can't seem to make this work. When i run it, i get a nameError. The code is like this:

on_off_status=600

def Status(data):
    if data <= on_off_status:
        status = True
    elif data > on_off_status:
         status = False
    return (status)


while True:
    data=int(input("what is the status?: "))
    Status(data)

    print (status)

I want to be able to use the status as True or False in another piece of code, which comes later.

Any help is appreciated.

You forgot to receive the returned value from the function.

on_off_status = 600

def Status (data):
    if data <= on_off_status:
        status = True
    elif data > on_off_status:
        status = False
    return (status)


while True:
    data = int(input("what is the status?: "))
    status = Status(data)
    print (status)

With

data = int(input("what is the status?: "))

you assign an expression (ie the object returned by int() ) to the name data , which is created ex-novo.

You need to do the same with status and assign it the newly created object (returned by the Status function)

status = Status(data)

As with data , the line above creates the name status and makes it refer to the new object.

In your code

Status(data)

creates a new object, but it is "lost", since you do not write down where it resides, so nobody can reach it via a name (also called variable in other languages, more or less).

Then

print (status)

tries to pass an object called status to print , but such name was never assigned (ie added to the public directory of names, properly called a namespace ).

Therefore Python cannot find it and throws the nameError

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM