
Want to learn Python programming from scratch? In this article, we’ll take a closer look at creating basic scripts and controlling the flow of a program—key skills for beginners. You’ll learn how to make a file executable, how to pass arguments to a script via argv, and how to handle user input.
Generally speaking, a script is just a regular file. This file stores a sequence of commands that need to be executed. Let’s start with a basic script. Let’s output a few lines to the standard output stream.
To do this, you need to create a file access_template.py with the following content:
access_template = ['switchport mode access', 'switchport access vlan {}', 'switchport nonegotiate', 'spanning-tree portfast', 'spanning-tree bpduguard enable'] print('\n'.join(access_template).format(5))
First, the list items are combined into a string, which is separated by the \n character, and the string contains the VLAN number, using string formatting. After that, you need to save the file and go to the command line.
This is how the script execution looks like:
$ python access_template.py switchport mode access switchport access vlan 5 switchport nonegotiate spanning-tree portfast spanning-tree bpduguard enable
It is not necessary to put the .py extension on the file, but if you are using Windows, it is advisable to do so, as Windows uses the file extension to determine how to process the file.
In the course, all scripts that will be created use the .py extension. You could say that it is good form to create Python scripts with this extension.
To make the file executable and not have to write python every time before calling the file, you need to:
make file executable (for Linux)
the first line of the file should contain the line #!/usr/bin/env python #!/usr/bin/env python3 depending on which version of Python is used by default
Example of access_template_exec.py file:
#!/usr/bin/env python3 access_template = ['switchport mode access', 'switchport access vlan {}', 'switchport nonegotiate', 'spanning-tree portfast', 'spanning-tree bpduguard enable'] print('\n'.join(access_template).format(5))
Thereafter:
chmod +x access_template_exec.py
Now you can call the file like this:
$ ./access_template_exec.py
Very often a script solves some general problem. For example, a script processes a configuration file in some way. It would be much better to pass the file name as an argument to the script, and then use the file that has already been specified. The sys module allows you to work with script arguments using argv.
Example access_template_argv.py:
from sys import argv interface = argv[1] vlan = argv[2] access_template = ['switchport mode access', 'switchport access vlan {}', 'switchport nonegotiate', 'spanning-tree portfast', 'spanning-tree bpduguard enable'] print('interface {}'.format(interface)) print('\n'.join(access_template).format(vlan))
Checking the script:
$ python access_template_argv.py Gi0/7 4 interface Gi0/7 switchport mode access switchport access vlan 4 switchport nonegotiate spanning-tree portfast spanning-tree bpduguard enable
The arguments that were passed to the script are substituted as template values.
A few points need to be explained here:
argv is a list
all arguments are in the list as strings
argv contains not only the arguments passed to the script, but also the name of the script itself
In this case, the argv list contains the following elements:
['access_template_argv.py', 'Gi0/7', '4']
First comes the name of the script itself, then the arguments in the same order.
Sometimes you need to get information from the user, for example, to request a password.
To get information from the user, you use the input function:
In [1]: print(input('Твой любимый протокол маршрутизации? ')) Твій улюблений протокол маршрутизації? OSPF OSPF
In this case, the information is immediately displayed to the user, but in addition, the information entered by the user can be stored in some variable and can be used further in the script.
In [2]: protocol = input('Твій улюблений протокол маршрутизації? ') Твій улюблений протокол маршрутизації? OSPF In [3]: print(protocol) OSPF
In parentheses, there is usually a question that specifies what information needs to be entered.
Requesting information from the script (file access_template_input.py):
interface = input('Enter interface type and number: ') vlan = input('Enter VLAN number: ') access_template = ['switchport mode access', 'switchport access vlan {}', 'switchport nonegotiate', 'spanning-tree portfast', 'spanning-tree bpduguard enable'] print('\n' + '-' * 30) print('interface {}'.format(interface)) print('\n'.join(access_template).format(vlan))
The first two lines request information from the user. The line is used to visually separate the request for information from the output. print('\n' + '-' * 30)
Script execution:
$ python access_template_input.py Enter interface type and number: Gi0/3 Enter VLAN number: 55 ------------------------------ interface Gi0/3 switchport mode access switchport access vlan 55 switchport nonegotiate spanning-tree portfast spanning-tree bpduguard enable
So far, all code has been executed sequentially – all lines of the script have been executed in the order in which they are written in the file. This section discusses Python’s capabilities in controlling the flow of the program:
branching during the program using if/elif/else constructs
repeating actions in a loop using for and while constructs
handling errors using try/except constructs
The if/elif/else construct allows you to branch during a program. The program branches when a certain condition is met.
In this construct, only if is required, elif and else are optional:
The if test always comes first.
After the if statement, there must be some condition: if this condition is met (returns True), then the actions in the if block are performed.
With elif, you can make several branches, that is, check the input data for different conditions.
The elif block is the same if, but only with the next check. Roughly speaking, it is “what if…”
There can be many elif blocks.
The else block is executed if none of the if or elif conditions were true.
Example of design:
In [1]: a = 9 In [2]: if a == 10: ...: print('a равно 10') ...: elif a < 10: ...: print('a меньше 10') ...: else: ...: print('a больше 10') ...: a менше 10
The if construct is built on conditions: if and elif are always followed by a condition. If/elif blocks are only executed when the condition evaluates to True, so the first thing to understand is what is true and what is false in Python.
In Python, besides the obvious values True and False, all other objects also have a corresponding value of false or true.
True meaning:
any non-zero number
any non-empty string
any non-empty object
False value:
0
None
empty string
empty object
For example, since an empty list is an error value, you can check if a list is empty like this:
In [12]: list_to_test = [1, 2, 3] In [13]: if list_to_test: ....: print("В списке есть объекты") ....: В списку є об'єкти
The same result could be obtained slightly differently:
In [14]: if len(list_to_test) != 0: ....: print("В списке есть объекты") ....: В списку є об'єкти
Comparison operators that can be used in conditions:
In [3]: 5 > 6 Out[3]: False In [4]: 5 > 2 Out[4]: True In [5]: 5 < 2 Out[5]: False In [6]: 5 == 2 Out[6]: False In [7]: 5 == 5 Out[7]: True In [8]: 5 >= 5 Out[8]: True In [9]: 5 <= 10 Out[9]: True In [10]: 8 != 10 Out[10]: True
Note that equality is checked with a double ==.
Example of using comparison operators:
In [1]: a = 9 In [2]: if a == 10: ...: print('a равно 10') ...: elif a < 10: ...: print('a меньше 10') ...: else: ...: print('a больше 10') ...: а менше 10
The in operator allows you to check for the presence of an element in a sequence (for example, an element in a list or a substring in a string):
In [8]: 'Fast' in 'FastEthernet' Out[8]: True In [9]: 'Gigabit' in 'FastEthernet' Out[9]: False In [10]: vlan = [10, 20, 30, 40] In [11]: 10 in vlan Out[11]: True In [12]: 50 in vlan Out[12]: False
When using dictionaries, the in condition checks against the dictionary keys:
In [15]: r1 = { ....: 'IOS': '15.4', ....: 'IP': '10.255.0.1', ....: 'hostname': 'london_r1', ....: 'location': '21 New Globe Walk', ....: 'model': '4451', ....: 'vendor': 'Cisco'} In [16]: 'IOS' in r1 Out[16]: True In [17]: '4451' in r1 Out[17]: False
The logical operators and, or, not can also be used in conditions:
In [15]: r1 = { ....: 'IOS': '15.4', ....: 'IP': '10.255.0.1', ....: 'hostname': 'london_r1', ....: 'location': '21 New Globe Walk', ....: 'model': '4451', ....: 'vendor': 'Cisco'} In [18]: vlan = [10, 20, 30, 40] In [19]: 'IOS' in r1 and 10 in vlan Out[19]: True In [20]: '4451' in r1 and 10 in vlan Out[20]: False In [21]: '4451' in r1 or 10 in vlan Out[21]: True In [22]: not '4451' in r1 Out[22]: True In [23]: '4451' not in r1 Out[23]: True
In Python, the and operator does not return a Boolean value, but rather the value of one of its operands.
If both operands are true, the result of the expression will be the last value:
In [24]: 'string1' and 'string2' Out[24]: 'string2' In [25]: 'string1' and 'string2' and 'string3' Out[25]: 'string3'
If one of the operators is false, the result of the expression will be the first false value:
In [26]: '' and 'string1' Out[26]: '' In [27]: '' and [] and 'string1' Out[27]: ''
The or operator, like the and operator, returns the value of one of its operands.
When evaluating the operands, the first true operand is returned:
In [28]: '' or 'string1' Out[28]: 'string1' In [29]: '' or [] or 'string1' Out[29]: 'string1' In [30]: 'string1' or 'string2' Out[30]: 'string1'
If all values are false, the last value is returned:
In [31]: '' or [] or {} Out[31]: {}
An important feature of the or operator is that the operands that come after the true value are not evaluated:
In [33]: '' or sorted([44, 1, 67]) Out[33]: [1, 44, 67] In [34]: '' or 'string1' or sorted([44, 1, 67]) Out[34]: 'string1'
Example of script check_password.py, which checks the length of the password and whether the password contains the username:
# -*- coding: utf-8 -*- username = input('Введіть ім'я користувача: ') password = input('Введіть пароль: ') if len(password) < 8: print('Пароль занадто короткий') elif username in password: print('Пароль містить ім'я користувача') else: print('Встановлено пароль для користувача {}'.format(ім'я користувача))
Script verification:
$ python check_password.py Введіть ім’я користувача: nata Введіть пароль: nata1234 Пароль містить ім’я користувача $ python check_password.py Введіть ім’я користувача: nata Введіть пароль: 123nata123 Пароль містить ім’я користувача $ python check_password.py Введіть ім’я користувача: nata Введіть пароль: 1234 Надто короткий пароль $ python check_password.py Введіть ім’я користувача: nata Введіть пароль: 123456789 Пароль для користувача nata встановлений
Sometimes it is more convenient to use the ternary operator than the expanded form:
s = [1, 2, 3, 4] result = True if len(s) > 5 else False
It’s better not to overuse this, but in simple terms, such a record can be useful.
Very often, the same action needs to be performed on a set of data of the same type. For example, convert all strings in a list to uppercase. To perform such actions in Python, a for loop is used.
The for loop iterates over the elements of a specified sequence one by one and performs the actions specified in the for block for each element.
Examples of sequences of elements that a for loop can traverse:
string
list
dictionary
range function
any iterable object
Example of converting strings in a list to uppercase without a for loop:
In [1]: words = ['list', 'dict', 'tuple'] In [2]: upper_words = [] In [3]: words[0] Out[3]: 'list' In [4]: words[0].upper() # перетворення слова у верхній реєстр Out[4]: 'LIST' In [5]: upper_words.append(words[0].upper()) # перетворення та додавання в новий список In [6]: upper_words Out[6]: ['LIST'] In [7]: upper_words.append(words[1].upper()) In [8]: upper_words.append(words[2].upper()) In [9]: upper_words Out[9]: ['LIST', 'DICT', 'TUPLE']
This solution has several nuances:
the same action must be repeated several times
the code is tied to a certain number of elements in the words list
The same actions with a for loop:
In [10]: words = ['list', 'dict', 'tuple'] In [11]: upper_words = [] In [12]: for word in words: ...: upper_words.append(word.upper()) ...: In [13]: upper_words Out[13]: ['LIST', 'DICT', 'TUPLE']
The expression means “for each word in the list words, perform the actions in the for block”. In this case, the word is the name of a variable that refers to a different value each iteration of the loop. for word in words: upper_words.append(word.upper()).
The for loop can work with any sequence of elements. For example, above we used a list and the loop iterated over the elements of the list. Similarly for working with tuples.
When working with strings, the for loop iterates over the characters of the string, for example:
In [1]: for letter in 'Test string': ...: print(letter) ...: T e s t s t r i n g
The loop uses a variable named letter. Although the name can be anything, it is useful when the name tells you which objects the loop is going to go through.
Sometimes you need to use a sequence of numbers in a loop. In this case, it is best to use the range function
Example of a for loop with the range() function:
In [2]: for i in range(10): ...: print(f'interface FastEthernet0/{i}') ...: interface FastEthernet0/0 interface FastEthernet0/1 interface FastEthernet0/2 interface FastEthernet0/3 interface FastEthernet0/4 interface FastEthernet0/5 interface FastEthernet0/6 interface FastEthernet0/7 interface FastEthernet0/8 interface FastEthernet0/9
This loop uses range(10). The range function generates numbers in the range from zero to the specified number (in this example, up to 10), but not including it.
In this example, the loop is iterating over the VLAN list, so the variable can be called vlan:
In [3]: vlans = [10, 20, 30, 40, 100] In [4]: for vlan in vlans: ...: print(f'vlan {vlan}') ...: print(f' name VLAN_{vlan}') ...: vlan 10 name VLAN_10 vlan 20 name VLAN_20 vlan 30 name VLAN_30 vlan 40 name VLAN_40 vlan 100 name VLAN_100
When a loop follows a dictionary, it actually follows the keys:
In [34]: r1 = { ...: 'ios': '15.4', ...: 'ip': '10.255.0.1', ...: 'hostname': 'london_r1', ...: 'location': '21 New Globe Walk', ...: 'model': '4451', ...: 'vendor': 'Cisco'} ...: In [35]: for k in r1: ...: print(k) ...: ios ip hostname location model vendor
If you need to output key-value pairs in a loop, you can do this:
In [36]: for key in r1: ...: print(key + ' => ' + r1[key]) ...: ios => 15.4 ip => 10.255.0.1 hostname => london_r1 location => 21 New Globe Walk model => 4451 vendor => Cisco
In [36]: for key in r1: ...: print(key + ' => ' + r1[key]) ...: ios => 15.4 ip => 10.255.0.1 hostname => london_r1 location => 21 New Globe Walk model => 4451 vendor => Cisco
Or use the items method, which allows you to loop through a key-value pair at once:
In [37]: for key, value in r1.items(): ...: print(key + ' => ' + value) ...: ios => 15.4 ip => 10.255.0.1 hostname => london_r1 location => 21 New Globe Walk model => 4451 vendor => Cisco
The items method returns a special view object that displays key-value pairs:
In [38]: r1.items() Out[38]: dict_items([('ios', '15.4'), ('ip', '10.255.0.1'), ('hostname', 'london_r1'), ('location', '21 New Globe Walk'), ('model', '4451'), ('vendor', 'Cisco')])
For loops can be nested within each other.
In this example, the commands list stores the commands to be executed for each of the interfaces in the fast_int list:
In [7]: commands = ['switchport mode access', 'spanning-tree portfast', 'spanning-tree bpduguard enable'] In [8]: fast_int = ['0/1','0/3','0/4','0/7','0/9','0/10','0/11'] In [9]: for intf in fast_int: ...: print('interface FastEthernet {}'.format(intf)) ...: for command in commands: ...: print(' {}'.format(command)) ...: interface FastEthernet 0/1 switchport mode access spanning-tree portfast spanning-tree bpduguard enable interface FastEthernet 0/3 switchport mode access spanning-tree portfast spanning-tree bpduguard enable interface FastEthernet 0/4 switchport mode access spanning-tree portfast spanning-tree bpduguard enable ...
The first for loop goes through the interfaces in the fast_int list, and the second one goes through the commands in the commands list.
Let’s look at an example of combining for and if.
The generate_access_port_config.py file:
1 access_template = ['switchport mode access', 2 'switchport access vlan', 3 'spanning-tree portfast', 4 'spanning-tree bpduguard enable'] 5 6 access = {'0/12': 10, '0/14': 11, '0/16': 17, '0/17': 150} 7 8 for intf, vlan in access.items(): 9 print('interface FastEthernet' + intf) 10 for command in access_template: 11 if command.endswith('access vlan'): 12 print(' {} {}'.format(command, vlan)) 13 else: 14 print(' {}'.format(command))
Code comments:
The first for loop iterates over the keys and values in the nested dictionary access
The current key, at this point in the loop, is stored in the variable intf
The current value, at this point in the loop, is stored in the variable vlan
The string interface FastEthernet is printed with the interface number appended to it
The second for loop iterates over the commands in the access_template list
Because you need to add the VLAN number to the switchport access vlan command:
inside the second for loop the commands are checked
if the command ends with access vlan
the command is output and the VLAN number is appended to it
In all other cases, the command is simply output.
Result of script execution:
$ python generate_access_port_config.py interface FastEthernet0/12 switchport mode access switchport access vlan 10 spanning-tree portfast spanning-tree bpduguard enable interface FastEthernet0/14 switchport mode access switchport access vlan 11 spanning-tree portfast spanning-tree bpduguard enable interface FastEthernet0/16 switchport mode access switchport access vlan 17 spanning-tree portfast spanning-tree bpduguard enable interface FastEthernet0/17 switchport mode access switchport access vlan 150 spanning-tree portfast spanning-tree bpduguard enable
The while loop is another type of loop in Python.
In a while loop, as in an if statement, you need to write a condition. If the condition is true, the actions inside the while block are performed. When using while loops, you need to pay attention to whether a state will be reached in which the loop condition will be false.
Let’s consider a simple example:
In [1]: a = 5 In [2]: while a > 0: ...: print(a) ...: a -= 1 # Эта запись равнозначна a = a - 1 ...: 5 4 3 2 1
First, a variable with the value 5 is created. Then, the while loop specifies the condition a > 0. That is, as long as the value a is greater than 0, the actions in the loop body will be performed. In this case, the value of the variable a will be printed.
In addition, in the loop body, the value a becomes one less with each pass.
The notation may be a little unusual. Python allows you to use this format instead of .a -= 1a = a – 1
Similarly, you can write: , , .a += 1a *= 2a / = 2
Since the value a decreases, the loop will not be infinite, and at some point the expression a > 0 will become false.
The following example is based on the password example from the section on the if construct. Using the while loop, you can make the script itself ask for the password again if it does not meet the requirements.
File check_password_with_while.py:
# -*- coding: utf-8 -*- username = input('Введіть ім'я користувача: ') password = input('Введіть пароль: ') password_correct = False while not password_correct: if len(password) < 8: print('Пароль занадто короткий\n') password = input('Введіть пароль ще раз: ') elif username in password: print('Пароль містить ім'я користувача\n') password = input('Введіть пароль ще раз: ') else: print(f'Пароль для користувача {username} установлен') password_correct = True
In this case, the while loop is useful because it returns the script back to the beginning of the checks, allowing you to type the password again, but without requiring the script itself to be restarted.
Now the script executes like this:
$ python check_password_with_while.py Введіть ім'я користувача: nata Введіть пароль: nata Пароль занадто короткий Введіть пароль ще раз: natanata Пароль містить ім'я користувача Введіть пароль ще раз: 123345345345 Пароль для користувача nata встановлений
Python has several operators that allow you to change the default behavior of loops.
The break operator allows you to interrupt a loop prematurely:
break breaks the current loop and continues execution of the following statements
if multiple nested loops are used, break breaks the inner loop and continues execution of the statements following the block * break can be used in for and while loops
Example with a for loop:
In [1]: for num in range(10): ...: if num < 7: ...: print(num) ...: else: ...: break ...: 0 1 2 3 4 5 6
Example with a while loop:
In [2]: i = 0 In [3]: while i < 10: ...: if i == 5: ...: break ...: else: ...: print(i) ...: i += 1 ...: 0 1 2 3 4
Using break in the password prompt example (file check_password_with_while_break.py):
username = input('Введіть ім'я користувача: ') password = input('Введіть пароль: ') while True: if len(password) < 8: print('Пароль занадто короткий\n') elif username in password: print('Пароль містить ім'я користувача\n') else: print('Пароль для користувача{} установлен'.format(ім'я користувача)) # завершает цикл while break password = input('Введіть пароль ще раз: ')
Now you can avoid repeating the line in each branch, just move it to the end of the loop. password = input(‘Enter password again: ‘)
And as soon as the correct password is entered, break will exit the while loop.
The continue operator returns control to the beginning of the loop. That is, continue allows you to “skip” the remaining expressions in the loop and move on to the next iteration.
Example with a for loop:
In [4]: for num in range(5): ...: if num == 3: ...: continue ...: else: ...: print(num) ...: 0 1 2 4
Example with a while loop:
In [5]: i = 0 In [6]: while i < 6: ....: i += 1 ....: if i == 3: ....: print("Пропускаем 3") ....: continue ....: print("Это никто не увидит") ....: else: ....: print("Текущее значение: ", i) ....: Текущее значение: 1 Текущее значение: 2 Пропускаем 3 Текущее значение: 4 Текущее значение: 5 Текущее значение: 6
Using continue in the password prompt example (file check_password_with_while_continue.py):
username = input('Введите имя пользователя: ') password = input('Введите пароль: ') password_correct = False while not password_correct: if len(password) < 8: print('Пароль слишком короткий\n') elif username in password: print('Пароль содержит имя пользователя\n') else: print('Пароль для пользователя {} установлен'.format(username)) password_correct = True continue password = input('Введите пароль еще раз: ')
Here, the loop exit is performed by checking the password_correct flag. When the correct password has been entered, the flag is set to True, and continue is used to jump to the beginning of the loop, skipping the last line with the password request.
The result of execution will be as follows:
$ python check_password_with_while_continue.py Введите имя пользователя: nata Введите пароль: nata12 Пароль слишком короткий Введите пароль еще раз: natalksdjflsdjf Пароль содержит имя пользователя Введите пароль еще раз: asdfsujljhdflaskjdfh Пароль для пользователя nata установлен
The pass operator does nothing. It is essentially a stub for objects. For example, pass can be useful in situations where you need to specify the structure of a script. It can be used in loops, functions, or classes. And it will not affect the execution of the code.
Example of using pass:
In [6]: for num in range(5): ....: if num < 3: ....: pass ....: else: ....: print(num) ....: 3 4
In for and while loops, you can optionally use an else block.
In a for loop:
the else block is executed if the loop has finished iterating the list
but the else is not executed if a break was executed in the loop
Example of a for loop with else (the else block is executed after the for loop completes):
In [1]: for num in range(5): ....: print(num) ....: else: ....: print("Числа закончились") ....: 0 1 2 3 4 Числа закончились
Example of a for loop with else and break in the loop (because of the break, the else block is not executed):
In [2]: for num in range(5): ....: if num == 3: ....: break ....: else: ....: print(num) ....: else: ....: print("Числа закончились") ....: 0 1 2
Example of a for loop with else and continue in the loop (continue does not affect the else block):
In [3]: for num in range(5): ....: if num == 3: ....: continue ....: else: ....: print(num) ....: else: ....: print("Числа закончились") ....: 0 1 2 4 Числа закончились
In a while loop:
else block is executed if the condition in while is false
else is not executed if break was executed in the loop
Example of a while loop with else (the else block is executed after the while loop completes):
In [4]: i = 0 In [5]: while i < 5: ....: print(i) ....: i += 1 ....: else: ....: print("Конец") ....: 0 1 2 3 4 Конец
Example of a while loop with else and break in the loop (because of the break, the else block is not executed):
In [6]: i = 0 In [7]: while i < 5: ....: if i == 3: ....: break ....: else: ....: print(i) ....: i += 1 ....: else: ....: print("Конец") ....: 0 1 2
If you have repeated the examples used earlier, then there have probably been situations when an error has popped up. Most likely, it was a syntax error, for example, a missing colon.
As a rule, Python reacts quite clearly to such errors, and they can be fixed.
However, even if the code is syntactically correct, there may be errors. In Python, these errors are called exceptions.
Examples of exceptions:
In [1]: 2/0 ----------------------------------------------------- ZeroDivisionError: division by zero In [2]: 'test' + 2 ----------------------------------------------------- TypeError: must be str, not int
In this case, two exceptions occurred: ZeroDivisionError and TypeError.
Most often, you can predict which exceptions will occur during program execution.
For example, if a program expects two numbers as input and outputs their sum, and the user enters a string instead of one of the numbers, a TypeError error will appear, as in the example above.
Python allows you to work with exceptions. You can catch them and perform certain actions if an exception occurs.
When an exception occurs in a program, it immediately terminates.
To work with exceptions, the try/except construct is used:
In [3]: try: ...: 2/0 ...: except ZeroDivisionError: ...: print("You can't divide by zero") ...: You can't divide by zero
The try construct works like this:
the statements written in the try block are executed first
if no exceptions occur during the execution of the try block, the except block is skipped, and the subsequent code is executed
if an exception occurs somewhere during the execution of the try block, the remaining part of the try block is skipped if the exception that occurred is specified in the except block, the code in the except block is executed. If the exception that occurred is not specified in the except block, the program execution is interrupted and an error is issued.
Note that the line Cool! in the try block is not printed:
In [4]: try: ...: print("Let's divide some numbers") ...: 2/0 ...: print('Cool!') ...: except ZeroDivisionError: ...: print("You can't divide by zero") ...: Let's divide some numbers You can't divide by zero
There can be multiple excepts in a try/except construct if different actions are required depending on the type of error.
For example, the script divide.py divides two numbers entered by the user:
# -*- coding: utf-8 -*- try: a = input("Введите первое число: ") b = input("Введите второе число: ") print("Результат: ", int(a)/int(b)) except ValueError: print("Пожалуйста, вводите только числа") except ZeroDivisionError: print("На ноль делить нельзя")
Script execution examples:
$ python divide.py Введите первое число: 3 Введите второе число: 1 Результат: 3 $ python divide.py Введите первое число: 5 Введите второе число: 0 На ноль делить нельзя $ python divide.py Введите первое число: qewr Введите второе число: 3 Пожалуйста, вводите только числа
In this case, the ValueError exception is raised when the user entered a string instead of a number when converting a string to a number. The ZeroDivisionError exception is raised if the second number is 0.
If you don’t need to print different messages for ValueError and ZeroDivisionError errors, you can do this (divide_ver2.py file):
# -*- coding: utf-8 -*- try: a = input("Введите первое число: ") b = input("Введите второе число: ") print("Результат: ", int(a)/int(b)) except (ValueError, ZeroDivisionError): print("Что-то пошло не так...")
Check:
$ python divide_ver2.py Введите первое число: wer Введите второе число: 4 Что-то пошло не так... $ python divide_ver2.py Введите первое число: 5 Введите второе число: 0 Что-то пошло не так...
You can omit a specific exception or exception in the except block. In this case, all exceptions will be caught.
This is not recommended!
The finally block is another optional block in the try construct. It is always executed regardless of whether an exception was thrown or not. This is where you put actions that should be performed in any case. For example, this could be closing a file.
The file divide_ver4.py with the finally block:
# -*- coding: utf-8 -*- try: a = input("Введите первое число: ") b = input("Введите второе число: ") result = int(a)/int(b) except (ValueError, ZeroDivisionError): print("Что-то пошло не так...") else: print("Результат в квадрате: ", result**2) finally: print("Вот и сказочке конец, а кто слушал - молодец.")
# -*- coding: utf-8 -*- try: a = input("Введите первое число: ") b = input("Введите второе число: ") result = int(a)/int(b) except (ValueError, ZeroDivisionError): print("Что-то пошло не так...") else: print("Результат в квадрате: ", result**2) finally: print("Вот и сказочке конец, а кто слушал - молодец.")
Check:
$ python divide_ver4.py Введите первое число: 10 Введите второе число: 2 Результат в квадрате: 25 Вот и сказочке конец, а кто слушал - молодец. $ python divide_ver4.py Введите первое число: qwerewr Введите второе число: 3 Что-то пошло не так... Вот и сказочке конец, а кто слушал - молодец. $ python divide_ver4.py Введите первое число: 4 Введите второе число: 0 Что-то пошло не так... Вот и сказочке конец, а кто слушал - молодец.
In general, the same code can be written with or without exceptions.
For example, this code example:
while True: a = input("Введите число: ") b = input("Введите второе число: ") try: result = int(a)/int(b) except ValueError: print("Поддерживаются только числа") except ZeroDivisionError: print("На ноль делить нельзя") else: print(result) break
You can rewrite it like this without try/except (file try_except_divide.py):
while True: a = input("Введите число: ") b = input("Введите второе число: ") if a.isdigit() and b.isdigit(): if int(b) == 0: print("На ноль делить нельзя") else: print(int(a)/int(b)) break else: print("Поддерживаются только числа")
Not always the same version without using exceptions will be simple and understandable.
It is important to evaluate in each specific situation which version of the code is clearer, more compact and more versatile – with exceptions or without.
If you have previously used some other programming language, there is a chance that using exceptions was considered bad form. In Python, this is not the case. To understand this issue a little, see the links to additional materials at the end of this section.
Sometimes you need to throw an exception in your code, you can do this like this:
raise ValueError("При выполнении команды возникла ошибка")
Python has many built-in exceptions, each of which is thrown in a specific situation.
For example, a TypeError is typically thrown when one data type was expected and another was passed:
In [1]: "a" + 3 --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-1-5aa8a24e3e06> in <module> ----> 1 "a" + 3 TypeError: can only concatenate str (not "int") to str
ValueError when the value does not match the expected value:
In [2]: int("a") --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-2-d9136db7b558> in <module> ----> 1 int("a") ValueError: invalid literal for int() with base 10: 'a'
In this article, we have passed an important stage – we have mastered the basic tools for creating scripts in Python and learned how to control the execution of programs. You have learned how to run scripts, pass arguments, interact with the user, and also control logic using conditions, loops, logical operators and exception handling.
This knowledge is the foundation of any Python program. From a simple password request to complex structures with nested loops and error handling – all this allows you to write clean, safe and manageable code. The most important thing is not to be afraid to experiment. Write, run, make mistakes and learn. Python encourages simplicity and readability – take full advantage of this.