0

Python If and else statements

Could you use the if and the else statements for words? Or only for numbers?

28th Jan 2019, 2:53 PM
Benji Mandel
Benji Mandel - avatar
3 Antworten
+ 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).
28th Jan 2019, 4:47 PM
Kishalaya Saha
Kishalaya Saha - avatar
+ 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
28th Jan 2019, 6:57 PM
Mayur Garg
Mayur Garg - avatar
+ 1
ok, thanks a lot!!!!
28th Jan 2019, 9:49 PM
Benji Mandel
Benji Mandel - avatar