0

I'm trying to create a game of last man standing in python, but when you input a number it outputs the negative version of the correct answer? Also, when i enter anything other than 1, 2, or 3, I get the error: ValueError: could not convert string to float: '(anything other than the numbers)'

any help is appreciated. Thanks!

import random

num = random.randrange(20, 30)  
print ("The number is " + str(num) + ", take either one, two or three away from it!")
take = float(input("input either 1, 2 or 3: "))
newnum = take - num
if take == 1:
    print(newnum)
elif take == 2:
    print(newnum)
elif take == 3:
    print(newnum)
else:
    print("please enter either 1, 2 or 3!")
lad12345
  • 13
  • 4

1 Answers1

1

You could just use a while loop to make sure the user only inputs 1,2 or 3.

import random

num = random.randrange(20, 30)  
print ("The number is " + str(num) + ", take either one, two or three away from it!")
take = None
while take not in {1,2,3}: #{} faster than ()
    take = int(input("input either 1, 2 or 3: "))
    print("please enter either 1, 2 or 3!")
print(num-take)

Also as the above code shows, you need to use num-take instead of vice-versa.

Buddy Bob
  • 5,829
  • 1
  • 13
  • 44
  • 1
    `1 <= take <= 3` should be slightly faster, but if you want to use `in` then use *set* as a container, it'd be a bit faster `take not in {1, 2, 3}`. For huge ranges more efficient will be to use conditional check *(first option)* or `range()`: `if take not in range(1, 4)`. – Olvin Roght May 01 '21 at 20:33
  • Thank you for that, never new about this. – Buddy Bob May 01 '21 at 20:35