while循环加次数限制

版本一,
该版本最后加了if else 用来判断guess_count的次数,中间的‘不等于’环节代码重复了,但是理解方便。

lucky_num = 66
input_num = -1      #定义input_num ,python程序从上到下,必须先定义初始值。   
guess_count =0      #定义游戏次数
# while lucky_num != input_num:     #让幸运数字跟猜的数字不相等,只要不相等,就无限循环,相等就终止循环
while lucky_num != input_num and guess_count<3: #游戏次数要小于3次 and是并且,要同时满足两个条件
    input_num = int(input("input the guess number"))

    if (input_num > lucky_num):
        print("is bigger real number")
    elif(input_num < lucky_num):
        print("Is smaller real number")
    # guess_count=guess_count+1
    guess_count += 1
if lucky_num == input_num:      #这里加了if,else判断,用来判断竞猜次数,但是代码有重复性
    print ("bingo")
else:
    print('to many retrys')

 



版本二
lucky_num = 66
input_num = -1      #定义input_num ,python程序从上到下,必须先定义初始值。   
guess_count =0      #定义游戏次数
# while lucky_num != input_num:     #让幸运数字跟猜的数字不相等,只要不相等,就无限循环,相等就终止循环
# while lucky_num != input_num and guess_count<3: #游戏次数要小于3次 and是并且,要同时满足两个条件
while guess_count<3:    #while循环用来判断次数,内部的if,elif,else循环判断正确性
    input_num = int(input("input the guess number"))

    if (input_num > lucky_num):
        print("is bigger real number")
    elif(input_num < lucky_num):
        print("Is smaller real number")
    else:               #添加else判断,直接循环内部判断正确性
        print('bingo')
        break       #用break跳出
    # guess_count=guess_count+1
    guess_count += 1
else:
    print('to many retrys')

 



版本三

for 循环

lucky_num = 66
input_num = -1
# lucky_num != input_num and
for i in range(3):
    input_num = int(input("input the guess number"))

    if (input_num > lucky_num):
        print("is bigger real number")
    elif(input_num < lucky_num):
        print("Is smaller real number")
    else:
        print("bingo")
        break

else:
    print("too many retrys")

 




posted @ 2018-03-15 14:51  人无远虑  阅读(5212)  评论(0编辑  收藏  举报