📜 ⬆️ ⬇️

Python: Thinking Programmer

A small article on how to solve the same problem in several ways. Designed for beginners in Python and programming.


As an example, a simple case is taken - the implementation of the dialogue confirming any operation. The program asks the user a question. ? [/ (Y/n)]: ? [/ (Y/n)]: to which you want to answer by entering one of eight valid values ​​( , , , , Y , y , N , n ).


Method number 1

The first thing that comes to mind is to implement a check of the coincidence of each of the conditions as follows:


  #!/usr/bin/env python # -*- coding: utf-8 -*- def are_you_sure1(): while True: print(" ? [/ (Y/n)]: ") response = input() if response == "" or response == "": print(" : {}".format(response)) elif response == "Y" or response == "y": print(" : {}".format(response)) elif response == "" or response == "": print(" : {}".format(response)) elif response == "N" or response == "n": print(" : {}".format(response)) else: print("  : {}".format(response) are_you_sure1() 

It was possible to paint all 8 if/elif blocks, but for brevity, the logical operator or (OR) is used for each of the pairs of possible values.


There is nothing wrong with this decision and it is correct, well describing the principle “The simpler, the better”. This is the solution that most beginner pythonists come to.


However, this is contrary to the principle of "Do not repeat," since any programmer seeks to reduce the number of characters entered.


Method number 2

The second way is to cut off unnecessary entities ( Occam's Razor ). It does not matter in which register the character will be entered in response to a program question. Therefore, we use the method of the string upper() or lower() to reduce characters to upper or lower case:


  #!/usr/bin/env python # -*- coding: utf-8 -*- def are_you_sure2(): while True: print(" ? [/ (Y/n)]: ") #  ,    #      response = input().upper() if response == "" or response == "Y": print(" : {}".format(response)) elif response == "" or response == "N": print(" : {}".format(response)) else: print("  : {}".format(response)) are_you_sure2() 

The value entered by the user is immediately converted to one register, and then it is already checked. As a result - reducing the number of input characters and duplicate blocks of code.


Method number 3

Another way is to check whether the entered value is in the list of valid values.


  #!/usr/bin/env python # -*- coding: utf-8 -*- def are_you_sure3(): while True: print(" ? [/ (Y/n)]: ") response = input() if response in ["", "", "Y", "y"]: print(" : {}".format(response)) elif response in ["", "", "N", "n"]: print(" : {}".format(response)) else: print("  : {}".format(response)) are_you_sure3() 

The check is performed using the in operator. An example of alternative thinking.


Method number 4

Another example of alternative thinking is the use of regular expressions. To do this, we use the standard module for working with regular expressions re and the re.match() method.


  #!/usr/bin/env python # -*- coding: utf-8 -*- import re #        def are_you_sure4(): while True: print(" ? [/ (Y/n)]: ") response = input() if re.match("[yY]", response): print(" : {}".format(response)) elif re.match("[nN]", response): print(" : {}".format(response)) else: print("  : {}".format(response)) are_you_sure4() 

The re.match(, ) method re.match(, ) searches for a given pattern at the beginning of a string. The regular expression [yY] and [nN] used as a template (square brackets group the characters). In more detail the topic of regular expressions is disclosed in the articles, links to which are given at the end. I also recommend the book “Learn your own regular expressions. 10 minutes to the lesson "Ben Forts .


In this method, you can also use the principle of cutting off excess and reduce regular expressions to the form [Y] and [N] using the method upper() .


It is also worth noting that in this case, any values ​​starting with the allowed characters, for example, , Yum , etc., will be considered correct, since re.match() searches for matches only from the beginning of the line. Unlike other methods, where there should be an exact match and any extra characters will cause a message about incorrectness. It can be considered an advantage, but nothing prevents to correct this behavior.


The latter method is unnecessary for such a simple example, but is good for its versatility and extensibility, since regular expressions allow for more complex checking (for example, checking e-mail ).


Method number 5

In the comments, random1st brought another elegant way :


  #!/usr/bin/env python # -*- coding: utf-8 -*- def check_answer(): while True: response = input(' ? [/ (Y/n)]: ') try: print( 0 <= "YyNn".index(response) <=3 and "True" or "False") except ValueError: print ("Incorrect") check_answer() 

And as saboteur_kiev rightly noted , this method is elegant, but not very beautiful in terms of code support. If you need to add new values ​​will be another developer - it is read and understood worse than the solution from the previous comment , where the positive and negative response is clearly separated.


Remark

@datacompboy and MamOn pointed to another interesting point. The Y and on the Russian-language keyboard are on the same button, which, if careless on the part of the user, can lead to completely opposite results. Similar moments also need to be considered when developing. Therefore, in applications where an error of choice can lead to irreversible results, it is better to request confirmation of Yes / No , in order to exclude the possibility of an error.


Links


')

Source: https://habr.com/ru/post/301344/


All Articles