我怎样才能确保这个while循环可以重新运行我的随机数代码而不会永远存在?

时间:2015-08-17 01:58:38

标签: python loops while-loop

我创建了一个猜测数字程序并使用了一个while循环来允许用户继续猜测,直到他/她能够正确完成,如下所示:

import random

number = random.randrange(1, 6) 

print "Guess the number, between 1 and 6"

guess = "yes"

while guess != number: 
    guess = int(raw_input('>'))
    if guess == number:
        break
        print "Good job! You got it right!"
        print number 


    elif guess > number: 
        print "Too High"
        print number  
        number = random.randrange(1, 6) 

    elif guess < number:
        print "Too Low"
        print number  
        number = random.randrange(1, 6) 

问题是,当我试图猜测数字时,它将随机结束,无论我是第一次猜测,4次还是30次。另外,我最初有,

guess = int(raw_input('>'))

取代,

guess = "yes"

并替换它以摆脱我最初需要添加到终端的额外且无用的raw_input。为什么我能够使它等于“是”,为什么我放在那里不重要?

Bug示例:

Guess the number, between 1 and 6
>3
Too High
2
>4
Too Low
5
>6
Too High
5
>3
Too High
1
>2
Too High
1
>5
Good job! You got it right!
5


------------------
(program exited with code: 0)
Press return to continue

它起作用了,现在:

Guess the number, between 1 and 6
>3
Too Low
4


------------------
(program exited with code: 0)
Press return to continue

3 个答案:

答案 0 :(得分:1)

您遇到的问题是while循环正在测试<{1}}匹配number 选择新guess值后但在获取之前一个新的number。这意味着你会说玩家猜错了,但他们之后就会变得正确而循环将会结束。

请改为尝试:

guess

我还将import random print "Guess the number, between 1 and 6" guess = 'y' # the values set here don't actually matter, they just need to be different number = 'x' while guess != number: number = random.randint(1, 6) guess = int(raw_input('>')) if guess == number: print "Good job! You got it right!" elif guess > number: print "Too High" print number elif guess < number: print "Too Low" print number 的使用更改为random.randrange,这将使其实际上在某些时间返回random.randint6排除上限)

答案 1 :(得分:0)

contents = []

class basket:

## This is where I want to define the list "contents",
## but it doesn't work.

    def __init__(self,name):
        self.name = name
        global contents
        if name not in contents:
            contents.append(name)

答案 2 :(得分:0)

import random number = random.randrange(1, 6) print "Guess the number, between 1 and 6" guess = "yes" while guess != number: guess = int(raw_input('>')) if guess == number: break print "Good job! You got it right!" print number break elif guess > number: print "Too High" print number number = random.randrange(1, 6) break elif guess < number: print "Too Low" print number number = random.randrange(1, 6) break 有效,因为guess = "yes"在while循环中的第一次检查时始终为guess != number,此时会要求用户输入。另外,在True块中,将if语句放在所有break之后。