简体   繁体   English

如何跟踪python中while循环的输入数量?

[英]how do I keep track of the number of inputs for a while loop in python?

I'm trying to make a "number guessing game" in python, and I want it to display the number of guesses the user had to make in order to guess the random number generated by the computer at the end. 我正在尝试用python创建一个“数字猜谜游戏”,并且我希望它显示用户为猜测最后由计算机生成的随机数而必须进行的猜测的数目。 Here's what I have so far to give an example of what I mean: 到目前为止,这里是我所要表达的示例:

    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

I'd like it to print something like "it took you __ guesses" at the end. 我希望它在最后打印类似“花了您__个猜测”的内容。 How would I go about keeping track of the number of inputs like that? 我将如何跟踪这样的输入数量? I tried searching around, but I wasn't really sure how to put it into words. 我尝试四处搜寻,但是我不确定如何将它写成文字。

What you want to do is get rid of the 3 while loops, and change them to if statements within a while loop: 您想要做的是摆脱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))

guess keeps track of no. 猜测保持否。 of guesses 猜测

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)

d = 74 count = 1 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

The value returned is the number of guesses 返回的值是猜测数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM