0

I am attempting to make my first bit of code which would be a random number generator and then subtract those numbers. I have this so far:

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

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

I then have a function putting these together:

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

I am attempting to make a solver by adding an ans() function. it would look like this:

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

However this does not evaluate the data of return Correct when it is right. Any tips or suggestions on getting raw_input to evaluate the inputed data?

  • 2
    Each call to `rand3` and `rand2` return a *different* random value. You need to assign those results to variables rather than calling again. – Daniel Roseman Nov 03 '16 at 16:34

2 Answers2

1

rand2 and rand3 return a different value on each call, so you'll have to save their return values, something like this should work:

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")
Francisco
  • 10,918
  • 6
  • 34
  • 45
0

Just call your random functions once and pass those numbers as parameters. For example:

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()
cdarke
  • 42,728
  • 8
  • 80
  • 84