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 or
s 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')