1

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?

2
  • 1
    The problem here is that with sum the order of the elements do not matter. With subtraction, the ordering of the elements will affect the result. Perhaps a manual subtraction command is the right way to go here.
    – Lix
    Mar 3, 2015 at 10:08
  • import operator; reduce(operator.sub, mynos) Is it only ever two numbers? Why not use distinct variables then?
    – dhke
    Mar 3, 2015 at 10:10

1 Answer 1

1

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.

4
  • May be add abs(n) to the result. If it does not want to show negative result and just the difference between two.
    – planet260
    Mar 3, 2015 at 10:10
  • @planet260: I think I know what exercise the OP is trying to complete; there are a few dozen related questions going round at the moment. They don't care about absolute results. Next up: multiplication and division.
    – Martijn Pieters
    Mar 3, 2015 at 10:12
  • @planet260 - true - but difference is not the same as subtraction. This might be the case, but it needs to be verified with the OP.
    – Lix
    Mar 3, 2015 at 10:12
  • Thanks for your help.. my program works just fine now! Mar 3, 2015 at 10:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.