2014-12-17 2 views
0

이 내 코드입니다 -형식 오류 : 단항 +에 대한 잘못된 피연산자 유형 : 'STR'는

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' 
+4

이 인쇄에 쉼표를 혼합하지 마십시오 성명서와 당신은 잘되어야합니다. – BlackVegetable

+0

좋아요, 그럼 네 질문은 뭐니? – aestrivex

답변

2

당신은 쉼표 제거해야합니다

print("What is " +str(r1)+s1+str(r2)) 
print("What is", r1, s1, r2) 

마지막 줄 :

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

그러나 더 파이썬 방법으로 당신이 사용할 수있는 % 또는 format :

print("What is {0}{1}{2}".format(r1,s1,r2)) 

OR :

print("What is %d%s%d" % (r1,s1,r2)) 
+1

또한 마지막 줄에는 쉼표를 제거하고 더하기를 삽입해야합니다. – BlackVegetable

+0

@BlackVegetable 예, thansk, 답변에 추가합니다. – Kasramvd

2

당신은 라인을 변경해야합니다 :이이 옵션을

print("What is ",+str(r1),+s1,+str(r2),) 

    플로트
0 정수
  • %f.2위한 문자열
  • %d위한
  • print("What is "+ str(r1) + s1 + str(r2))
  • print("What is %d %s %d" % (r1,s1,r2))
  • print("What is", r1, s1, r2)

    • 그리고 당신은 또한 당신의 마지막 줄을 변경해야합니다 :

      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")
  • 관련 문제