[英]Using def and return in python 3
我正在嘗試使用def並在python 3中返回,它將檢查一個數字是否大於另一個,然后返回狀態為True或False。 但是,我似乎無法使這項工作。 當我運行它時,我得到一個nameError。 代碼是這樣的:
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)
我希望能夠在以后的另一段代碼中使用狀態為True或False。
任何幫助表示贊賞。
您忘記了從函數接收返回的值。
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)
用
data = int(input("what is the status?: "))
您可以將表達式(即,由int()
返回的對象)分配給名稱data
,該名稱是ex-novo創建的。
您需要對status
進行相同的操作,並將其分配給新創建的對象(由Status
函數返回)
status = Status(data)
與data
,上面的行創建名稱status
並使其引用新對象。
在你的代碼中
Status(data)
創建一個新對象,但是它是“丟失的”,因為您沒有寫下它的位置,因此沒有人可以通過名稱(在其他語言中也稱為變量,或多或少)來訪問它。
然后
print (status)
嘗試傳遞一個名為status
的對象進行print
,但是從未分配過這樣的名稱(即,添加到名稱的公共目錄中,正確地稱為namespace
)。
因此,Python無法找到它並拋出nameError
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.