python - 循环出错,导致测验的数学查询重复自身

标签 python math error-handling

我有一段代码基本上是一个测验。我有错误处理,所以如果有人按了一个字母或数字以外的任何东西,它会继续进行测验,而不是让这个人尝试另一个问题。 (例如,如果第 5 题是 2+3 而他们输入了 t,那么它会继续进行并且不会给他们第 5 题的不同问题)。 我试图更新编码,所以它会循环:

def random_question():#defines function to get random question
count = 0#equates count to 0
for number in range (0,10):#makes the code generate the question 10 times
    try:#the code makes it so the computer tries one thing and is the beggining
        questionList = [random_sum,random_subtraction,random_times]#puts functions in a list to be called on
        randomQuestion = random.choice(questionList)#calls on the list to generate the random questions
        randomQuestion()#calls on variable
        except ValueError:#if there is a value error or a type error it will notice it and try to stop it
            print ("Please enter a number")#prints out the statement if there is a type error or a value error
            else:
                break
random_question()#calls on the function random_question

但是,它会出现语法错误,并突出显示 ValueError 旁边的“except”部分。

任何关于为什么会这样的帮助将不胜感激。

最佳答案

您的 except 语句应与 try 语句具有相同的缩进。在您的示例代码中,它缩进了一个额外的制表符,这会导致该错误。

Python 非常重视缩进,它通常是罪魁祸首。我不清楚您的 def 行是否是占位符或者此代码是否是其中的一部分,但如果此代码是函数定义的一部分,您还有其他缩进问题需要担心。

我建议仔细检查并确保一切都正确排列。基本的经验法则是,如果某物是另一物的一部分,则在其下方缩进。

def something():
    step 1
    step 2
    if (condition):
        the true thing
    else:
        the false thing
    while (something):
        repeat something
this is not part of the function anymore

关于python - 循环出错,导致测验的数学查询重复自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36282383/

相关文章:

python - 使用 aplay 通过 python 脚本中的子进程播放声音

python - 配置返回代码 256 - python setup.py egg_info 失败,错误代码为 1 in/tmp/pip_build_root/lxml

mysql - SQL查询以获取设定时间段的平均值

asp.net - 当 UnitOfWork 是整个请求时,如何最好地通知用户 NHibernate 异常?

Python 列表超出范围

python - 为什么在 python 中搜索排序列表需要更长的时间?

c# - 给定总数,确定一个值将进入其中的次数

c# - 在贝塞尔曲线的平行线中检测到 "Kinks"

error-handling - 处理未知的网络协议(protocol)

java - 为什么这似乎没有初始化