Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accept lowercase or uppercase letter in Python

Tags:

python

Working on a menu display where the letter "m" takes the user back to the main menu. How can I have it so that it works regardless if the letter "m" is uppercase or lowercase?

elif choice == "m":
like image 762
sdot257 Avatar asked Nov 29 '22 05:11

sdot257


1 Answers

One of

elif choice in ("m", "M"):
elif choice in "mM":                       # false positive if choice == ''
elif choice == 'm' or choice == 'M':
elif choice.lower() == 'm':

In terms of maintainability, the 4th alternative is better when you want to extend to case-insensitive comparison of multiple-letter strings, as you need to provide all 2N possibilities in the 1st and 3rd alternatives. The 2nd alternative only works properly for single-character strings.

With the 4th alternative it is also impossible to miss a case when you want to change the 'm' to other letters.

In terms of efficiency, the 2nd alternative is the most efficient, and then the 1st, and then the 3rd and finally the 4th. This is because the 3nd alternative involves more operations; and while function calling and getting attribution is slow in Python so both makes the 4th alternative relatively slow.

See http://pastie.org/1230957 for the disassembly and timeit result.

Of course unless you're doing this comparison 10 million times there is no perceivable difference between each one.

like image 134
kennytm Avatar answered Dec 05 '22 01:12

kennytm