1、习题35,做加分练习,判断输入是否为数字。
- 需要修改地方:原来gold_room对输入判断有不是很好,只对还有0和1的数字(其实应该是字符)进行判断,如下。所以我要修改能对整数进行判断。
def gold_room():
print "this room is full of gold.how much do you take?"
next = raw_input(">")
if "0" in next or "1" in next:
how_much = int(next)
if isinstance(next,(int,long,float)):
if next.isdigit():
how_much = int(next)
else:
dead("man,learn to type a number.")
if how_much < 50:
print "nice,you're not greedy,you win!"
exit(0)
else:
dead("you greedy bastard!")
- 选个能判断输入是否为整数的函数。
两个,
type(num):可以获得num的类型
if isinstance(num,int):判断num是否为整型数字,是输出true,反之false
if a.isdigit():判断a是否为整型数字。 - 遇到问题:不管输入什么都是输出else的语句,即判断结果输入不是数字。

提前给a赋值5,输出就是正常的

- 最终找到原因:


所以也就是说,raw_input输入默认的格式是str,所以if a.isdigit()都是fault,所以直接执行else。
python2.x版本中有两个输入函数input()和raw_input(),input()输入实数时,它的值就是实数;而raw_input()不管输入的是什么,它的值都是string,所以需要用eval()函数将值转换为实数
- 具体解决方法。
第一,把raw_input()改成input()即可。
第二,用下面方法也可以。
a = raw_input(">")
if type(eval(a)) is int:
print "yes"
else:
print "no"
def gold_room():
print "this room is full of gold.how much do you take?"
next = raw_input(">")
# if "0" in next or "1" in next:
# how_much = int(next)
if isinstance(next,(int,long,float)):
# if type(eval(a)) is int:
# if next.isdigit():
how_much = int(next)
else:
dead("man,learn to type a number.")
if how_much < 50:
print "nice,you're not greedy,you win!"
exit(0)
else:
dead("you greedy bastard!")
网友评论