[英]Random Input From A List
我想為用戶顯示一個隨機輸入選項,如果不滿足條件,它會從列表中選擇另一個隨機輸入。
import random
choice = ''
clues = []
clues.append(fname:= input('What is your first name? '))
clues.append(residence:= input('Where do you live? '))
clues.append(sname:= input('What is your surname? '))
while choice != 'smores':
choice = random.choice(clues)
這樣做只會顯示每個輸入,然后從任何輸入中為選擇分配一個隨機答案。 我想要的是選擇 sname 作為它的第一個選項,如果用戶的響應不是 smores,它將從線索中隨機選擇另一個選項。
我使用了海象運算符,因為我不確定如何保存輸入,使用普通變量只會返回一個錯誤,說明 append 不接受關鍵字參數。 海象操作員仍然通過存儲和返回我需要的值來完成我想要的操作,但是如果有人對不同的方法有建議,我會全力以赴。
您的程序已經在運行,您也可以使用這個庫來代替 random。
import secrets
choice=""
clues = []
clues.append(fname:= input('What is your first name? '))
clues.append(residence:= input('Where do you live? '))
clues.append(sname:= input('What is your surname? '))
while choice != 'smores':
choice = secrets.choice(clues)
print(choice)
我認為這是你需要的:
import random
questions = ['What is your first name?', 'Where do you live?', 'What is your surname?']
choice = input(random.choice(questions))
while choice != 'smores':
choice = input(random.choice(questions))
else:
print('thank you for right answer!')
我認為這可能更接近您正在尋找的內容。 它只會顯示第一個問題,然后會一直顯示一個隨機問題,直到您輸入“smores”。 它還將所有答案保存在問題是關鍵索引的字典中
import random
questions = [
'What is your first name? ',
'Where do you live? ',
'What is your surname? '
]
answers = {}
question = questions[0]
answer = input(question)
while answer != 'smores':
answers[question] = answer
question = random.choice(questions)
answer = input(question)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.