Python中的While循环问题

时间:2017-09-28 15:26:36

标签: python-2.7

我想创建一款名为"猜数字"。

的游戏

我希望程序生成一个随机数,并将其与用户输入的值进行比较,并将其正确/错误的次数写入文本文件。

程序的第一部分工作正常,问题出现在最后,我要求用户输入决定是否退出/继续该程序。

它一直在询问用户是否退出/继续的输入。

前: -

  

欢迎来到Guess the Number游戏!

     

输入介于1到10:4之间的数字

     

您猜错了数字!

     

按Q退出或按E继续:E

     

按Q退出或E继续:Q

     

按Q退出或按E继续:E

不退出或继续该计划,以下是我的代码,请帮帮我。只是Python的初学者,自学。

 import random


print "Welcome to the Guess the Number game!"
print

c = True
lost = 0
win = 0
j = ""
d = True

while c == True:
    v = random.randint(1,10)
    n = input("Enter a number between 1 to 10 : ")
    print
    if n > 10:
        print "The number you entered is above 10, please enter a number below 10."
        print
    elif n < 0:
        print "The number you entered is below 0, please enter a number above 0."
        print
    elif 0<n<10:
        print "Progressing..."
        print
    else:
        j = " "
    if n == v:
        print "Congratulations, you guess the number correctly!"
        print
        win = win + 1
        file = open("text.txt","w") 
        file.write("Number of times won : %s \n" %(win))
        file.close()
    else:
        print "You guess the number incorrectly!"
        print        
        lost = lost + 1
        file = open("text.txt","w") 
        file.write("Number of times lost : %s \n" %(lost))
        file.close()      
    while d == True:
        response =  raw_input("Press Q to quit or E to continue : ")
        response = str(response)          
        print        
        if response == 'Q':
            c = False
            d == False
        elif response == 'E':
            c = True
            d == False
        else:
            print("Please read the instructions properly and press the proper button.")
            print        
            d == True

1 个答案:

答案 0 :(得分:0)

你的问题就在这个while循环中

while d == True:
    response =  raw_input("Press Q to quit or E to continue : ")
    response = str(response)          
    print        
    if response == 'Q':
        c = False
        d == False
    elif response == 'E':
        c = True
        d == False
    else:
        print("Please read the instructions properly and press the proper button.")
        print        
        d == True

=(赋值运算符)和==(比较运算符)之间存在很大差异,第一个(=)将重写变量,并将新值存储在内存中。 ==,但是只会比较左边的内容和右边的内容,所以当你输入d == False或True时,你永远不会重新分配变量,它将永远保持在该循环中。要纠正它,您只需将其更改为此

while d == True:
    response =  raw_input("Press Q to quit or E to continue : ")
    response = str(response)          
    print        
    if response == 'Q':
        c = False
        d = False
    elif response == 'E':
        c = True
        d = False
    else:
        print("Please read the instructions properly and press the proper button.")
        print        
        d = True