我創建了這個函式并想呼叫回傳的結果,但是我不確定如何取回變數。如果可能的話,如果用戶鍵入 n,我還希望彈出一條不同的訊息。有人可以幫忙嗎?
def give_entertainment():
random_form_of_entertainment = random.choice(form_of_entertainment)
good_user_input = "y"
while good_user_input == "y":
user_input = input(f"We have chosen {random_form_of_entertainment} for your entertainment! Sound good? y/n: ")
if good_user_input != user_input:
random_form_of_entertainment = random.choice(form_of_entertainment)
continue
else:
print("Awesome! Glad we got that figured out. Your trip is all planned! ")
return random_form_of_entertainment
uj5u.com熱心網友回復:
x = give_entertainment()
應該將函式的回傳值存盤到x.
和:
print(x)
您應該看到存盤在x變數中的內容。
uj5u.com熱心網友回復:
在將方法分配給變數時呼叫該方法。
some_var = your_method()
現在這個some_var變數有回傳值。
uj5u.com熱心網友回復:
我個人會為此使用遞回函式,我使它適用于 y/n/invalid_input 案例。此外,無效輸入不會更新 random_form_of_entertainment,因此用戶必須說 y 或 n 才能更改。我希望這就是你要找的!
def give_entertainment():
random_form_of_entertainment = random.choice(forms_of_entertainment)
good_user_input = "y"
bad_user_input = "n"
invalid_input = True
while invalid_input:
user_input = input(f'We have chosen {random_form_of_entertainment} for your entertainment! Sound good? y/n: ')
if user_input == good_user_input:
print("Awesome! Glad we got that figured out. Your trip is all planned for!")
return random_form_of_entertainment
elif user_input == bad_user_input:
print("Sorry to hear that, let me try again...")
return give_entertainment()
else:
print("I don't recognize that input, please try again.")
continue
chosen_result = give_entertainment()
print(f'You chose {chosen_result}!')
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/474871.html
