[英]How to define a function in Python properly?
好吧,我正在按照教程編寫此模擬,最后,我在錯誤中得到了這個(這些是一些變量):
num_cashiers, num_servers, num_ushers = get_user_input() NameError: name 'get_user_input' 未定義
當我在 class 中將其定義為 function 時,所有內容都寫入其中。 幫助!
這是一些代碼:
def get_user_input():
num_cashiers = input("Enter no. of cashiers working: ")
num_servers = input("Enter no. of servers working: ")
num_ushers = input("Enter no. of ushers working: ")
# Now, brace yourself! Do try to understand this stuff
if all(str(i).isdigit() for i in params): # Check if input is valid
params = [int(x) for x in params]
else:
print("Could not parse input. The simulation will use default values: ",
"\n1 cashier, 1 server, 1 usher")
params = [1, 1, 1]
return params
def main():
# Setup
random.seed(42)
num_cashiers, num_servers, num_ushers = get_user_input()
# Run the Simulation
env = simpy.Environment()
env.process(run_theater(env, num_cashiers, num_servers, num_ushers))
env.run(until=90)
# View the results
mins, secs = get_average_wait_time(wait_times)
print(
"Running simulation...",
f"\nThe average wait time is {mins} minutes and {secs} seconds.",
)
if __name__ == '__main__':
main()
實際上,您的腳本中存在縮進錯誤。 正確一個
def get_user_input():
num_cashiers = input("Enter no. of cashiers working: ")
num_servers = input("Enter no. of servers working: ")
num_ushers = input("Enter no. of ushers working: ")
.......
你的縮進不正確。
def get_user_input():
num_cashiers = input("Enter no. of cashiers working: ")
num_servers = input("Enter no. of servers working: ")
num_ushers = input("Enter no. of ushers working: ")
# Now, brace yourself! Do try to understand this stuff
if all(str(i).isdigit() for i in params): # Check if input is valid
params = [int(x) for x in params]
else:
print("Could not parse input. The simulation will use default values: ",
"\n1 cashier, 1 server, 1 usher")
params = [1, 1, 1]
return params
def main():
# Setup
random.seed(42)
num_cashiers, num_servers, num_ushers = get_user_input()
# Run the Simulation
env = simpy.Environment()
env.process(run_theater(env, num_cashiers, num_servers, num_ushers))
env.run(until=90)
# View the results
mins, secs = get_average_wait_time(wait_times)
print(
"Running simulation...",
f"\nThe average wait time is {mins} minutes and {secs} seconds.",
)
if __name__ == '__main__':
main()
我還想提醒您,如果您運行此代碼,您將收到一條錯誤消息
UnboundLocalError:分配前引用的局部變量“params”
因為您甚至在聲明它之前就使用了params
好的,您應該首先分配參數,然后檢查用戶輸入是否正確,如下所示:
def get_user_input():
num_cashiers = input("Enter no. of cashiers working: ")
num_servers = input("Enter no. of servers working: ")
num_ushers = input("Enter no. of ushers working: ")
params = [num_cashiers,num_servers, num_ushers] # <------ I've added this line
if all(str(i).isdigit() for i in params):
params = [int(x) for x in params]
else:
print("Could not parse input. The simulation will use default values: ",
"\n1 cashier, 1 server, 1 usher")
params = [1, 1, 1]
return params
當然,你的縮進是不正確的。 我希望你知道
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.