input函数出现的问题(Python)
参考书<A Learner's Guide to Programming Using the Python Language>,写下如下的程序:
1 # coding=utf-8 2 # 以上是为了能在文中添加中文的注释 3 4 def save_transaction(price, credit_card, description): 5 file = open("transaction.txt", "a") 6 file.write("%s%07d%16s\n" % (credit_card, price, description)) 7 file.close() 8 9 items = ["DONUT","LATTE","FILTER","MUFFIN"] 10 prices = [1.50, 2.0, 1.80, 1.20] 11 running = True 12 13 while running: 14 option = 1 15 for choice in items: 16 print(str(option) + "." + choice) 17 option = option + 1 18 19 print(str(option) + ".Quit") 20 21 choice = int(input("Choose an option: ")) 22 if option == choice: 23 running = False 24 else: 25 #用input的话,如果是以0开始的字符串的话,就会报错 26 credit_card = input("Credit card number: ") 27 while len(credit_card) != 16 : 28 credit_card = input("the length of credit card number must be equal to 16. Please input Credit card number again: ") 29 save_transaction(prices[choice-1]*100, credit_card, items[choice-1])
但是,在运行到第26行的时候,如果输入“0987648900804387”时,会出现如下的错误:
Traceback (most recent call last): File "transaction.py", line 26, in <module> credit_card = input("Credit card number: ") File "<string>", line 1 0987648900804387 ^ SyntaxError: invalid token
上网查了下,注意到一个细节:
input其实是通过raw_input来实现的,原理很简单,就下面一行代码:[参考 http://www.cnblogs.com/linlu11/archive/2009/11/25/1610830.html]
def input(prompt): return (eval(raw_input(prompt)))
那么,简单写了测试函数:
>>> eval("0123") 83 >>> eval("0987") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<string>", line 1 0987 ^ SyntaxError: invalid token >>> eval("0x9d") 157 >>> eval("0x9h") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<string>", line 1 0x9h ^ SyntaxError: unexpected EOF while parsing
可见,在input函数中,调用eval时候,会根据字符串中的第一个或者前2个字符来判断字符串对应是8进制还是16进制的,
如果是0,就是按照8进制来处理:所以上面的输入是 0987648900804387 非法的,不是一个有效的8进制数;
如果是0x,就按照16进制来处理,所以0x9h也是非法的。
因此,原程序中的第26行到28行,可以换成:
1 credit_card = raw_input("Credit card number: ") 2 while len(credit_card) != 16 : 3 credit_card = raw_input("the length of credit card number must be equal to 16. Please input Credit card number again: ")