2012-02-20 76 views
0

所以我的代码:Python的类型错误

intex = input("Enter in a letter of text\n") 
if intex == 'a' or 'b' or 'c' or 'd' or 'e' or 'f' or 'g' or 'h' or 'j' or 'k' or 'l' or 'm' or 'n' or 'o' or 'p' or 'q' or 'r': 
    counter += intex 
    print(counter) 

顺便说一句,所有的字母都定义,我只是不认为这是neccessary把他们在,(A = 1,B = 2等)但每当我运行的代码,它给了我错误TypeError: unsupported operand type(s) for +=: 'int' and 'str'

我知道这个错误意味着,我不能添加一个字母数字,但有没有办法做到这一点没有错误?我试过float(),但那给了我另一个错误!请帮忙!

+0

'INTEX == 'a' 或 'b' 或“c''你怎么看这个呢?你能解释这段代码吗?它不像我见过的任何Python。 – 2012-02-20 19:57:17

+0

'计数器+ =输入“( '输入文字\ n信')abcdefghijklmnopqr'' – 2012-02-20 20:03:01

+0

什么是'counter'计数?你将如何使用它? – 2012-02-20 20:04:29

回答

7

or操作不工作,你的思考方式。表达a or b返回a如果它有一个trucy truth value,并b否则。你大概的意思

if intex in "abcdefghijklmnopqr": 
    ... 

以信为整数转换,使得a映射到1等,你可以使用ord()

counter += ord(intex) - ord("a") + 1 
+0

给了我这个错误类型错误:奥德()预期的字符,但长度为0的字符串中发现 – Billjk 2012-02-20 19:57:02

+0

@SolomonWise:我添加更多的信息 - 答案原本只由第一部分或'或'的。 – 2012-02-20 20:02:44

+0

谢谢,但我做什么,如果用户输入b或c或d ... – Billjk 2012-02-20 20:12:35

4
if intex == 'a' or 'b' or 'c' 

应改为intex == 'a' or intex == 'b' ...

一种更容易这样做的方法是使用in运算符。 我只能假设你想要这样的东西来存储值的地方。

my_list = [] 
if ord(intex) >= ord("a") and ord(intex) <=ord("r"): 
    my_list.append(ord(intex)) 

你能指定代码应该做什么吗?它看起来很奇怪。

+1

这给了我错误ValueError异常:无效的基数为10字面INT():“A” – Billjk 2012-02-20 20:02:16

+0

对不起,不知道我在想什么。你想做什么?你的代码没有多大意义。你为什么要将字符串添加到计数器? – 2012-02-20 20:03:02

+0

我将字母转换为数字 – Billjk 2012-02-20 20:03:43