Python 如何循环涉及列表的代码
我对python相当陌生,我想知道是否有人能帮助我循环这段代码,我过去也做过循环,但这段代码涉及一个列表元素,每次从1到10都必须更改,我不知道如何进行更改Python 如何循环涉及列表的代码,python,loops,Python,Loops,我对python相当陌生,我想知道是否有人能帮助我循环这段代码,我过去也做过循环,但这段代码涉及一个列表元素,每次从1到10都必须更改,我不知道如何进行更改 print ("Question 1: ") print (questions[0]) #asks for the answer from the user ans = int(input()) #compares the users input to the answer if ans == eval(questions[0]):
print ("Question 1: ")
print (questions[0])
#asks for the answer from the user
ans = int(input())
#compares the users input to the answer
if ans == eval(questions[0]):
print ("Well done, you got it correct")
#if correct grants a point to the overall score
score = score + 1
在维护代码时,最接近的方法是
for index, question in enumerate(questions):
print ("Question {}: ".format(index+1))
print (question)
#asks for the answer from the user
ans = int(input())
#compares the users input to the answer
if ans == eval(question):
print ("Well done, you got it correct")
#if correct grants a point to the overall score
score = score + 1
请注意,应避免使用eval
,因为它不安全。建议的替代方法是制作一本带有预先准备好的问题和答案的词典,例如
questions = {'What is 5 + 4?' : 9,
'What is 3 - 1?' : 2}
或者。你所说的“不安全”是什么意思?例如,请参阅,还有。但是如果我将其用于一个简单的程序,而该程序并不太复杂,我应该会很好,对吗?或者我在尝试扩展它时会遇到问题吗?例如,是的,你会很好,除非问题包含无效语法,这只会导致错误。在专业软件开发中,人们应该很少(如果有的话)使用
eval
。这只是为了学习,所以不用担心,非常感谢您的帮助。