I am writing a program were add and subtract numbers from an integer to keep score. The admin and subtracting is working but I am trying to add a feature that if you add number after the word add or subtract it changes by that number, but I can’t get that to work.
cont = True
score = 0
num = False
while cont == True:
q = input("add, subtract, or end: ")
for char in q:
n = q.isnumeric()
if n == True:
num = True
num2 = q
if num == False:
if q.lower() == "add":
score = 1
elif q.lower() == "subtract" or q.lower() == "sub":
score -= 1
elif q.lower() == "end":
cont = False
print(score)
elif num == True:
if "add" in q.lower():
score = num2
elif "subtract" in q.lower() or "sub" in q.lower():
score -= num2
elif q.lower() == "end":
cont = False
print(score)
I expect it to add one if you type add subtract one if you type sub or subtract and end the program if you type end, that works the part that I expected and doesn’t work is that it is supposed to detect if there is a number in the string using the isnumeric() function and add or subtract that number.
CodePudding user response:
Your code simplifies neatly to something like:
score = 0
while True: # Infinite loop; we'll use `break` to end
print("Score:", score)
q = input("add, subtract, or end: ").lower().strip() # lower-case, remove whitespace
words = q.split() # Split entry by spaces
verb = words.pop(0) # Remove first word
if verb == "end":
break
if words and words[0].isnumeric(): # If there is a second word and it's numeric
value = int(words[0])
else: # Otherwise default to 1
value = 1
if verb == "add":
score = value
elif verb == "subtract":
score -= value
else:
print("Unknown verb", verb)