[英]Random Input From A List
I want to display a random input option for the user and if the condition is not met it picks another random input from the 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)
Doing this will just show each of the inputs then the choice is assigned a random answer from any of the inputs.这样做只会显示每个输入,然后从任何输入中为选择分配一个随机答案。 What I want is for choice to pick sname as it's first option and if the user's response is not smores it will randomly pick another option from clues.
我想要的是选择 sname 作为它的第一个选项,如果用户的响应不是 smores,它将从线索中随机选择另一个选项。
I used the walrus operator because I wasn't sure how I could save the input, using a normal variable just returns an error saying append does not take keyword arguments.我使用了海象运算符,因为我不确定如何保存输入,使用普通变量只会返回一个错误,说明 append 不接受关键字参数。 The walrus operator still did what I wanted by storing and returning the values I need but if anyone has a suggestion on a different approach I'm all ears.
海象操作员仍然通过存储和返回我需要的值来完成我想要的操作,但是如果有人对不同的方法有建议,我会全力以赴。
Your program already working you can use also this library in place of random.您的程序已经在运行,您也可以使用这个库来代替 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)
I think this is what you need:我认为这是你需要的:
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!')
I think this might be closer to what you're looking for.我认为这可能更接近您正在寻找的内容。 It will only show the first question, and then it will keep displaying a random question until you type "smores".
它只会显示第一个问题,然后会一直显示一个随机问题,直到您输入“smores”。 It also saves all of the answers in a dictionary where the question is the key index
它还将所有答案保存在问题是关键索引的字典中
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.