python while循环 我希望限制他的循环次数 例如只循环3次 改怎么修改

import random
secret = random.randint(1,20)
print('---自己测试---')
temp = input('guess the number:')
guess = int(temp)
while guess != secret:
if guess > secret:
print('too big')
else:
print('too small')
temp = input('try again:')
guess = int(temp)

if guess == secret:
print('bingo')
print('game over')

import random

secret = random.randint(1,20)

count = 1

print('---自己测试---')

temp = input('guess the number:')

guess = int(temp)

while guess != secret or count > 3:

        if guess > secret:

             print('too big')

        else:

             print('too small')

        temp = input('try again:')

        guess = int(temp)

        count += 1

if guess == secret:        

    print('bingo')            

    print('game over')

扩展资料: 

while循环的语法是:while(Boolean_expression)  {  //Statements  }。

在执行时,如果布尔表达式的结果为真,则循环中的动作将被执行。这将继续下去,只要该表达式的结果为真。 在这里,while循环的关键点是循环可能不会永远运行。当表达式进行测试,结果为 false,循环体将被跳过,在while循环之后的第一个语句将被执行。

布尔表达式出现在循环的结尾,所以在循环中的语句执行前一次布尔测试。 如果布尔表达式为true,控制流跳回起来,并且在循环中的语句再次执行。这个过程反复进行,直到布尔表达式为 false。

温馨提示:答案为网友推荐,仅供参考
第1个回答  2017-12-04
import random
secret = random.randint(1, 20)
print('随机数为%d' % secret)
print('---自己测试---')

for i in range(3):
    if i == 0:
        temp = input('guess the number:')
    else:
        temp = input('try again:')
    guess = int(temp)
    if guess == secret:
        print('bingo')
        print('game over')
        break
    else:
        if guess > secret:
            print('too big')
        else:
            print('too small')

第2个回答  2020-03-24
print('欢迎来到游戏')
import random
secret = random.randint(1,20)
i = 1
temp = input('不妨猜猜我手里的数字:')
guess = int(temp)
while guess !=secret and i < 3:
temp = input('猜错了请重新输入吧:')
guess = int(temp)
if guess == secret:
print('你是我的小宝贝')
else:
if guess > secret:
print('大乐大乐')
else :
print('小了小了')
i=i+1
print('游戏结束')
第3个回答  推荐于2017-12-05
加个变量统计下次数,然后while条件语句里加个条件判断不就可以了追问

你好大大 我是初学者 你能不能写一下完整的代码呢 我用的是3.4的版本

追答import random
secret = random.randint(1,20)
count = 1
print('---自己测试---')
temp = input('guess the number:')
guess = int(temp)
while guess != secret or count > 3:
        if guess > secret:
             print('too big')
        else:
             print('too small')
        temp = input('try again:')
        guess = int(temp)
        count += 1
        
if guess == secret:        
    print('bingo')            
    print('game over')

追问

兄弟啊 你的这个程序 我跑了 是错的啊

追答

失误

# coding: utf8

import random
secret = random.randint(1,20)
count = 1
print('---自己测试---')
temp = input('guess the number:')
guess = int(temp)
while guess != secret and count < 3:
        if guess > secret:
             print('too big')
        else:
             print('too small')
        temp = input('try again:')
        guess = int(temp)
        count += 1
        
if guess == secret:        
    print('bingo')            
    print('game over')

这个应该没问题了,我测试了下。

本回答被提问者和网友采纳
第4个回答  2020-05-03
直接用for
for 一个变量名 in range(想循环的次数):
代码