Generating two random numbers and subtracting them

I need to do this, and I have come up with this for adding:

import random
mynos = []

print ("First, we'll do some addition")

for counter in range (0,2):
      mynumber = random.randint(1,20)
      mynos.append(mynumber)
print(mynos)

the_answer = sum(mynos)
#print(the_answer) (^^^)

player_answer =int(input("What is the answer?"))

def main():
      if player_answer is the_answer:
            print ("Correct! Well done!")
            print ("You scored 1 out of 10 so far!")
            print ("Good job!")
      else:
            print ("Incorrect! You scored null points!")
            print ("You have zero out of 10 so far!")
            exit()

main()

That was the adding part of the program, but instead of using sum is there anything to use for subtracting the two randomly generated numbers in mynos?

Upvotes: 1

Views: 2348

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1123400

If you only ever have 2 integers, just use subtraction on the individual elements:

the_answer = mynos[0] - mynos[1]

The 'functional' way to subtract numbers in a sequence is to use the reduce() function:

import operator
try:
    # Python 3 moved reduce to the functools module
    from functools import reduce
except ImportError:
    pass

the_answer = reduce(operator.sub, mynos)

The operator.sub() function stands in for the - operator in that case.

Upvotes: 1

Related Questions