【问题标题】:TypeError: bad operand type for unary +: 'str'TypeError:一元+的错误操作数类型:'str'
【发布时间】:2014-12-17 16:24:29
【问题描述】:

这是我的代码 -

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'

【问题讨论】:

标签: python


【解决方案1】:

你必须换行:

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 用于浮动

您还需要更改最后一行:

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")

【讨论】:

    【解决方案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))
    

    【讨论】:

    • 最后一行需要去掉逗号并插入一个加号。
    • @BlackVegetable 是的,谢谢,我添加它来回答
    猜你喜欢
    • 2013-03-28
    • 2021-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-02
    • 1970-01-01
    相关资源
    最近更新 更多