0
Python If and else statements
Could you use the if and the else statements for words? Or only for numbers?
3 Answers
+ 2
The condition after if statement can certainly involve a string. For example,
if "am" in "spam":
print("eggs")
checks if the string "am" is a part of the string "spam" (True).
+ 2
Apart from what Kishalaya Saha mentioned, you can compare strings in if and else statements as well.
if 'a' > 'A':
print(1)
This works perfectly.
Strings are compared character by character based on their ASCII values.
So 'Mary' is greater than 'Mac' as first two characters are equal but 'r' has a greater ASCII value than 'c'. Other operators such as < , >= , <= , == , != work as you would expect them to.
It is also interesting to note that non empty strings (even though it contains only spaces such as ' ' ) by themselves are seen as True where as an empty string (any string with length 0) is False.
For instance,
if 'a' :
print(1) #Output => 1
But
if '':
print(1) #No Output
+ 1
ok, thanks a lot!!!!