[英]Return a non-repeating, random result from a list inside a function
我正在編寫一個Python程序,該程序可以響應請求並向用戶發出響應。 下面是兩個函數的示例。 如何在不使用全局變量的情況下執行此操作,並且仍然返回非重復的隨機響應?
# stores prior response
website_result = 'first_response.wav'
def launch_website():
# if service is offline return with default msg otherwise launch service
if is_connected() == 'FALSE':
arg = 'this_service_is_offline.wav'
return arg
else:
site = 'http://www.somesite.com'
launch_it(site)
return launch_website_response()
def launch_website_response():
# using the global variable inside function
global website_result
# possible responses
RESPONSES = ['first_response.wav', 'second_response.wav', 'third_response.wav']
# ensures a non-repeating response
tmp = random.choice(RESPONSES)
while website_result == tmp:
tmp = random.choice(RESPONSES)
website_result = tmp
return website_result
您的website_result
變量表示您具有某種持久狀態。 也許您可以考慮將其存儲在文本文件中,並在每次需要時進行訪問,然后進行更改(如果您不必對其進行太多調用,則可以使用此方法,否則會遇到I / O限制)。
我不知道您的應用程序的詳細信息,但是可能會發生,您還可以使兩個函數都將website_result
作為@JGut建議的參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.