我怎样才能改善这个循环?

时间:2013-09-29 18:21:52

标签: python python-3.x while-loop

再次,我仍然得到了蟒蛇的悬念。我做了一个程序让用户猜出一个由计算机随机生成的“幻数”。在5次不正确的尝试之后,它使用两个随机生成的变量以加法问题的形式提供一个提示,其变量等于幻数。

这是代码:

def moot():
    count = 0
    # magicNumber is the randomly generated number from 1 to 100 that must be guessed
    magicNumber = random.randint(1,100) 
    var1 = 0 
    var2 = 0
    guess = eval(input('Enter a number: '))
    # This loop sets random values for var1 and var2 that sum up to the magicNumber

    while var1 + var2 != var: 
        var2 = random.randint(1,100)
        var3 = random.randint(1,100)
    # an addition problem is made from var1 and var2 to be used as a hint later
    hint = 'Try adding '+ str(var1)+ ' and '+ str(var2)+'\n'
    # withinRange checks to see if the users guess is (valid) within the range of 1 to 100
    # if not, asks for another number until a valid one is provided
    withinRange = True if (guess <= 100 and guess >= 1) else False  

    while not withinRange:
        count = count + 1
        guess = eval(input('Number is invalid.Enter a number between 1 and 100: '))
        withinRange = True if (guess <= 100 and guess >= 1) else False
    # rng tells the user if his guess is too high or low
    rng = 'low' if guess < magicNumber else 'high'

    # the following loop repeatedly asks for input until the user enteres the majicNumber
    while magicNumber != guess:
        count = count + 1
        print('\nThats incorrect. Your number is too',rng,end='\n')
        # after 5 incorrect guesses the program prints out the addition problem that
        # was made using var1 and var2
        if count > 5:
            print(hint)
        guess = eval(input('Guess: '))
        withinRange = True if (guess <= 100 and guess >= 1) else False
        while not withinRange:
            count = count + 1
            guess = eval(input('Nope, has to be between 1 and 100. Try again: '))
            withinRange = True if (guess <= 100 and guess >= 1) else False
        rng = 'low' if guess < magicNumber else 'high'

    print('\nYou entered the right number!')    

    print('Number:',magicNumber)
    print('range of last guess was too',rng)
    print('Number of guesses:',count + 1)

上次,我被告知我没有提供有关我的计划的足够信息。我希望我没有对评论做过。这是我的目标/问题/查询/目标:我想在程序中添加一些代码行,以便在7次尝试后终止它。

该程序现在所做的是一遍又一遍地接受猜测,直到达到正确的方式。但是我想在'count'变量达到6之后添加一些杀死它的代码。每次输入猜测时,count变量都会增加。无论是否正确。

任何建议都会非常感激,感谢提前向导!

1 个答案:

答案 0 :(得分:0)

代码存在很多问题。

请不要使用eval()将字符串转换为整数。 int()执行此操作时没有eval的安全风险。

在您的while循环中,您将var1var2var进行比较。什么是var?你没有在任何地方定义它。我想你的意思是magicNumber。然后在循环中设置var2var3。为什么var3。你不使用它。至少,获得两个数字的最佳方法是获得一个最大值为magicNumber的数字,然后计算第二个数字。

True if (guess <= 100 and guess >= 1) else False可以写成

True if 1 <= guess <= 100 else False

摆脱循环中和循环外的重复代码。您可能想要添加其他功能,例如一个函数,用于获取用户的输入并进行一些基本检查。