![](/img/trans.png)
[英]Define a main function in python which can run other functions in python
[英]Can't run multiple functions in a main function in Python
所以我面臨的一個問題是:
我定義了 2 個函數和一個 function 使用另一個 function 的變量現在當我使用以下代碼運行它們時,它可以正常工作:
def type_anything():
use = input(">")
return use
def print_it():
print(use)
if __name__ == '__main__':
while True:
use = type_anything()
print_it()
Output:
> abcd
abcd
> efgh
efgh
> anything
anything
但是,當我決定創建一個主 function 來運行上述兩個函數,然后在“ if __name__ ==
......”行下運行主 function,如下所示:
def type_anything():
use = input("> ")
return use
def print_it():
print(use)
def run_it():
while True:
use = type_anything()
print_it()
if __name__ == '__main__':
run_it()
該程序無法正常運行,而是顯示此錯誤:
> anything
Traceback (most recent call last):
File "C:/<location>/sample.py", line 17, in <module>
run_it()
File "C:/<location>/sample.py", line 13, in run_it
print_it()
File "C:/<location>/sample.py", line 7, in print_it
print(use)
NameError: name 'use' is not defined
為什么會這樣? 我需要做什么?
您不能在另一個 function 中使用一個 function 中定義的變量。
每個 function 都需要接收它使用的 arguments。
def type_anything():
use = input(">")
return use
def print_it(use):
print(use)
if __name__ == '__main__':
while True:
use = type_anything()
print_it(use)
這應該可以解決您的問題:
def type_anything():
use = input("> ")
return use
def print_it(use):
print(use)
def run_it():
while True:
use = type_anything()
print_it(use)
if __name__ == '__main__':
run_it()
print_it
function 不知道任何變量的use
,因此會出現錯誤。
注意type_anything
function 如何returns
變量use
和print_it
function 接受一個參數然后打印它。
請不要養成使用全局變量的習慣,從長遠來看,這會破壞您編寫的所有內容。 這只是幫助您理解問題的示例!
您的問題是變量 scope。 在第一個示例中,您的變量use
是global
的,因為您在主程序中定義了它:
if __name__ == '__main__':
while True:
use = type_anything()
print_it()
它沒有在type_anything
中定義,你可以將這個變量重命名為任何東西,它仍然可以工作:
def type_anything():
x = input(">")
return x
在第二個示例中,您在 function 中定義它:
def run_it():
while True:
use = type_anything()
print_it()
您可以通過use
全局變量來解決此問題:
def run_it():
global use
while True:
use = type_anything()
print_it()
一種更好的方法
將變量use
傳遞給使用它的 function:
def print_it(use):
print(use)
def run_it():
while True:
use = type_anything()
print_it(use)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.