参考书<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: ")

最新文章

  1. SQL Server 通过备份文件初始化复制
  2. unity自定义工具
  3. js中的call与apply深入浅出
  4. _Dispose(typeinfo,pointer ); 不知道说的是什么? 感觉会有用, 留待以后研究
  5. Play Framework Web开发教程(33): 结构化页面-组合使用模板
  6. iframe父子页面互调方法和属性
  7. 201521123028 《Java程序设计》第10周学习总结
  8. python正则详解
  9. CAD 二次开发 -- 自动加载开发的DLL
  10. 一、Dev
  11. 【十】虚拟机工具 03 - jinfo命令使用
  12. hibernate---session查询
  13. 【函数】raise 函数(小窗help)
  14. CentOS 6.5环境实现corosync+pacemaker实现DRBD高可用
  15. sklearn,交叉验证中的分层抽样
  16. 苹果企业版签名分发相关问题,蒲公英签名,fir.im分发,安装ipa设置信任
  17. 如何调试makefile变量
  18. 具体解释Hibernate中cascade与inverse
  19. [Sdoi2016]齿轮
  20. C++17中那些值得关注的特性(上)

热门文章

  1. ActiveMQ入门实例Demo
  2. Theano conv2d的border_mode
  3. table表框去掉相邻的间隔
  4. Masonry tableviewCell布局(转)
  5. 生成GUID唯一值的方法汇总(dotnet/javascript/sqlserver)
  6. javascript创建多行字符串的方法(转)
  7. iOS10权限设置问题以及xcdoe8更新细节问题
  8. p/invoke碎片,对结构体的处理
  9. nginx_mysql_redis配置
  10. SQLSERVER如何使用递增排序的GUID做主键