0

I have this code:

print("Christian Dooley")
print("Lab #5")
import sys

def calculation():
 counter = 0
 NumberOfElements = 1
 numbers = []
 sum = (0)
 for i in range(NumberOfElements):
     value=eval(input("Enter a new number:"))
     numbers.append(value)
 while counter <= value:
     print(counter)
     sum+=counter
     counter+=1
     if counter % 2 != 0:
         print("This number is even")
     else:
         print("This number is odd")
 print(sum)

while True:
 calculation()
 repeat = input("Do you want to 'count' another number \n Awnser yes or no: ")
 if repeat == "Yes" or "yes":
      calculation()
 elif repeat == str("no") or str("No"):
      break

When the code runs, it should ask the user to input a number; print every number leading up to it; tell if the number is even or odd; print the sum; and finally have the user enter if he wants to repeat the process or not.

This part of the code is giving me trouble:

    if repeat == "Yes" or "yes":
        calculation()
    elif repeat == str("no") or str("No"):
        break

The if statement will keep running over and over, no matter what I enter for the repeat variable. Why does this happen?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • 2
    Yep, this gets asked a lot. `repeat == "Yes" or "yes"` is _not_ the same as `repeat == "Yes" or repeat == "yes"`. The latter is what you want, because the former is always, always, always, always True :) – Ray Toal Mar 20 '18 at 01:06
  • This one is hard to search for, to make it more fun. – abarnert Mar 20 '18 at 01:10

1 Answers1

3

The or statement evaluates the first boolean, if it's False it then evaluates the second. Your second boolean statement is actually a string and strings are always True, meaning they exist. The only string that would return False is an empty string "".

Therefore whatever the value of the first boolean, meaning whatever the value of repeat, "yes" will always evaluate to True.

You want if repeat == "Yes" or repeat == "yes" or if repeat in ['Yes', 'yes'] or better still with a set: if repeat in {'Yes', 'yes'}

ted
  • 13,596
  • 9
  • 65
  • 107