简体   繁体   中英

Python problem with TypeError: unsupported operand type(s) for +: 'int' and 'str'

I'm new to the whole programming world, I've encountered a problem with Python when doing the caesar exercise of cs50. I could not figure out what went wrong, highly appreciate your help!

from cs50 import get_string
from sys import argv

if len(argv) != 2:
    print("only input one integer")

x = argv[1]

n = get_string("plaintext: ")

for i in range(len(n)):

if str.islower(n[i]):
    lower = (((ord(n[i]) - 97 + x) % 26)) + 97
    print(chr(lower), end="")

elif str.isupper(n[i]):
    upper = (((ord(n[i]) - 65) + x) % 26) + 65
    print(chr(upper), end="")

else:
    print(f"{n[i]}", end="")

It is expected in the terminal window that:

python caesar.py 1
plaintext: hi
ij

But it says:

Traceback (most recent call last):
  File "caesar.py", line 14, in <module>
    lower = (((ord(n[i]) - 97 + x) % 26)) + 97
TypeError: unsupported operand type(s) for +: 'int' and 'str'

I think the variable x is a string. replace argv[1] with int(argv[1]) .

You are attempting to mathematically add an integer and a string, or a piece of text. That text may look like a "5" but to the computer its a character that represents a written 5, not the literal number 5. Typically when something takes user input like an input() or taking a runtime argument it defaults to taking it as type string .

you want the int() or float() functions such that x = int(argv[1]) that will turn a number in a string into an actual number. (float() for decimal point'd numbers aka "floating point") Obviously these will break if you enter something that is not meant to be a number.

The list sys.argv gives you a list of strings, and when you do x = argv[1] , x becomes a string.

Now when you try to do lower = (((ord(n[i]) - 97 + x) % 26)) + 97 , you are trying to add an integer and a string, which is not possible, so the only change you need to do in your code is to make sure the input x you are taking is a integer, which you can do by using x = int(argv[1])

So your final code becomes

from cs50 import get_string
from sys import argv

if len(argv) != 2:
    print("only input one integer")

#Changed this! Now x is an integer, since you convert the string in argv[1] to an integer
x = int(argv[1])

n = get_string("plaintext: ")

for i in range(len(n)):

    if str.islower(n[i]):
        lower = (((ord(n[i]) - 97 + x) % 26)) + 97
        print(chr(lower), end="")

    elif str.isupper(n[i]):
        upper = (((ord(n[i]) - 65) + x) % 26) + 65
        print(chr(upper), end="")

    else:
        print(f"{n[i]}", end="")

The output comes up as expected now

plaintext: hi
ij

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM