2015-04-01 100 views
3

我刚刚开始学习python 2.7.1,并且我已经为奶牛和公牛游戏编写了代码,其中您需要猜测通过不断重复输入4位数字直到您获得正确的数字。 但由于某些原因,代码只能持续最多3次循环。这里是代码: -我的if-else循环只运行三次而应该运行更多次

number=raw_input("Enter the 4 digit number to be guessed:") 
a=map(int,str(number)) 

def Guess(): 
    yournumber=raw_input("Enter your number now:") 
    b=map(int,str(yournumber)) 
    i=j=k=0 
    while i<=3: 
     if a[i]==b[i]: 
      j+=1 
     elif b[i] in a: 
      k+=1 
     i+=1 
    print str(j),"Bulls and "+str(k),"Cows"  
    return yournumber 

Guess() 
c=Guess() 

if c==number: 
    print "BINGO! You have guessed the number!" 
else: 
    Guess() 
+0

如果我从0开始,我每增加一次它可能只能运行有限的次数。 – radimpe 2015-04-01 19:48:11

回答

6

实际上没有循环来要求用户输入。

在您的实施中,函数Guess()正好有三个调用。

的实现:

Guess() # first call 
c=Guess() # second call 

if c==number: 
    print "BINGO! You have guessed the number!" 
else: 
    Guess() # third call 

#end 

相反,你应该循环,而用户得到它错了。试试这个块代替:

c="" 

while c != number: 
    c = Guess() 

print "BINGO! You have guessed the number!" 
+1

非常感谢Naftali!我现在感到很蠢。 – 2015-04-02 05:10:57

+0

但真的非常感谢吨:) – 2015-04-02 05:11:14

+2

@PrateekTripathi在堆栈溢出,我们说谢谢你的答案是正确的。看看这个图片http://i.stack.imgur.com/uqJeW.png – 2015-04-02 05:51:13