-1

再一次,我仍然掌握python的窍门。我制作了一个程序,让用户猜测一个由计算机随机生成的“幻数”。在 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 变量都会上升。不管它是否正确。

任何建议将不胜感激,在此先感谢向导!

4

1 回答 1

0

代码有很多问题。

请不要eval()用于将字符串转换为整数。int()这样做没有安全风险eval

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

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

True if 1 <= guess <= 100 else False

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

于 2013-09-29T19:33:02.217 回答