pythonoperands

TypeError: bad operand type for unary +: 'str' python


number=int(input("Please enter a number:     "))

for b in range(1,11):
    b=int(b)
    output=int (number) *int (b)
    print(+str (b) +" times "+ str (number) +" is " +output)

I want the program to ask for a number and then print its times table up to 10*number, however I keep getting this error. BTW, I'm doing GCSE computing.

Traceback (most recent call last):
File "C:\Users\jcowp_000\Documents\School\Lutterworth\Computing\Documents_-_-___________---________---______-_-_-_-__-__\Python\Python manual tasks.py", line 21, in <module>
print(+str (b) +" times "+ str (number) +" is " +output)
TypeError: bad operand type for unary +: 'str'

Solution

  • I think this is what you're trying to do:

    number = int(input("Please enter a number:     "))
    
    for b in range(1,11):
        output = int(number) * b   # b is already an int, you can use it directly in computations
        print(str(b) + " times " + str(number) + " is " + str(output))
    

    Note that +str(b) is incorrect syntax, and also note you cannot concatenate " is", which is a str, with output, which is an int.