
Python: Programmer Thinking
- Tutorial
A short 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 confirmation dialog of any operation. The program asks the user a question Вы уверены? [Д/н (Y/n)]:
, to which you want to respond by entering one of the eight permissible values ( Д
, д
, Н
, н
, Y
, y
, N
, n
).
Method number 1
The first thing that comes to mind is to implement a verification 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 blocks if/elif
, but for brevity, a 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 characterizing the principle "The simpler, the better." This is the decision most beginner pythonists come to.
However, this contradicts the principle of "Do not repeat", as any programmer seeks to reduce the number of input characters.
Method number 2
The second way is to cut off excess entities ( Occam's Razor ). It does not matter in which register the character will be entered in response to a program question. Therefore, we will use the string method upper()
or lower()
to cast 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 checked. As a result - reducing the number of input characters and repeating blocks of code.
Method number 3
Another way is to check whether the entered value is on 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()
Validation is done using the entry operator in
. An example of alternative thinking.
Method number 4
Another example of alternative thinking is using regular expressions. To do this, we will use the standard module for working with regular expressions re
and the method re.match()
.
#!/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 method re.match(шаблон, строка)
searches for the given pattern at the beginning of the line. A regular expression [yYдД]
and [nNнН]
(square brackets group characters) are used as a pattern . The topic of regular expressions is described in more detail in the articles cited at the end. I also recommend the book “Master your own regular expressions. 10 minutes per 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 will be considered correct any values beginning with permitted characters, for example да
, Yum
etc., have been re.match()
looking 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 an error message. This can be considered an advantage, but nothing prevents fix this behavior.
The latter method is redundant for such a simple example, but it 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 provided another elegant way :
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def check_answer():
while True:
response = input('Вы уверены? [Д/н (Y/n)]: ')
try:
print( 0 <= "YyДдNnНн".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, there will be another developer - it is read and parsed worse than the solution from the previous comment , where the positive and negative answers are clearly separated.
Remark
@datacompboy and MamOn pointed out another interesting point. The symbol Y
and Н
on the Russian-language keyboard are on one button, which, if the user inattentively, can lead to completely opposite results. Similar points must also be considered when developing. Therefore, in applications where an error of choice can lead to irreversible results, it is better to require confirmation of Yes
/ No
in order to exclude the possibility of error.
References
- “The worse, the better”
- Do not repeat
- Occam's razor
- Pythonicway: Operators in Python
- Pythonz.net: str.upper method
- Ben Fort “Master your own regular expressions. 10 minutes per lesson "
- Typical Programmer: Using Regular Expressions in Python for Beginners
- Regular expressions in Python: learning and optimizing
- Habrahabr: Regular expressions, a guide for beginners