参考书<A Learner's Guide to Programming Using the Python Language>,写下如下的程序:
# coding=utf-8
# 以上是为了能在文中添加中文的注释 def save_transaction(price, credit_card, description):
file = open("transaction.txt", "a")
file.write("%s%07d%16s\n" % (credit_card, price, description))
file.close() items = ["DONUT","LATTE","FILTER","MUFFIN"]
prices = [1.50, 2.0, 1.80, 1.20]
running = True while running:
option = 1
for choice in items:
print(str(option) + "." + choice)
option = option + 1 print(str(option) + ".Quit") choice = int(input("Choose an option: "))
if option == choice:
running = False
else:
#用input的话,如果是以0开始的字符串的话,就会报错
credit_card = input("Credit card number: ")
while len(credit_card) != 16 :
credit_card = input("the length of credit card number must be equal to 16. Please input Credit card number again: ")
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 1987648900804387
^
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("")
83
>>> eval("")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1987
^
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行,可以换成:
credit_card = raw_input("Credit card number: ")
while len(credit_card) != 16 :
credit_card = raw_input("the length of credit card number must be equal to 16. Please input Credit card number again: ")
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)