Python, help me! TypeError: unsupported operand type(s) for +: 'int' and 'str'

Asked 2 years ago, Updated 2 years ago, 18 views

numbers = (1,2,3,4,5,6,7,8,9)
for list in numbers :
    if list==1 :
        print("1" + "st")
    elif list==2 :
        print("2" + "nd")
    elif list==3 :
        print("3" + "rd")
    else :
        print(list + "th")

If you do this, TypeError: unsupported operation type(s) for +: 'int' and 'str' The corresponding error appears. Results

1st
2nd
3rd
4th
5th
6th
7th
8th
9th 

I want to make it come out like this. What should I do?

python

2022-09-21 10:21

1 Answers

int and str cannot be +.

+ is possible with the same type.

To solve this problem, there are two main solutions.

You can print it out separately, or you can transform the values in the list.

numbers = (1,2,3,4,5,6,7,8,9)
for list in numbers :
    # # print(list)
    if list==1:
        print("1", "st")
    elif list==2:
        print("2", "nd")
    elif list==3:
        print("3", "rd")
    else:
        print(list, "th")
numbers = (1,2,3,4,5,6,7,8,9)
for list in numbers :
    if list==1 :
        print("1" + "st")
    elif list==2 :
        print("2" + "nd")
    elif list==3 :
        print("3" + "rd")
    else :
        print(str(list) + "th")

The rest doesn't matter, but list + "th" is not possible in the last else statement.


2022-09-21 10:21

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.