【问题标题】:My if-else loop runs only thrice while it should be running more number of times我的 if-else 循环只运行三次,而它应该运行更多次
【发布时间】:2015-04-01 19:34:29
【问题描述】:

我刚开始学习python 2.7.1,我写了一个奶牛和公牛游戏的代码,你需要通过不断地重新输入4位数字来猜测一个四位数字,直到你得到正确的数字。 但由于某种原因,代码最多只能持续 3 个循环。这是代码:-

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()

【问题讨论】:

  • 如果 i 从 0 开始并且 i 每次递增,它可能只运行有限的次数。

标签: python-2.7 loops if-statement


【解决方案1】:

实际上没有循环来不断询问用户输入。

在您的实现中,函数 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!"

【讨论】:

  • @PrateekTripathi 在堆栈溢出中,我们通过将答案标记为正确来表示感谢。看看这张图片i.stack.imgur.com/uqJeW.png
  • 我会记住的:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-19
  • 1970-01-01
  • 2022-01-05
  • 2018-05-02
  • 2019-05-09
  • 2021-10-07
相关资源
最近更新 更多