让raw_input评估数据,然后打印回来

时间:2016-11-03 16:31:59

标签: python python-2.7

我试图将我的第一段代码作为随机数生成器,然后减去这些数字。到目前为止我有这个:

    def rand2():
        rand2 = random.choice('123456789')
        return int(rand2)

    def rand3():
        rand3 = random.choice('987654321')
        return int(rand3)

然后我有一个功能将这些放在一起:

    def rand():
        print rand3()
        print '-'
        print rand2()
        ans()

我试图通过添加ans()函数来创建求解器。它看起来像这样:

    def ans():
        ans = int(raw_input("Answer: "))
        if ans == rand3() - rand2():
            print("Correct")

然而,当它是正确的时,这不会评估返回正确的数据。有关获取raw_input以评估输入数据的任何提示或建议吗?

2 个答案:

答案 0 :(得分:1)

rand2rand3会在每次调用时返回不同的值,因此您必须保存其返回值,这样的事情应该有效:

def rand():
    r3 = rand3()
    r2 = rand2()
    print r3
    print '-'
    print r2
    ans(r3, r2)

def ans(r3, r2):
    ans = int(raw_input("Answer: "))
    if ans == r3 - r2:
        print("Correct")

答案 1 :(得分:0)

只需将随机函数调用并将这些数字作为参数传递。例如:

import random

# Variable names changed.  Having a variable the same name as a function
# is confusing and can lead to side-effects in some circumstances
def rand2():
    rand2v = random.choice('123456789')
    return int(rand2v)

def rand3():
    rand3v = random.choice('987654321')
    return int(rand3v)

# This functions takes as parameters the two random numbers
def ans(r2, r3):
    ans = int(raw_input("Answer: "))
    if ans == r3 - r2:
        print("Correct")

def rand():
    # This is the only place we create random numbers
    r2 = rand2()
    r3 = rand3()

    # The print can be doe in one line
    print r3, '-', r2

    # Pass the numbers to ans()
    ans(r2, r3)

rand()