python的新手遇到不支持的操作数类型的问题?

时间:2015-10-13 09:11:37

标签: python

我继续在我的代码中出现此错误并且不确定如何修复它,我尝试将key和num转换为整数以尝试修复它但它不起作用。 感谢

代码:

m = "hi"
key = input("What is the key: ")
while len(key) < 0:
    print("Please enter a key")
    key = input("What is the key: ")
    key=int(key)

print (key, m)

def encrypt(m, key):
    translated=''
    for symbol in m:
         if symbol.isalpha():
             num = ord(symbol)
             print (num)
             num = num+ key
print(encrypt(m, key))

当我运行代码时,我得到了这个:

What is the key: 3
3 hi
104
Traceback (most recent call last):
  File "C:/Users/anon/Documents/test2.py", line 17, in <module>
    print(encrypt(m, key))
  File "C:/Users/anon/Documents/test2.py", line 16, in encrypt
    num = num+ key
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> 

1 个答案:

答案 0 :(得分:0)

查看代码的这一部分:

key = input("What is the key: ")
while len(key) < 0:
    print("Please enter a key")
    key = input("What is the key: ")
    key=int(key)

如果key小于0,则while循环将运行,key将转换为int

但如果key不小于0,则会跳过while循环。 key=int(key)将无法运行,因此key仍为str

你不能做str() + int()之类的事情。如果你这样做,那么Python会引发你所拥有的TypeError,因为它们是不同的类型。所以Python并不了解你在做什么。我想你知道的。

顺便说一下,如果用户没有输入数字(例如,一个单词),那么int()函数将会引发ValueError: invalid literal for int() with base 10

所以最好的方法是使用try...except来捕获此错误并告诉用户输入这样的数字:

while True:
    try:
        key = int(input("What is the key: "))
        break # if 'int' raise an error, `break` will not run so the loop will not break.
    except ValueError:
        print('please enter a key')
相关问题