尝试写一个猜字游戏时,使用了raw_input()作为输入。
代码如下。
think = 53guess = raw_input("Guess what I think\n") while True: if guess > think: print "It‘s too big." guess = raw_input("Guess one more time.\n") if guess < think: print "It‘s too small." guess = raw_input("Guess one more time.\n") if guess == think: print "Greet, you get it." break
运行结果:输入数字无论是否大于53,打印结果皆为 It‘s too big.
猜测可能 raw_input() 返回字符非 int
尝试使用 int() 转化为整型,修改代码如下:
think = 53 guess = int(raw_input("Guess what I think\n")) while True: if guess > think: print "It‘s too big." guess = int(raw_input("Guess one more time.\n")) if guess < think: print "It‘s too small." guess = int(raw_input("Guess one more time.\n")) if guess == think: print "Greet, you get it." break
修改后可正常运行。
网上查阅:
“
Python input和raw_input的区别
使用input和raw_input都可以读取控制台的输入,但是input和raw_input在处理数字时是有区别的
纯数字输入
当输入为纯数字时
input返回的是数值类型,如int,float
raw_inpout返回的是字符串类型,string类型
"
在输入内容为int或者float时可直接使用 input() 来接受输入,未必使用 raw_input()。
时间: 2024-12-10 10:02:58