这是我的代码 -
import random
symbols=["+","-","x"]
question=0
score=0
choice=0
name=input("What is your name?")
while question<10:
r1=random.randint(1,10)
r2=random.randint(1,10)
s1=random.choice(symbols)
add=(r1+r2)
sub=(r1-r2)
times=(r1*r2)
print("What is ",+str(r1),+s1,+str(r2),)
ask=int(input())
if s1=="+":
if ask==add:
print("Correct")
score=score+1
else:
print("Incorrect")
if s1=="-":
if ask==sub:
print("Correct")
score=score+1
else:
print("Incorrect")
if s1=="x":
if ask==sub:
print("Correct")
score=score+1
else:
print("Incorrect")
print("Your score is: "+score,"out of 10")
我得到的错误是 -
What is your name?Emma
Traceback (most recent call last):
File "C:/Users/Emma/Documents/Python/Questions Maths.py", line 14, in <module>
print("What is ",+str(r1),+s1,+str(r2),)
TypeError: bad operand type for unary +: 'str'
答案 0 :(得分:2)
您需要删除逗号:
print("What is " +str(r1)+s1+str(r2))
print("What is", r1, s1, r2)
同样在最后一行:
print("Your score is: " + score + "out of 10")
但作为一种更加pythonic的方式,您可以使用%
或format
:
print("What is {0}{1}{2}".format(r1,s1,r2))
或者:
print("What is %d%s%d" % (r1,s1,r2))
答案 1 :(得分:2)
你必须改变这一行:
print("What is ",+str(r1),+s1,+str(r2),)
这两个选项
print("What is "+ str(r1) + s1 + str(r2))
print("What is %d %s %d" % (r1,s1,r2 ))
print("What is", r1, s1, r2)
%s
表示字符串%d
表示整数%f.2
for float 你还需要改变你的最后一行:
print("Your score is: "+score,"out of 10")
有:
print("Your score is: "+ score +" out of 10")
print("Your score is: %s out of 10" % score)
print("Your score is:", score, "out of 10")