我的计算机科学课正在做一个练习编程任务,我们需要创建一个程序,询问十个随机问题来测试学生的算术技巧。我为每个问题中的两个数字制作了单独的变量,并为随机操作制作了一个变量。这是我的代码,我正在使用python 3.5,我一直在收到错误。任何人都可以看到我哪里出错...我认为这是使用eval模块。
#This is where the import commands go
from random import randint
import random
#This is a set list of variables for each question (21 in total as 2 for each question and operation)
operation = ['x', '-', '+']
q1p1 = (randint(0,100))
q1p2 = (randint(0,100))
#This variable stores the users score
score = 0
#This changes the randomly generated numbers into strings, then evauates them as maths equations so it knows the answers.
#Also it stores the whole of each question as a variable, making it easier to code.
question1 = eval(str(q1p1) + operation + str(q1p2))
#This asks for the user’s name
name = input("What is your forename (With No Caps?)")
surname = input("What is your surname (With No Caps?)")
#This prints a welcome message, personalised with the user's name
print("Welcome to your test," + name)
#Information about how to answer questions
print('''Throughout your test you will be asked a series of questions.
These questions will be randomly generated and are designed to test your basic arithmetic skills.
Please enter your answers in integer form.
EG. if the question was 5 + 5, you would enter 10 with no spaces or extra characters.''')
#First question
print (question1)
answer1 = input("What is the answer to the above question?")
if (question1) == True:
print("Well done, you got it correct!")
(score) + 1
答案 0 :(得分:0)
我运行了代码并收到以下错误:
无法将'list'对象隐式转换为str
为该行:
question1 = eval(str(q1p1) + operation + str(q1p2))
操作是一个列表,您正在尝试打印字符串中的操作列表。这不会像你期望的那样工作,你需要选择一个单独的操作,例如:
question1 = eval(str(q1p1) + str(operation[2]) + str(q1p2))
我认为你的程序不像你期望的那样工作。您正在尝试创建一个问题字符串,然后检查这个“问题1”是否属实?以下是您的计划应该做的一些步骤:
检查用户输入是否与正确答案匹配
import random
operations = ['+','-','x']
operation = random.choice(operations)
number1 = random.randrange(0,10)
number2 = random.randrange(0,10)
score = 0
answer = None
if operation == '+':
answer = number1 + number2
elif operation == '-':
answer = number1 - number2
elif operation == 'x':
answer = number1 * number2
user_answer = input("What is " + str(number1) + " " + operation + " " + str(number2) + "?")
user_answer = float(user_answer)
if user_answer == answer:
print("Correct")
score = score+1
也是行
score + 1
不执行您认为的操作,它只需要得分并为其添加一个,它不会对此值执行任何操作。要提高分数,您需要将其重新分配回分数:
score = score + 1
答案 1 :(得分:0)
“x”不是python中的乘法运算符,请使用'*'
调试时,最好使用print在代码中显示有趣变量的值。
例如,当您在代码中的某一行看到错误并且您不确定原因时。尝试打印该行使用的值。
例如,将代码更改为以下内容:
print( 'eval called with', str(q1p1) + operation + str(q1p2) )
question1 = eval(str(q1p1) + operation + str(q1p2))