【问题标题】:how do I keep track of the number of inputs for a while loop in python?如何在python中跟踪while循环的输入数量?
【发布时间】:2014-12-05 05:58:34
【问题描述】:

我正在尝试在 python 中制作一个“猜数字游戏”,我希望它显示用户必须进行的猜测次数,以便猜测计算机最后生成的随机数。到目前为止,我举一个例子来说明我的意思:

    from random import*
a=randrange(1,51)
b=int(input("Can you guess my number?: "))
while a>b:
    b=int(input("Too low, try again: "))
while a<b:
    b=int(input("Too high, try again: "))
while a==b:
    print("You got it! The number was", a)
    break

我希望它在最后打印出类似“它花了你 __ 猜测”之类的内容。我将如何跟踪这样的输入数量?我试着四处寻找,但我不确定如何用语言表达。

【问题讨论】:

  • 首先,这段代码没有做你想做的事。假设您输入了一个太低的数字,然后是一个太高的数字,最后是一个太低的数字。您的代码将提前终止。
  • 我现在明白了,谢谢。

标签: python random input while-loop range


【解决方案1】:

您要做的是摆脱 3 个while 循环,并将它们更改为while 循环中的if 语句:

from random import*
a=randrange(1,51)
b = 0
guesses = 0 #Initialize a variable to store how many guesses the user has used
while b != a:
    b=int(input("Can you guess my number?: "))
    if a>b:
        b=int(input("Too low, try again: "))
    else:
        b=int(input("Too high, try again: "))
    guesses+=1

print("You got it! The number was", a)
print("You took {} guesses!".format(guesses))

【讨论】:

    【解决方案2】:

    guess 记录没有。猜测

    from random import*
    
    a=randrange(1,51)
    guess = 0
    while True:
        b=int(input("Can you guess my number?: "))
        guess += 1
    
        if b==a:
            print("You got it correct")
            break
    
        elif b>a:
            print("number is higher")
    
        else:
            print("number is lower")
    
    print("Guesses: ", guess)
    

    【讨论】:

      【解决方案3】:

      d = 74 计数 = 1

      def check(n): if n==d: count += 1 print "You Got the number" elif n>d:
      print "The number is too high" count += 1 check(int(raw_input('Enter another number'))) elif n<d:
      print "The no is too low" if count count += 1 check(int(raw_input('Enter something high'))) return count

      返回的值为猜测次数

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-01-19
        • 2016-07-17
        • 2023-03-18
        • 2014-08-06
        • 1970-01-01
        • 1970-01-01
        • 2013-02-08
        • 2015-12-21
        相关资源
        最近更新 更多