假如 : 给出一个真实的数字real_num= 43,
# -*- coding: UTF-8 -*-
real_num = 43
# print type(real_num)
while True:
guess_num = int(raw_input("请输入你猜的数字:"))
# print type(guess_num)
if real_num > guess_num :
print "你猜的数字比原来的小了"
elif real_num < guess_num:
print "你猜的数字比原来的大了"
else:
print "猜对了"
break
假如 : 给出一个真实的数字real_num= 43,
限定猜数字的次数 ,只能 猜3次
# -*- coding: UTF-8 -*-
real_num = 43
# print type(real_num)
retry_count = 0
# while True:
while retry_count < 3:
guess_num = int(raw_input("请输入你猜的数字:"))
# print type(guess_num)
if real_num > guess_num :
print "你猜的数字比原来的小了"
retry_count+=1
elif real_num < guess_num:
print "你猜的数字比原来的大了"
retry_count += 1
else:
print "猜对了"
break
# -*- coding: UTF-8 -*-
real_num = 43
# print type(real_num)
retry_count = 0
# while True:
while retry_count < 3:
guess_num = int(raw_input("请输入你猜的数字:"))
# print type(guess_num)
if real_num > guess_num :
print "你猜的数字比原来的小了"
elif real_num < guess_num:
print "你猜的数字比原来的大了"
else:
print "猜对了"
break
retry_count += 1
假如 : 给出一个真实的数字real_num= 43,
限定猜数字的次数 ,只能 猜3次
并且要求使用导入 random 模块,随机数模块的方式,进行猜数字
# -*- coding: UTF-8 -*-
import random
real_num = random.randrange(10)
# print type(real_num)
retry_count = 0
# while True:
while retry_count < 3:
guess_num = int(raw_input("请输入你猜的数字:"))
# print type(guess_num)
if real_num > guess_num :
print "你猜的数字比原来的小了"
elif real_num < guess_num:
print "你猜的数字比原来的大了"
else:
print "猜对了"
break
retry_count += 1
else:
print "The real num is ",real_num
while的后面有一个else语句,返回一个实际数的值
由于尝试输入非数字字符(如回车)后,代码出错!请把输入字符串中的“空格和字符串”去掉。
# -*- coding: UTF-8 -*-
import random
real_num = random.randrange(10)
# print type(real_num)
retry_count = 0
# while True:
while retry_count < 3:
guess_num = int(raw_input("请输入你猜的数字:").strip())
# print type(guess_num)
if real_num > guess_num :
print "你猜的数字比原来的小了"
elif real_num < guess_num:
print "你猜的数字比原来的大了"
else:
print "猜对了"
break
retry_count += 1
else:
print "The real num is ",real_num