如何在python中计算条件语句的输出?

时间:2016-11-01 10:02:41

标签: python

我制作了这段代码,我希望它告诉我它用了多少次来找到我输入的号码,我想告诉它应该多少次重复一次找到“stop_at”的行为

print 'first write the random int (lowest number first)'

imp1 = float(raw_input())
imp2 = float(raw_input())
print 'the prosess will be between', imp1, 'and', imp2, 'when do you want to stop the opperation'
stop_at = float(raw_input())


while True:
    num = random.randint(imp1, imp2)
    if num == stop_at:
        print
        print
        print stop_at, "were found after", ..., 'tryes'
        print '                   '
        break
    print num

3 个答案:

答案 0 :(得分:1)

您可以添加计数器

try:
    float(s) if '.' in s else int(s)
    return True
except ValueError:
    return False

答案 1 :(得分:0)

首先,您不能将float值用作random.randint函数的输入参数。输入参数必须为integer类型。

其次,stop_at也是如此。它必须是integer,因为random.randint将返回integer(它可能是float,但只有在2.0格式11.0时才会if ...)。

第三,你应该引入计数器并在while部分代码中增加它以获得命中数。另外,你应该引入一个将放在imp1 = int(raw_input("Enter low guess")) imp2 = int(raw_input("Enter high guess")) stop_at = int(raw_input("Enter the number you want guessed")) i = 0 while True: i += 1 num = random.randint(imp1, imp2) if num == stop_at: print "\n\n{0} was found after {1} tries\n\n".format(stop_at, i) print num 循环内的计数器,它将告诉你有多少循环。

答案 2 :(得分:0)

引入一些计数变量,您将在每次循环传递时递增。

cnt = 0
while True:
    num = random.randint(imp1, imp2)
    cnt += 1
    if num == stop_at:
        print
        print
        print stop_at, "were found after tryes {}".format(cnt)
        print
        break
    print num