Python随机数游戏,根据对随机数的贴近度响应不同

时间:2017-02-06 03:55:06

标签: python random

尝试根据猜测与随机生成的数字的接近程度生成不同的响应。注释掉的部分是我尝试为随机数的10个数字内的猜测生成不同的响应。

$("#pageResults li").each(function (){

    var viewsText = $(this).find(".duration-viewCount").text();
    var numViews = +viewsText.match(/\|\s([^ ]+)/)[1].replace(/,/g, "");

    var likesText = $(this).find(".likes").text();
    var numLikes = +likesText.match("^([^ ]+)")[1].replace(/,/g, "");

    //i think numlikes * 50 > numViews is what you're looking for, change that if not
    if (numLikes > 5 && numLikes * 50 > numViews)
    {
        $(this).css("background-color", "lightgreen");
    }

});

在随机生成的数字的指定范围内产生以下输出。

import random

while True:

    number = random.randint(1,1000)
    guess = 0
    tries = 0

    while guess != number:
        guess = input('Please enter your guess, number must be between 0 and 1000: ')
        tries += 1
    if guess < number:
        if number - 10 <= guess:
            print('Getting warm but still too low!')
        print('Too Low!')
    elif guess > number:
        if number + 10 >= guess:
            print('Getting warm but still too high!')
        print('Too High!')
    print("Great Guess! The number was %i and you guessed it in %s tries!") % (number, tries)
    again = raw_input("Enter 'y' or 'n' to select to play again: ")
    if again == 'n':
        break

2 个答案:

答案 0 :(得分:2)

问题是由于缩进,作为初学者,您应该看到基本嵌套循环如何工作。缩进后的代码将产生正确的结果。我添加了另外一个处理打印“Too Low”和“Too High”的其他内容

import random

while True:

    number = random.randint(1,1000)
    guess = 0
    tries = 0

    while guess != number:
         guess = input('Please enter your guess, number must be between 0 and 1000: ')
         tries += 1
         if guess < number:
             if number - 10 <= guess:
                 print('Getting warm but still too low!')
             else:
                 print('Too Low!')
         elif guess > number:
             if number + 10 >= guess:
                 print('Getting warm but still too high!')
             else:
                 print('Too High!')
        else:
            print("Great Guess! The number was %i and you guessed it in %s tries!") % (number, tries)

    again = raw_input("Enter 'y' or 'n' to select to play again: ")
    if again == 'n':
        break

答案 1 :(得分:1)

问题是因为首先满足第一个'if子句'的条件,其他条件将被忽略。您可以重新安排if子句以根据需要显示消息:

    if number - 10 <= guess:
        print('Getting warm but still too low!')
    elif guess < number:
        print('Too Low!') 
    elif number + 10 >= guess:
        print('Getting warm but still too high!')
    elif guess > number:
        print('Too High!')