您的位置:首页 > 编程语言 > Python开发

Guess Number by Python

2010-10-22 14:14 357 查看
猜测一个随机数

#!/usr/bin/env python

'guessNumber.py -- my first Python : guess number'

# import random function
from random import randint

# generate a random number
number = randint(0, 100)

# set default value
counter = 0
last_num = {
"min":0,
"max":100,
}

# loop
while True:
n = int(raw_input("Enter a number between %d to %d:" % (last_num['min'], last_num['max'])))
counter += 1
if not (last_num['min'] < n < last_num['max']):
print "Invalid number. Please try again."

# jump to next loop
continue
if n == number:
print '%d times! And the number is %d' % (counter,number)
raw_input('press anykey to exit')
# finish, jump out of the loop
break
elif n < number:
last_num['min'] = n
elif n > number:
last_num['max'] = n


#! /usr/bin/env python

import sys,os
import random

def JudgeNum(num):
print '**'*10 + '**'*10
print 'The random number is', num
print 'if the random number is biger, please input [B]\n'
print 'if the random number is lesser, please input [L]\n'
print 'if the random number is equal, please input [E]\n'
choiceFlag  =  raw_input('You choice is: ').upper()
return choiceFlag

#RandomNum = random.randint(1,100)
#print 'The first random number is', RandomNum
topNum = 100
lowNum = 1

counter = 0

while True:
RandomNum = random.randint(lowNum,topNum)
#print 'The first random number is', RandomNum
choiceFlag = JudgeNum(RandomNum)
if choiceFlag == 'B':
topNum = RandomNum - 1
counter += 1
print 'topNum is: ', topNum
print 'lowNum is: ', lowNum
continue

if choiceFlag == 'L':
lowNum = RandomNum + 1
counter += 1
print 'topNum is: ', topNum
print 'lowNum is: ', lowNum
continue

if     choiceFlag == 'E':
#print 'topNum is: ', topNum
#print 'lowNum is: ', lowNum
#counter += 1
print '%d times, guess right\n' %(counter)
print 'The number ',RandomNum, ' is your want'
break

if choiceFlag != 'B' and choiceFlag != 'E' and choiceFlag != 'L':
counter += 1
print 'Wrong input value, Please try it again......'
#choiceFlag  =  raw_input('You choice is: ').upper()
continue
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: