TypeError:一元+的错误操作数类型:' str'

时间:2014-12-17 16:24:30

标签: python

这是我的代码 -

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'

2 个答案:

答案 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),)

这两个选项

  1. print("What is "+ str(r1) + s1 + str(r2))
  2. print("What is %d %s %d" % (r1,s1,r2 ))
  3. print("What is", r1, s1, r2)

    • %s表示字符串
    • %d表示整数
    • %f.2 for float
  4. 你还需要改变你的最后一行:

    print("Your score is: "+score,"out of 10")
    

    有:

    1. print("Your score is: "+ score +" out of 10")
    2. print("Your score is: %s out of 10" % score)
    3. print("Your score is:", score, "out of 10")