0

I'm curious what's the reason for the different results from the two samples below (just or without variable GPA and or with variable GPA)?

GPA = input('Enter GPA Grade: ')
if  GPA == 'A+' or 'a+' or 'A' or 'a':
    print('5.0')

The code above always make same output '5.0' no matter what kind of input we enter.

GPA = input('Enter GPA Grade: ')
if  GPA == 'A+' or GPA == 'a+' or GPA == 'A' or GPA == 'a':
    print('5.0')

The code above make the correct output when we type the variable GPA after or.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578

1 Answers1

2

The reason that the outputs are different is that the first example checks whether the strings "a+", "A", or "a" are true, NOT whether GPA is equal to them.

For example, if you wrote:

if "a":
    print("Success")

"Success" would be printed because "a" is "technically true" (more correctly, it's "truthy"). Contrastingly, if you wrote:

if "":
    print("Success")

Nothing would be printed because the empty string is "falsy." Other things that are falsy include 0 and [] (empty list).

In your first example:

GPA = input('Enter GPA Grade: ')
if GPA == 'A+' or 'a+' or 'A' or 'a':
   print('5.0')  

5.0 is always printed because the interpreter simplifies the if code like this:

if (GPA == 'A+') or ('a+') or ('A') or ('a')

This way, the expression will always evaluate to True because of the truthy strings:

if (GPA == 'A+') or True or True or True

So no matter what the GPA is, the ors will simplify to just True.

The second example works as expected because you are testing each equality case separately. Another shorter solution uses the in operator, which tests if an element is in a list:

GPA = input('Enter GPA Grade: ')
if GPA in ['a', 'A', 'a+', 'A+']:
    print('5.0')

Even better, using the str.lower() method:

GPA = input('Enter GPA Grade: ')
if GPA.lower() in ['a', 'a+']:
    print('5.0')
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Aviv Shai
  • 997
  • 1
  • 8
  • 20