Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Thonny: The Beginner-Friendly Python Editor
Are you a Python beginner looking for a tool that can support your learning? This article is for you! Every programmer needs a place to write their code. This article will discuss an awesome tool called Thonny that will enable you to start working with Python in a beginner-friendly environment.
In this article, you’ll learn:
- How to install Thonny on your computer
- How to navigate Thonny’s user interface to use its built-in features
- How to use Thonny to write and run your code
- How to use Thonny to debug your code
By the end of this article, you’ll be comfortable with the development workflow in Thonny and ready to use it for your Python learning.
So what is Thonny? Great question!
Thonny is a free Python Integrated Development Environment (IDE) that was especially designed with the beginner Pythonista in mind. Specifically, it has a built-in debugger that can help when you run into nasty bugs, and it offers the ability to do step through expression evaluation, among other really awesome features.
Installing Thonny
This article assumes that you have Python 3 installed on your computer. If not, please review Python 3 Installation & Setup.
Web Download
The web download can be accessed via a web browser by visiting the Thonny website. Once on the page, you will see a light gray box in the top right corner like this:
Once you’ve found the gray box, click the appropriate link for your operating system. This tutorial assumes you’ve downloaded version 3.0.1.
Command Line Download
You can also install Thonny via your system’s command line. On Windows, you can do this by starting a program called Command Prompt, while on macOS and Linux you start a program called Terminal. Once you’ve done that, enter the following command:
The User Interface
Let’s make sure you understand what Thonny has to offer. Think of Thonny as the workroom in which you will create amazing Python projects. Your workroom contains a toolbox containing many tools that will enable you to be a rock star Pythonista. In this section, you’ll learn about each of the features of the UI that’ll help you use each of the tools in your Thonny toolbox.
The Code Editor and Shell
Now that you have Thonny installed, open the application. You should see a window with several icons across the top, and two white areas:
Notice the two main sections of the window. The top section is your code editor, where you will write all of your code. The bottom half is your Shell, where you will see outputs from your code.
The Icons
Across the top you’ll see several icons. Let’s explore what each of them does. You’ll see an image of the icons below, with a letter above each one. We will use these letters to talk about each of the icons:
Working our way from left to right, below is a description of each of the icons in the image.
A: The paper icon allows you to create a new file. Typically in Python you want to separate your programs into separate files. You’ll use this button later in the tutorial to create your first program in Thonny!
B: The open folder icon allows you to open a file that already exists on your computer. This might be useful if you come back to a program that you worked on previously.
C: The floppy disk icon allows you to save your code. Press this early and often. You’ll use this later to save your first Thonny Python program.
D: The play icon allows you to run your code. Remember that the code you write is meant to be executed. Running your code means you’re telling Python, “Do what I told you to do!” (In other words, “Read through my code and execute what I wrote.”)
E: The bug icon allows you to debug your code. It’s inevitable that you will encounter bugs when you’re writing code. A bug is another word for a problem. Bugs can come in many forms, sometimes appearing when you use inappropriate syntax and sometimes when your logic is incorrect.
Thonny’s bug button is typically used to spot and investigate bugs. You’ll work with this later in the tutorial. By the way, if you’re wondering why they’re called bugs, there’s also a fun story of how it came about!
F-H: The arrow icons allow you to run your programs step by step. This can be very useful when you’re debugging or, in other words, trying to find those nasty bugs in your code. These icons are used after you press the bug icon. You’ll notice as you hit each arrow, a yellow highlighted bar will indicate which line or section Python is currently evaluating:
- The F arrow tells Python to take a big step, meaning jumping to the next line or block of code.
- The G arrow tells Python to take a small step, meaning diving deep into each component of an expression.
- The H arrow tells Python to exit out of the debugger.
I: The resume icon allows you to return to play mode from debug mode. This is useful in the instance when you no longer want to go step by step through the code, and instead want your program to finish running.
J: The stop icon allows you to stop running your code. This can be particularly useful if, let’s say, your code runs a program that opens a new window, and you want to stop that program. You’ll use the stop icon later in the tutorial.
Let’s Try It!
Get ready to write your first official Python program in Thonny:
-
Enter the following code into the code editor:
-
Click the play button to run your program.
-
See the output in the Shell window.
-
Click the play button again to see that it says hello one more time.
Congratulations! You’ve now completed your first program in Thonny! You should see Hello world!
printed inside the Shell, also known as the console. This is because your program told Python to print this phrase, and the console is where you see the output of this execution.
Other UI Features
To see more of the other features that Thonny has to offer, navigate to the menu bar and select the View dropdown. You should see that Shell has a check mark next to it, which is why you see the Shell section in Thonny’s application window:
Let’s explore some of the other offerings, specifically those that will be useful to a beginning Pythonista:
-
Help: You’ll select the Help view if you want more information about working with Thonny. Currently this section offers more reading on the following topics: Running Programs Step-wise, how to install 3rd Party Packages, or using Scientific Python Packages.
-
Variables: This feature can be very valuable. A variable in Python is a value that you define in code. Variables can be numbers, strings, or other complex data structures. This section allows you to see the values assigned to all of the variables in your program.
-
Assistant: The Assistant is there to give you helpful hints when you hit Exceptions or other types of errors.
The other features will become useful as you advance your skills. Check them out once you get more comfortable with Thonny!
The Code Editor
Now that you have an understanding of the UI, let’s use Thonny to write another little program. In this section, you’ll go through the features of Thonny that will help guide you through your development workflow.
Write Some Code
In the code editor (top portion of the UI), add the following function:
def factorial(num):
if num == 1:
return 1
else:
return num * factorial(num - 1)
print(factorial(3))
Save Your Code
Before we move on, let’s save your program. Last time, you were prompted to do this after pressing the play button. You can also do this by clicking the blue floppy disk icon or by going to the menu bar and selecting File > Save. Let’s call the program factorial.py
.
Run Your Code
In order to run your code, find and press the play icon. The output should look like this:
Debug Your Code
To truly understand what this function is doing, try the step feature. Take a few large and small steps through the function to see what is happening. Remember you can do this by pressing the arrow icons:
As you can see, the steps will show how the computer is evaluating each part of the code. Each pop up window is like a piece of scratch paper that the computer is using to compute each portion of the code. Without this awesome feature, this may have been hard to conceptualize—but now you’ve got it!
Stop Running Your Code
So far, there hasn’t been a need to hit the stop icon for this program, particularly because it exits as soon as it has executed print()
. Try increasing the number being passed to the factorial function to 100
:
def factorial(num):
if num == 1:
return 1
else:
return num * factorial(num - 1)
print(factorial(100))
Then step through the function. After a while, you will notice that you will be clicking for a long time to reach the end. This is a good time to use the stop button. The stop button can be really useful to stop a program that is either intentionally or unintentionally running continuously.
Find Syntax Errors in Your Code
Now that you have a simple program that works, let’s break it! By intentionally creating an error in your factorial program, you’ll be able to see how Thonny handles these types of issues.
We will be creating what is called a syntax error. A syntax error is an error that indicates that your code is syntactically incorrect. In other words, your code does not follow the proper way to write Python. When Python notices the error, it will display a syntax error to complain about your invalid code.
Above the print statement, let’s add another print statement that says print("The factorial of 100 is:")
. Now let’s go ahead and create syntax errors. In the first print statement, remove the second quotation mark, and in the other remove the second parenthesis.
As you do this, you should see that Thonny will highlight your SyntaxErrors
. Missing quotations are highlighted in green, and missing parenthesis are in gray:
For beginners, this is a great resource that will allow you to help spot any typos while you’re writing. Some of the most common and frustrating errors when you start programming are missing quotes and mismatched parentheses.
If you have your Assistant View turned on, you will also notice that it will give you a helpful message to guide you in the right direction when you are debugging:
As you get more comfortable with Thonny, the Assistant can be a useful tool to help you get unstuck!
The Package Manager
As you continue to learn Python, it can be quite useful to download a Python package to use inside of your code. This allows you to use code that someone else has written inside of your program.
Consider an example where you want to do some calculations in your code. Instead of writing your own calculator, you might want to use a third-party package called simplecalculator
. In order to do this, you’ll use Thonny’s package manager.
The package manager will allow you to install packages that you will need to use with your program. Specifically, it allows you to add more tools to your toolbox. Thonny has the built-in benefit of handling any conflicts with other Python interpreters.
To access the package manager, go to the menu bar and select Tools > Manage Packages… This should pop open a new window with a search field. Type simplecalculator
into that field and click the Search button.
The output should look similar to this:
Go ahead and click Install to install this package. You will see a small window pop up showing the system’s logs while it installs the package. Once it completes, you are ready to use simplecalculator
in your code!
In the next section, you will use the simplecalculator
package along with some of the other skills you’ve learned in this tutorial to create a simple calculator program.
Check Your Understanding
You’ve learned so much about Thonny so far! Here’s what you’ve learned:
- Where to write your code
- How to save your code
- How to run your code
- How to stop your code from running
- Where to see your code execute
- How to spot
SyntaxErrors
- How to install third party packages
Let’s check your understanding of these concepts.
Now that you have simplecalculator
installed, let’s create a simple program that will use this package. You’ll also use this as an opportunity to check that you understand some of the UI and development features that you’ve learned thus far in the tutorial.
Part 1: Create a File, Add Some Code, and Understand the Code
In Part 1, you will create a file, and add some code to it! Do your best to try to dig into what the code is actually doing. If you get stuck, check out the Take a Deeper Look window. Let’s get started:
- Start a new file.
- Add the following code into your Thonny code editor:
1from calculator.simple import SimpleCalculator
2
3my_calculator = SimpleCalculator()
4my_calculator.run('2 * 2')
5print(my_calculator.lcd)
This code will print out the result of 2 * 2
to the Thonny Shell in the main UI. To understand what each part of the code is doing, check out the Take a Deeper Look section below.
-
Line 1: This code imports the library
calculator
inside of the package calledsimplecalculator
. From this library, we import the class calledSimpleCalculator
from a file calledsimple.py
. You can see the code here. -
Lines 2: This is a blank line behind code blocks, which is generally a preferred style. Read more about Python Code Quality in this article.
-
Line 3: Here we create an instance of the class
SimpleCalculator
and assign it to a variable calledmy_calculator
. This can be used to run different calculators. If you’re new to classes, you can learn more about object-oriented programming here. -
Line 4: Here we have the calculator run the operation
2 * 2
by callingrun()
and passing in the expression as a string. -
Line 5: Here we print the result of the calculation. You’ll notice in order to get the most recent calculation result, we must access the attribute called
lcd
.
Great! Now that you know exactly what your calculator code is doing, let’s move on to running this code!
Part 2: Save the File, View the Variables, and Run Your Code
Now it’s time to save and run your code. In this section, you’ll make use of two of the icons we reviewed earlier:
- Save your new file as
calculations.py
. - Open the Variables window and make note of the two variables listed. You should see
SimpleCalculator
andmy_calculator
. This section also gives you insight into the value that each variable is pointing to. - Run your code! You should see
4.0
in the output:
Great job! Next you’ll explore how Thonny’s debugger can help you to better understand this code.
Other Great Beginner Features
As you get more comfortable with Thonny, the features in this section will come in quite handy.
Debugging
Using your calculations.py
script, you’re going to use the debugger to investigate what is happening. Update your code in calculations.py
to the following:
from calculator.simple import SimpleCalculator
def create_add_string(x, y):
'''Returns a string containing an addition expression.'''
return 'x + y'
my_calculator = SimpleCalculator()
my_calculator.run(create_add_string(2, 2))
print(my_calculator.lcd)
Hit the save icon to save this version.
You’ll notice the code has a new function called create_add_string()
. If you’re unfamiliar with Python functions, learn more in this awesome Real Python course!
As you inspect the function, you may notice why this script will not work as expected. If not, that’s okay! Thonny is going to help you see exactly what is going on, and squash that bug! Go ahead and run your program and see what happens. The Shell output should be the following:
>>> %Run calculations.py
0
Oh no! Now you can see there is a bug in your program. The answer should be 4! Next, you’ll use Thonny’s debugger to find the bug.
Let’s Try It!
Now that we have a bug in our program, this is a great chance to use Thonny’s debugging features:
-
Click the bug icon at the top of the window. This enters debugger mode.
-
You should see the import statements highlighted. Click the small step arrow icon, the yellow arrow in the middle. Keep pressing this to see how the debugger works. You should notice that it highlights each step that Python takes to evaluate your program. Once it hits
create_add_string()
, you should see a new window pop up. -
Examine the pop up window carefully. You should see that it shows the values for x and y. Keep pressing the small step icon until you see the value that Python will return to your program. It will be enclosed in a light-blue box:
Oh no! There’s the bug! It looks like Python will return a string containing the lettersx
andy
(meaning'x + y'
and not a string containing the values of those variables, like'2 + 2'
, which is what the calculator is expecting.) Each time you see a light-blue box, you can think of this as Python replacing subexpressions with their values, step by step. The pop up window can be thought of as a piece of scratch paper that Python uses to figure out those values. Continue to step through the program to see how this bug results in a calculation of0
. -
The bug here has to do with string formatting. If you are unfamiliar with string formatting, check out this article on Python String Formatting Best Practices. Inside
create_add_string()
, the f-string formatting method should be used. Update this function to the following:def create_add_string(x, y): '''Returns a string containing an addition expression.''' return f'{x} + {y}'
-
Run your program again. You should see the following output:
>>> %Run calculations.py 4.0
Success! You have just demonstrated how the step-by-step debugger can help you find a problem in your code! Next you’ll learn about some other fun Thonny features.
Variable Scope Highlighting
Thonny offers variable highlighting to remind you that the same name doesn’t always mean the same variable. In order for this feature to work, on the menu bar, go to Thonny > Preferences and ensure that Highlight matching names is checked.
Notice in the code snippet below, that create_add_string()
now has a new variable called my_calculator
, though this is not the same as the my_calculator
on lines 10 and 11. You should be able to tell because Thonny highlights the variables that reference the same thing. This my_calculator
inside the function only exists within the scope of that function, which is why it is not highlighted when the cursor is on the other my_calculator
variable on line 10:
This feature can really help you avoid typos and understand the scope of your variables.
Code Completion
Thonny also offers code completion for APIs. Notice in the snapshot below how pressing the Tab key shows the methods available from the random
library:
This can be very useful when you’re working with libraries and don’t want to look at the documentation to find a method or attribute name.
Working on a Pre-Existing Project
Now that you’ve learned the basic features of Thonny, let’s explore how you can use it to work on a pre-existing project.
Find a File on Your Computer
Opening a file on your computer is as easy as going to the menu bar, selecting File > Open, and using your browser to navigate to the file. You can also use the open folder icon at the top of the screen to do this as well.
If you have a requirements.txt
file and pip
locally installed, you can pip install
these from the Thonny system Shell. If you don’t have pip installed, remember you can use the Package Manager to install it:
$ pip install -r requirements.txt
Work on a Project From Github
Now that you are a Thonny expert, you can use it to work on the exercises from Real Python Course 1: Introduction to Python:
-
Navigate to the Real Python GitHub repo called book1-exercises.
-
Click the green button labeled Clone or download and select Download Zip.
-
Click the opening folder icon to navigate and find the downloaded files. You should find a folder called
book1-exercises1
. -
Open one of the files and start working!
This is useful because there are tons of cool projects available on GitHub!
Conclusion
Awesome job getting through this tutorial on Thonny!
You can now start using Thonny to write, debug, and run Python code! If you like Thonny, you might also like some of the other IDEs we’ve listed in Python IDEs and Code Editors (Guide).
Thonny is actively maintained, and new features are being added all the time. There are several awesome new features that are currently in beta that can be found on the Thonny Blog. Thonny’s main development takes place at the Institute of Computer Science of the University of Tartu, Estonia, as well as by contributors around the world.
Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Thonny: The Beginner-Friendly Python Editor
Вы новичок в Python, ищите инструмент, который бы поддерживал ваше обучение? Эта статья для вас! Каждому программисту нужно место для написания своего кода. В этой статье будет обсуждаться замечательный инструмент под названием Thonny, который позволит вам начать работу с Python в среде, удобной для начинающих.
*В этой статье вы узнаете:*
-
Как установить Thonny на свой компьютер
-
Как ориентироваться в пользовательском интерфейсе Thonny, чтобы использовать его встроенные функции
-
Как использовать Thonny для написания и запуска вашего кода
-
Как использовать Thonny для отладки вашего кода
К концу этой статьи вы освоитесь с процессом разработки в Thonny и будете готовы использовать его для изучения Python.
Так что же такое Тонни? Отличный вопрос!
Thonny — это бесплатная интегрированная среда разработки Python (IDE), специально разработанная для начинающих Pythonista. В частности, у него есть встроенный отладчик, который может помочь, когда вы сталкиваетесь с неприятными ошибками, и он предлагает возможность выполнять пошаговую оценку выражений, помимо других действительно потрясающих функций.
*Бесплатный образец главы:* ссылка: [Загрузите бесплатный образец главы из курса Real Python] и получите практические навыки программирования на Python.
Установка Тонни
В этой статье предполагается, что на вашем компьютере установлен Python 3. Если нет, просмотрите Python 3 Установка и настройка.
Загрузка через Интернет
Доступ к веб-загрузке можно получить через веб-браузер, посетив веб-сайт Thonny. Оказавшись на странице, вы увидите светло-серую рамку в правом верхнем углу, например:
Как только вы нашли серое поле, нажмите на соответствующую ссылку для вашей операционной системы. В этом руководстве предполагается, что вы загрузили версию 3.0.1.
Загрузка из командной строки
Вы также можете установить Thonny через командную строку вашей системы. В Windows вы можете сделать это, запустив программу под названием Command Prompt , а в macOS и Linux вы запустите программу под названием Terminal . Сделав это, введите следующую команду:
Интерфейс пользователя
Давайте удостоверимся, что вы понимаете, что может предложить Тонни. Думайте о Тонни как о рабочей комнате, в которой вы будете создавать удивительные проекты Python. Ваша рабочая комната содержит набор инструментов, содержащий множество инструментов, которые позволят вам стать рок-звездой Pythonista. В этом разделе вы узнаете о каждой из функций пользовательского интерфейса, которые помогут вам использовать каждый из инструментов в наборе инструментов Thonny.
Редактор кода и оболочка
Теперь, когда у вас установлен Thonny, откройте приложение. Вы должны увидеть окно с несколькими значками в верхней части и двумя белыми областями:
Обратите внимание на два основных раздела окна. В верхнем разделе находится ваш редактор кода, где вы будете писать весь свой код. Нижняя половина — это ваша оболочка, где вы увидите выходные данные из вашего кода.
Иконы
Вверху вы увидите несколько значков. Давайте рассмотрим, что делает каждый из них. Вы увидите изображение значков ниже, с буквой над каждым. Мы будем использовать эти буквы, чтобы поговорить о каждой иконке:
Направляясь слева направо, ниже приведено описание каждого из значков на изображении.
*A:* Значок бумаги позволяет создать новый файл. Обычно в Python вы хотите разделить ваши программы на отдельные файлы. Вы будете использовать эту кнопку позже в руководстве, чтобы создать свою первую программу в Thonny!
*B:* Значок открытой папки позволяет открыть файл, который уже существует на вашем компьютере. Это может быть полезно, если вы вернетесь к программе, над которой работали ранее.
*C:* Значок дискеты позволяет сохранить ваш код. Нажмите это рано и часто. Вы будете использовать это позже, чтобы сохранить свою первую программу Thonny Python.
*D:* Значок воспроизведения позволяет запускать ваш код. Помните, что код, который вы пишете, предназначен для выполнения. Запуск вашего кода означает, что вы говорите Python: «Делай то, что я тебе говорил!» (Другими словами: «Прочитайте мой код и выполните то, что я написал».)
*E:* Значок ошибки позволяет отлаживать ваш код. Это неизбежно, что вы будете сталкиваться с ошибками, когда вы пишете код. Ошибка - другое слово для проблемы. Ошибки могут проявляться во многих формах, иногда они появляются, когда вы используете неподходящий синтаксис, а иногда, когда ваша логика неверна.
Кнопка ошибки Тонни обычно используется для выявления и изучения ошибок. Вы будете работать с этим позже в этом уроке. Кстати, если вы задаетесь вопросом, почему их называют ошибками, есть также забавная story о том, как это произошло!
*F-H:* Значки со стрелками позволяют запускать ваши программы шаг за шагом. Это может быть очень полезно, когда вы отлаживаете или, другими словами, пытаетесь найти эти неприятные ошибки в вашем коде. Эти значки используются после нажатия значка ошибки. Когда вы нажмете на каждую стрелку, вы заметите, что желтая подсвеченная полоса укажет, какую линию или раздел Python в настоящее время оценивает:
*Стрелка* F * указывает Python сделать большой шаг, означающий переход к следующей строке или блоку кода. *Стрелка* G * указывает Python сделать небольшой шаг, что означает углубление в каждый компонент выражения. *Стрелка* H * указывает Python выйти из отладчика.
*I:* Значок возобновления позволяет вам вернуться в режим воспроизведения из режима отладки. Это полезно в том случае, когда вы больше не хотите пошагово проходить по коду и вместо этого хотите, чтобы ваша программа завершила работу.
*J:* Значок остановки позволяет вам остановить выполнение кода. Это может быть особенно полезно, если, скажем, ваш код запускает программу, которая открывает новое окно, и вы хотите остановить эту программу. Вы будете использовать значок остановки позже в руководстве.
Давай попробуем!
Будьте готовы написать свою первую официальную программу на Python на Thonny:
-
Введите следующий код в редакторе кода:
-
Нажмите кнопку воспроизведения, чтобы запустить вашу программу.
-
Смотрите вывод в окне оболочки.
-
Нажмите кнопку воспроизведения еще раз, чтобы увидеть, что он говорит привет еще раз.
Поздравляем! Вы закончили свою первую программу в Тонни! Вы должны увидеть + Hello world! +
Внутри Shell, также называемой консолью. Это потому, что ваша программа сказала Python напечатать эту фразу, а консоль — это место, где вы видите результат этого выполнения.
Другие функции интерфейса
Чтобы увидеть больше других функций, которые может предложить Тонни, перейдите к строке меню и выберите раскрывающийся список View. Вы должны увидеть, что рядом с Shell стоит галочка, вот почему вы видите раздел Shell в окне приложения Thonny:
Давайте рассмотрим некоторые другие предложения, в частности те, которые будут полезны для начинающего Pythonista:
-
Справка: Вы выберете представление Help, если хотите получить больше информации о работе с Thonny. В настоящее время этот раздел предлагает дополнительные материалы для чтения по следующим темам: Полезное выполнение программ, _ Как установить _3-й пакет сторонних разработчиков или Использование пакетов Scientific Python.
-
Переменные: Эта функция может быть очень ценной. Переменная в Python — это значение, которое вы определяете в коде. Переменными могут быть числа, строки или другие сложные структуры данных. В этом разделе вы можете увидеть значения, назначенные всем variables в вашей программе.
-
Помощник: Помощник здесь, чтобы дать вам полезные советы, когда вы нажимаете Исключения или другие типы ошибок.
Другие функции станут полезными по мере развития ваших навыков. Проверьте их, как только вы освоитесь с Тонни!
Редактор кода
Теперь, когда у вас есть понимание пользовательского интерфейса, давайте использовать Тонни, чтобы написать еще одну небольшую программу. В этом разделе вы познакомитесь с функциями Thonny, которые помогут вам в процессе разработки.
Напишите некоторый код
В редакторе кода (верхняя часть пользовательского интерфейса) добавьте следующую функцию:
def factorial(num):
if num == 1:
return 1
else:
return num *factorial(num - 1)
print(factorial(3))
Сохраните ваш код
Прежде чем мы продолжим, давайте сохраним вашу программу. В прошлый раз вам предложили сделать это после нажатия кнопки воспроизведения. Вы также можете сделать это, нажав синий значок дискеты или перейдя в строку меню и выбрав File> Save. Давайте назовем программу + factorial.py +
.
Запустите ваш код
Чтобы запустить код, найдите и нажмите значок воспроизведения. Вывод должен выглядеть так:
Отладка вашего кода
Чтобы по-настоящему понять, что делает эта функция, попробуйте функцию step. Сделайте несколько больших и маленьких шагов через функцию, чтобы увидеть, что происходит. Помните, что вы можете сделать это, нажав значки со стрелками:
Как вы можете видеть, шаги покажут, как компьютер оценивает каждую часть кода. Каждое всплывающее окно похоже на бумажку, которую компьютер использует для вычисления каждой части кода. Без этой потрясающей функции это, возможно, было бы трудно осмыслить, но теперь вы ее получили!
Прекратите запуск вашего кода
До сих пор не было необходимости нажимать значок остановки для этой программы, особенно потому, что она завершается, как только она выполняет + print () +
. Попробуйте увеличить число, передаваемое факториальной функции, до + 100 +
:
def factorial(num):
if num == 1:
return 1
else:
return num* factorial(num - 1)
print(factorial(100))
Затем перейдите через функцию. Через некоторое время вы заметите, что будете долго нажимать, чтобы дойти до конца. Это хорошее время, чтобы использовать кнопку остановки. Кнопка «Стоп» может быть действительно полезна для остановки программы, которая намеренно или непреднамеренно работает непрерывно.
Найти синтаксические ошибки в вашем коде
Теперь, когда у вас есть простая программа, которая работает, давайте сломаем ее! Умышленно создавая ошибку в своей факториальной программе, вы сможете увидеть, как Thonny справляется с этими типами проблем.
Мы будем создавать то, что называется синтаксической ошибкой . Синтаксическая ошибка — это ошибка, которая указывает, что ваш код синтаксически неверен. Другими словами, ваш код не следует правильному способу написания Python. Когда Python замечает ошибку, он отображает синтаксическую ошибку, чтобы пожаловаться на неверный код.
Над оператором print добавим еще один оператор print, который говорит + print (" Факториал 100 равен: ") +
. Теперь давайте продолжим и создадим синтаксические ошибки. В первом операторе печати удалите вторую кавычку, а в другом удалите вторую скобку.
Когда вы сделаете это, вы увидите, что Thonny выделит ваши + SyntaxErrors +
. Недостающие цитаты выделены зеленым цветом, а недостающие скобки — серым:
Для начинающих это отличный ресурс, который поможет вам обнаружить любые опечатки во время написания. Некоторые из наиболее распространенных и разочаровывающих ошибок при запуске программирования — отсутствие кавычек и несоответствующих скобок.
Если у вас включен Assistant View, вы также заметите, что он даст вам полезное сообщение, которое поможет вам в правильном направлении при отладке:
Когда вы будете чувствовать себя более комфортно с Тонни, помощник может стать полезным инструментом, который поможет вам разобраться!
Диспетчер пакетов
Поскольку вы продолжаете изучать Python, может быть весьма полезно загрузить пакет Python для использования внутри вашего кода. Это позволяет вам использовать код, который кто-то другой написал внутри вашей программы.
Рассмотрим пример, в котором вы хотите выполнить некоторые вычисления в своем коде. Вместо написания собственного калькулятора, вы можете использовать third-party пакет, называемый + simplecalculator +
. Для этого вам понадобится менеджер пакетов Thonny.
Менеджер пакетов позволит вам установить пакеты, которые вам понадобятся в вашей программе. В частности, это позволяет вам добавить больше инструментов в ваш набор инструментов. Thonny имеет встроенное преимущество обработки любых конфликтов с другими интерпретаторами Python.
Чтобы получить доступ к менеджеру пакетов, перейдите в строку меню и выберите Tools> Manage Packages… _ Это должно открыть новое окно с полем поиска. Введите + simplecalculator +
в это поле и нажмите кнопку _Search.
Вывод должен выглядеть примерно так:
Идите дальше и нажмите Install, чтобы установить этот пакет. Вы увидите всплывающее небольшое окно, в котором отображаются журналы системы во время установки пакета. После завершения вы готовы использовать + simplecalculator +
в своем коде!
В следующем разделе вы будете использовать пакет + simplecalculator +
вместе с некоторыми другими навыками, которые вы узнали в этом руководстве, для создания простой программы калькулятора.
Проверьте свое понимание
Вы так много узнали о Тонни! Вот что вы узнали:
-
Где написать свой код
-
Как сохранить свой код
-
Как запустить ваш код
-
Как остановить ваш код от запуска
-
Где увидеть выполнение вашего кода
-
Как определить
+ SyntaxErrors +
*Как установить сторонние пакеты
Давайте проверим ваше понимание этих концепций.
Теперь, когда у вас установлен + simplecalculator +
, давайте создадим простую программу, которая будет использовать этот пакет. Вы также будете использовать это как возможность проверить, понимаете ли вы некоторые из пользовательских интерфейсов и функций разработки, которые вы изучили до сих пор в этом руководстве.
Часть 1. Создание файла, добавление некоторого кода и понимание кода
В первой части вы создадите файл и добавите к нему некоторый код! Делайте все возможное, чтобы попытаться понять, что на самом деле делает код. Если вы застряли, посмотрите на Take a Deeper Look window. Давайте начнем:
-
Начать новый файл.
-
Добавьте следующий код в редактор кода Thonny:
1 from calculator.simple import SimpleCalculator
2
3 my_calculator = SimpleCalculator()
4 my_calculator.run('2* 2')
5 print(my_calculator.lcd)
Этот код выведет результат +2 * 2 +
в оболочку Thonny в главном интерфейсе пользователя. Чтобы понять, что делает каждая часть кода, ознакомьтесь с разделом Take a Deeper Look ниже.
Большой! Теперь, когда вы точно знаете, что делает код вашего калькулятора, давайте перейдем к выполнению этого кода!
Часть 2. Сохраните файл, просмотрите переменные и запустите ваш код
Теперь пришло время сохранить и запустить ваш код. В этом разделе вы будете использовать две иконки, которые мы рассмотрели ранее:
-
Сохраните новый файл как
+ computing.py +
. -
Откройте окно Variables и запишите две перечисленные переменные. Вы должны увидеть
+ SimpleCalculator +
и+ my_calculator +
. Этот раздел также дает вам представление о значении, на которое указывает каждая переменная. -
Запустите свой код! Вы должны увидеть
+ 4.0 +
в выводе:
Отличная работа! Далее вы узнаете, как отладчик Thonny может помочь вам лучше понять этот код.
Другие отличные особенности для начинающих
По мере того, как вы будете чувствовать себя более комфортно с Тонни, функции в этом разделе будут весьма полезными.
отладка
Используя ваш скрипт + computing.py +
, вы будете использовать отладчик для расследования происходящего. Обновите ваш код в + computing.py +
до следующего:
from calculator.simple import SimpleCalculator
def create_add_string(x, y):
'''Returns a string containing an addition expression.'''
return 'x + y'
my_calculator = SimpleCalculator()
my_calculator.run(create_add_string(2, 2))
print(my_calculator.lcd)
Нажмите значок сохранения, чтобы сохранить эту версию.
Вы заметите, что в коде есть новая функция + create_add_string () +
. Если вы не знакомы с функциями Python, узнайте больше на thsomes курс Real Python!
При проверке функции вы можете заметить, почему этот скрипт не будет работать должным образом. Если нет, то все в порядке! Тонни поможет вам точно понять, что происходит, и уничтожит эту ошибку! Идите вперед и запустите вашу программу и посмотрите, что произойдет Вывод Shell должен быть следующим:
>>> %Run calculations.py
0
о нет! Теперь вы можете видеть, что в вашей программе есть ошибка. Ответ должен быть 4! Далее вы будете использовать отладчик Тонни, чтобы найти ошибку.
Давай попробуем!
Теперь, когда у нас есть ошибка в нашей программе, это отличный шанс использовать функции отладки Thonny:
-
Нажмите на значок ошибки в верхней части окна. Это входит в режим отладчика.
-
Вы должны увидеть выделенные операторы импорта. Нажмите на маленький значок стрелки шага, желтая стрелка посередине. Продолжайте нажимать, чтобы увидеть, как работает отладчик. Вы должны заметить, что он выделяет каждый шаг, который делает Python для оценки вашей программы. Как только он нажмет
+ create_add_string () +
, вы увидите всплывающее окно. -
Внимательно осмотрите всплывающее окно. Вы должны увидеть, что он показывает значения для х и у. Нажимайте на маленький значок шага, пока не увидите значение, которое Python вернет вашей программе. Он будет заключен в голубую рамку:
о нет! Это ошибка! Похоже, что Python вернет строку, содержащую буквы+ x +
и+ y +
(означающие+ 'x + y' +
, а не строку, содержащую значения этих переменных, например+ '2 + 2' + `, чего и ожидает калькулятор.) Каждый раз, когда вы видите светло-синий прямоугольник, вы можете думать об этом как о Python, заменяющем подвыражения их значениями, шаг за шагом. Всплывающее окно можно рассматривать как лист бумаги, который Python использует для определения этих значений. Продолжайте просматривать программу, чтобы увидеть, как эта ошибка приводит к вычислению `+ 0 +
. -
Ошибка здесь связана с форматированием строки. Если вы не знакомы с форматированием строк, ознакомьтесь с этой статьей на Python Рекомендации по форматированию строк. Внутри
+ create_add_string () +
следует использовать the метод форматирования f-строки. Обновите эту функцию следующим образом:
def create_add_string(x, y):
'''Returns a string containing an addition expression.'''
return f'{x} + {y}'
-
Запустите вашу программу снова. Вы должны увидеть следующий вывод:
>>> %Run calculations.py
4.0
Успех! Вы только что продемонстрировали, как пошаговый отладчик может помочь вам найти проблему в вашем коде! Далее вы узнаете о некоторых других забавных функциях Thonny.
Подсветка переменной области
Тонни предлагает подсветку переменных, чтобы напомнить вам, что одно и то же имя не всегда означает одну и ту же переменную. Чтобы эта функция работала, в строке меню перейдите к Thonny> Preferences и убедитесь, что Highlight соответствует именам отмечен.
Обратите внимание на фрагмент кода ниже, что + create_add_string () +
теперь имеет новую переменную с именем + my_calculator +
, хотя это не то же самое, что + my_calculator +
в строках 10 и 11. Вы должны быть в состоянии сказать, потому что Тонни выделяет переменные, которые ссылаются на одно и то же. Этот + my_calculator +
внутри функции существует только внутри области действия этой функции, поэтому он не выделяется, когда курсор находится на другой переменной + my_calculator +
в строке 10:
Эта функция действительно может помочь вам избежать опечаток и понять область действия ваших переменных.
Завершение кода
Тонни также предлагает завершение кода для API. Обратите внимание на снимок ниже, как нажатие клавиши [.keys] # Tab # показывает методы, доступные из библиотеки + random +
:
Это может быть очень полезно, когда вы работаете с библиотеками и не хотите просматривать документацию, чтобы найти метод или имя атрибута.
Работа над уже существующим проектом
Теперь, когда вы изучили основные функции Thonny, давайте рассмотрим, как вы можете использовать его для работы над уже существующим проектом.
Найти файл на вашем компьютере
Открыть файл на вашем компьютере так же просто, как перейти к строке меню, выбрать File> Open и использовать браузер для перехода к файлу. Вы также можете использовать значок открытой папки в верхней части экрана, чтобы сделать это.
Если у вас есть файл + needs.txt +
и + pip +
, установленные локально, вы можете + pip install +
из командной консоли Thonny. Если у вас не установлен pip, помните, что вы можете использовать ссылку: # the-package-manager [Package Manager], чтобы установить его:
$ pip install -r requirements.txt
Работа над проектом от Github
Теперь, когда вы являетесь экспертом Thonny, вы можете использовать его для работы над упражнениями из Real Python Course 1: Введение в Python:
-
Перейдите к репозиторию Real Python GitHub, который называется book1-exercises.
-
Нажмите зеленую кнопку с надписью Clone или download и выберите Download Zip.
-
Нажмите на значок открывающейся папки, чтобы найти и найти загруженные файлы. Вы должны найти папку с именем
+ book1-упражнения1 +
. -
Откройте один из файлов и начните работать!
Это полезно, потому что на GitHub есть множество интересных проектов!
Заключение
Удивительная работа, проходящая через этот урок на Тонни!
Теперь вы можете начать использовать Thonny для написания, отладки и запуска кода Python! Если вам нравится Thonny, вам также могут понравиться некоторые другие IDE, которые мы перечислили в Python IDE и редакторах кода (Руководство).
Тонни активно поддерживается, и все время добавляются новые функции. В настоящее время в бета-версии есть несколько потрясающих новых функций, которые можно найти в блоге Thonny. Основное развитие Тонни происходит в Institute of Computer Science University of Tartu, Эстония, а также авторами по всему миру.
If you’re new to programming and looking to get started with Python on a Raspberry Pi, Thonny IDE is a great choice. In fact, even as a seasoned developer, I tend to use it regularly for simple Python projects. I find it easier to stay focused on your code than on more powerful solutions.
Thonny is a beginner-friendly Python code editor that comes pre-installed on Raspberry Pi OS. The interface is clean and simple, and the built-in Python interpreter means that we can start coding right away without having to install anything else.
In this article, I’ll walk you through the steps you need to take to get started with Thonny on your Raspberry Pi. By the end of this guide, you’ll be able to use Thonny like a pro, and use all the advanced features that come with it (and are often unknown because they are hidden so they don’t scare beginners ^^).
By the way, if you get overwhelmed as soon as Python is required for a project, I recommend checking out my e-book “Master Python on Raspberry Pi“. It will guide you step-by-step to learn the essential concepts (and only the essential concepts) required to achieve any project in the future. Raspberry Pi without Python is like a car without an engine, you miss all the fun parts. Get 10% off by downloading it today!
Setting up Thonny on Raspberry Pi
Raspberry Pi OS
If you use Raspberry Pi OS with a desktop environment, you already have Thonny installed on your system.
It’s a default application that comes with both versions (the full version, “with recommended software” but also the desktop edition). Check my Raspberry Pi OS guide here if you need more details.
You can find Thonny under programming in the main menu.
If you don’t see it, maybe you removed it manually, check the following instructions to reinstall it on your system.
Other distributions
Thonny is a free Python IDE, available on all platforms and systems. So, it’s pretty easy to install it on your Raspberry Pi, whatever operating system you use. It’s even available on Windows and Mac if you want to try it on your computer.
On most Linux distributions, you can use your package manager to install it:
- On any Debian-based distributions (like Ubuntu):
sudo apt install thonny
- On Fedora and Red Hat-based distributions:
sudo dnf install thonny
And if it doesn’t work, you can try other options (not tested):
- You can also try Snap or Flatpak if it’s not available in your default repositories:
sudo snap install thonny-ide
flatpak install org.thonny.Thonny - There is also a script available for other cases:
bash <(wget -O - https://thonny.org/installer-for-linux)
Check their GitHub project for more details.
So, whatever your case may be, it shouldn’t be difficult to install Thonny on your Raspberry Pi. And I guess 90% of you already have it, so let’s move into an introduction about the user interface.
Overview of the Thonny user interface
The goal of the Raspberry Pi (and the system, too) is to be accessible to young students. The whole idea is to help them learn how to code with an inexpensive device and an intuitive interface (full story here).
By default, Thonny is set up on Raspberry Pi OS with a minimalist interface, looking like this:
Grab my Python cheat sheet!
If like me, you always mix the languages syntax, download my cheat sheet for Python here!
Download now
Top menu
At the top of the window, you have one row with big buttons, for the main actions you can use with Thonny: create a new file, save, run your code, etc.
No complicated menus and submenus, when you code for the first time, you don’t need anything fancy. But don’t worry, we’ll see that it’s possible to switch to a more traditional mode, with all the options at hand.
Editor
The editor window, just below the top menu, is where you will write your Python code.
By default, it provides syntax highlighting, and there are other helpful features you can enable, as we’ll see later.
You can have several files open in different tabs. You can right-click on this section of the window to get access to a few “advanced” features. More about this later.
Shell
Finally, the shell window at the bottom of the window, is where you’ll see the result of your script, or can run Python commands directly.
It’s only for Python commands, you can’t use it for traditional Linux commands.
And if you need to clear the history, you can do this with a right-click.
Writing your first Python script with Thonny
The goal of this article is not to teach you how to write Python scripts, but if it’s your first time with Thonny, you might also be pretty new to Python. So, here is a quick summary of how you can write Python code in Thonny.
- Start by writing your Python code in the editor section of the interface.
For a quick test, you can just copy & paste this line:print("Hello Thonny!")
- Click on the “Save” button in the menu bar, and save the file with a “.py” extension.
For example: “test.py”. - Then, click on “Run” to test your script.
When you run a script, you’ll see the result in the Shell just below:
If you made a mistake in your code, it will also show up in the Shell, with the related Python error (as if you were running it with a command line).
Download Your Essential Linux Commands Guide!
It’s a free PDF guide containing every Raspberry Pi Linux command you should know!
Download now
Reminder: Remember that all the members of my community get access to this website without ads, exclusive courses and much more. You can become part of this community for as little as $5 per month & get all the benefits immediately.
Advanced features of Thonny
Even if Thonny has a minimalist interface by default, with most features hidden from new users, it doesn’t mean it’s a weak editor. Once you’re a bit more advanced with Python, and don’t fear a more complete interface, I recommend switching to the regular mode and enjoying all the built-in features.
Customize Thonny interface
You don’t have to stay with this childish interface forever. Once in regular mode, you’ll have access to all the options to customize the Thonny interface to your liking.
Switch to regular mode
If you have the top bar with the big buttons (which is the default style on Raspberry Pi OS), you can switch to a more traditional layout by clicking on “Switch to regular mode” in the top-right corner:
You need to restart the application to update the interface.
Once done, it should look like this:
You still have the top bar with the same buttons, but they are much smaller. More importantly, you get access to the full menu, with all the options we’ll need to take advantage of all the features.
Change theme
By default, (on Raspberry Pi OS at least), Thonny uses the same style as the whole desktop environment theme (which is not my favorite, as explained here). But you can now change that easily:
Grab my Python cheat sheet!
If like me, you always mix the languages syntax, download my cheat sheet for Python here!
Download now
- Now that you have access to the full menu, go to Tools > Options.
- Click on the “Theme & Font” tab.
- You’ll see a few options where you can choose a different theme for the interface, the code highlighting and also pick a custom font for the editor and the shell (or just change their size).
The configuration looks like this, with the “Clean Dark Blue” theme already applied:
You also need to restart Thonny to get the new theme applied entirely. Here is what it looks like after changing it:
It is no longer a childish interface, it’s very close to what you can get with a traditional code IDE like Visual Studio Code, Sublime Text or whatever. And I’ll show you other interesting features that I discovered while researching this article, so you might not know them either.
Code completion
Thonny has a code completion feature built-in by default.
It doesn’t work the same as the other editors I use, so I didn’t know it was available directly.
The goal of a code completion feature is to help you find a function name, by suggesting what seems the most likely depending on your code. It basically looks like this:
Thonny knows I’m looking for a function from the “time” module, so it shows me a list of all of them, with a short description of what each one does.
For most code editors, this is automatic and the editor will suggest all the possibilities to you. With Thonny, you have to ask for help when you need it :-). Press “CTRL+SPACE” to get this tooltip to show up.
There is also something similar if you need help with the function’s parameters.
Pressing “CTRL+SHIFT+SPACE” while calling any method with parameters will show a different tooltip:
In this example, I can see that the count() method on a string has three parameters in this order: x (the substring), start and end. The last two are optional. It can be a time saver when you work with libraries you’re not used to.
Code analysis
Thonny also comes with some interesting code analysis features that are especially useful for beginners.
When you get an error while running your script, or during the debug process, you’ll get the raw Python error in the shell. This is classic, nothing exceptional here.
But you can also enable the assistant (under View in the menu, if it’s not enabled by default) and get some additional help from it:
In this example, “unexpected EOF while parsing” is not very helpful. If you are an advanced programmer, you’ll quickly understand what’s going on, but for beginners (or if you have no idea), the assistant explains more clearly that I have an issue with missing parentheses.
The assistant can also give useful tips even when your code is working:
In this case, I’m importing a module (“time”) that I don’t use at all in my script. It’s obvious in this example, but with longer scripts, it can be useful.
Thonny can suggest many other things to improve your project, so it might be a good idea to enable this tool from time to time.
Thonny keyboard shortcuts
Thonny comes with many useful keyboard shortcuts that can help you work faster and more efficiently.
In addition to the classical shortcuts I won’t list here (CTRL+C, CTRL+V, CTRL+A, etc.), here are a few interesting ones:
Keyboard shortcut | Action |
---|---|
CTRL + R | Run the current script |
TAB | Indent selected lines |
SHIFT + TAB | Dedent selected lines |
CTRL + 3 | Comment selected lines |
ALT + 4 | Uncomment selected lines |
CTRL + G | Go (to specified line) |
CTRL + SPACE | Suggest auto-complete |
CTRL + SHIFT + SPACE | Show parameter info |
CTRL + L | Clear shell |
Optional views
As for the assistant, there are many views available that are not enabled by default, to keep the interface as clean as possible.
But if you are used to a more traditional editor, you’ll probably want to enable a few of them. You can find the list in the menu, under “View”.
For example, the “Files” view will display the file explorer on the side. You can also enable the “TODO” view to list all the TODO comments from your code in one window or enable the “Variable” view to have a summary of the variables you use.
Manage plugins and extensions
When you code in Python, you’re always using external libraries, from the PIP repository for example. Thonny has a nice feature built-in to manage them.
You can browse and install these plugins from the “Tools” menu by clicking on “Manage Plugins”. From there, you can search for plugins, install them, and manage their settings:
In one click, you can install most modules from PyPi without having to type any command line.
Switch Python version
Finally, one last thing I want to say about the Thonny options is that you can easily switch the Python version used from the “Interpreter” tab:
It was particularly useful on old Raspberry Pi OS versions when they were Python 2 and 3 installed by default. But even now, if you installed a more recent Python version manually, you can use this to switch to it for your project.
I hope this guide was useful, and that you discovered a few interesting features about Thonny you didn’t know about. If you want to know more about Python, I have plenty of tutorials on this website. Feel free to check them to learn even more:
- Getting Started With Python Games On Raspberry Pi (Pygame)
- Python on Raspberry Pi: The Top 5 Libraries for Every Developer
- Should You Learn Linux or Python first?
Download Your Essential Linux Commands Guide!
It’s a free PDF guide containing every Raspberry Pi Linux command you should know!
Download now
Additional Resources
Not sure where to start?
Understand everything about the Raspberry Pi, stop searching for help all the time, and finally enjoy completing your projects.
Watch the Raspberry Pi Bootcamp course now.
Master your Raspberry Pi in 30 days
Don’t want the basic stuff only? If you are looking for the best tips to become an expert on Raspberry Pi, this book is for you. Learn useful Linux skills and practice multiple projects with step-by-step guides.
Download the e-book.
VIP Community
If you just want to hang out with me and other Raspberry Pi fans, you can also join the community. I share exclusive tutorials and behind-the-scenes content there. Premium members can also visit the website without ads.
More details here.
Need help building something with Python?
Create, understand, and improve any Python script for your Raspberry Pi.
Learn the essentials step-by-step without losing time understanding useless concepts.
Get the e-book now.
You can also find all my recommendations for tools and hardware on this page.
I’m the lead author and owner of RaspberryTips.com.
My goal is to help you with your Raspberry Pi problems using detailed guides and tutorials.
In real life, I’m a Linux system administrator with web developer experience.
Learning to program is hard. Even when you finally get your colons and parentheses right, there is still a big chance that the program doesn’t do what you intended. Commonly, this means you overlooked something or misunderstood a language construct, and you need to locate the place in the code where your expectations and reality diverge.
Programmers usually tackle this situation with a tool called a debugger, which allows running their program step-by-step. Unfortunately, most debuggers are optimized for professional usage and assume the user already knows the semantics of language constructs (e.g. function call) very well.
Thonny is a beginner-friendly Python IDE, developed in University of Tartu, Estonia, which takes a different approach as its debugger is designed specifically for learning and teaching programming.
Although Thonny is suitable for even total beginners, this post is meant for readers who have at least some experience with Python or another imperative language.
Getting started
Thonny is included in Fedora repositories since version 27. Install it with sudo dnf install thonny or with a graphical tool of your choice (such as Software).
When first launching Thonny, it does some preparations and then presents an empty editor and the Python shell. Copy following program text into the editor and save it into a file (Ctrl+S).
n = 1 while n < 5: print(n * "*") n = n + 1
Let’s first run the program in one go. For this press F5 on the keyboard. You should see a triangle made of periods appear in the shell pane.
A simple program in Thonny
Did Python just analyze your code and understand that you wanted to print a triangle? Let’s find out!
Start by selecting “Variables” from the “View” menu. This opens a table which will show us how Python manages program’s variables. Now run the program in debug mode by pressing Ctrl+F5 (or Ctrl+Shift+F5 in XFCE). In this mode Thonny makes Python pause before each step it takes. You should see the first line of the program getting surrounded with a box. We’ll call this the focus and it indicates the part of the code Python is going to execute next.
Thonny debugger focus
The piece of code you see in the focus box is called assignment statement. For this kind of statement, Python is supposed to evaluate the expression on the right and store the value under the name shown on the left. Press F7 to take the next step. You will see that Python focused on the right part of the statement. In this case the expression is really simple, but for generality Thonny presents the expression evaluation box, which allows turning expressions into values. Press F7 again to turn the literal 1 into value 1. Now Python is ready to do the actual assignment — press F7 again and you should see the variable n with value 1 appear in the variables table.
Thonny with variables table
Continue pressing F7 and observe how Python moves forward with really small steps. Does it look like something which understands the purpose of your code or more like a dumb machine following simple rules?
Function calls
Function call is a programming concept which often causes great deal of confusion to beginners. On the surface there is nothing complicated — you give name to a code and refer to it (call it) somewhere else in the code. Traditional debuggers show us that when you step into the call, the focus jumps into the function definition (and later magically back to the original location). Is it the whole story? Do we need to care?
Turns out the “jump model” is sufficient only with the simplest functions. Understanding parameter passing, local variables, returning and recursion all benefit from the notion of stack frame. Luckily, Thonny can explain this concept intuitively without sweeping important details under the carpet.
Copy following recursive program into Thonny and run it in debug mode (Ctrl+F5 or Ctrl+Shift+F5).
def factorial(n): if n == 0: return 1 else: return factorial(n-1) * n print(factorial(4))
Press F7 repeatedly until you see the expression factorial(4) in the focus box. When you take the next step, you see that Thonny opens a new window containing function code, another variables table and another focus box (move the window to see that the old focus box is still there).
Thonny stepping through a recursive function
This window represents a stack frame, the working area for resolving a function call. Several such windows on top of each other is called the call stack. Notice the relationship between argument 4 on the call site and entry n in the local variables table. Continue stepping with F7 and observe how new windows get created on each call and destroyed when the function code completes and how the call site gets replaced by the return value.
Values vs. references
Now let’s make an experiment inside the Python shell. Start by typing in the statements shown in the screenshot below:
Thonny shell showing list mutation
As you see, we appended to list b, but list a also got updated. You may know why this happened, but what’s the best way to explain it to a beginner?
When teaching lists to my students I tell them that I have been lying about Python memory model. It is actually not as simple as the variables table suggests. I tell them to restart the interpreter (the red button on the toolbar), select “Heap” from the “View” menu and make the same experiment again. If you do this, then you see that variables table doesn’t contain the values anymore — they actually live in another table called “Heap”. The role of the variables table is actually to map the variable names to addresses (or ID-s) which refer to the rows in the heap table. As assignment changes only the variables table, the statement b = a only copied the reference to the list, not the list itself. This explained why we see the change via both variables.
Thonny in heap mode
(Why do I postpone telling the truth about the memory model until the topic of lists? Does Python store lists differently compared to floats or strings? Go ahead and use Thonny’s heap mode to find this out! Tell me in the comments what do you think!)
If you want to understand the references system deeper, copy following program to Thonny and small-step (F7) through it with the heap table open.
def do_something(lst, x): lst.append(x) a = [1,2,3] n = 4 do_something(a, n) print(a)
Even if the “heap mode” shows us authentic picture, it is rather inconvenient to use. For this reason, I recommend you now switch back to normal mode (unselect “Heap” in the View menu) but remember that the real model includes variables, references and values.
Conclusion
The features I touched in this post were the main reason for creating Thonny. It’s easy to form misconceptions about both function calls and references but traditional debuggers don’t really help in reducing the confusion.
Besides these distinguishing features, Thonny offers several other beginner friendly tools. Please look around at Thonny’s homepage to learn more!
Thonny - идеальная IDE для новичков Python
Python и 1000 программ
Thonny — это простая IDE, разработанная для начинающих. Она предоставляет встроенный отладчик, показывающий, почему не работает код, и ассистента, указывающего на ошибки и предлагающего возможные способы решения. В общем, это идеальная IDE для обучения.
Настройка Thonny
Настроить Thonny не составляет труда. На момент написания статьи Thonny поставляется со встроенным Python 3.7.
Для начала войдем в Thonny и в верхней части страницы найдем установщика для OS:
Следуем инструкциям при установке и запускаем IDE по мере готовности:
Thonny приветствует нас активными элементами UI, скорее всего, ими будут редактор и оболочка. Однако вы всегда можете изменить элементы, отображающиеся в меню просмотра.
Не будем усложнять. Лучше начать работу со следующими окнами.
- Оболочка. Здесь вы наблюдайте непосредственный процесс выполнения кода.
- Заметки. Сюда добавляете рабочие заметки, чтобы сосредоточить все в одном месте (возможен вариант с сохранением псевдокода не в редакторе, а в этом окне).
- Переменные. Вы всегда знаете значения переменных. Поскольку они подвержены изменениям, то по мере роста программы легко потерять им счет.
- Ассистент. Это окно предоставляет текстовую информацию об ошибках в коде и подсказывает способы их устранения.
Индивидуальные настройки
Прежде чем переходить к обзору возможностей, уделим еще немного внимания настройкам.
Не вдаваясь в детали, отдельно рассмотрим несколько разделов.
Общие
У вас есть возможность разрешить запуск нескольких экземпляров Thonny вместо распределения файлов по вкладкам.
Кроме того, вы вольны переоткрыть файлы из предыдущего сеанса при возобновлении работы с IDE.
Редактор
Здесь речь пойдет об отличных настройках для редактора, позволяющих наглядно представить все, что происходит при написании кода. Например, вам могут пригодиться следующие.
- Подсветка совпадающих имен позволяет увидеть опечатки в переменных.
- Подсветка скобок помогает замечать отсутствие открывающейся или закрывающейся скобки.
- Подсветка синтаксических элементов отделяет синтаксис от текста или символов, упрощая обнаружение синтаксических ошибок.
Тема и шрифт
Темы и шрифты зависят от личных предпочтений. Выбирайте то, что понравится именно вам.
Уделите время поиску подходящего для вас стиля.
Функциональные возможности
А теперь пора познать всю прелесть Thonny.
После настройки IDE начинаем писать код. Создадим какой-нибудь некорректный код, чтобы увидеть ассистента в действии.
Справа в окне заметок представлены задания, слева — код. Как видно, в оболочке допущена ошибка, и ассистент спешит на помощь.
TypeError: unsupported operand type(s) for +: 'int' and 'str' main.py, line 4 Ваша программа пытается соединить целое число и строку. [+]Did you mean to treat both sides as text and produce a string? (Вы планировали, что обе стороны будут текстом, и на выходе получится строка?) [+]Did you mean to treat both sides as numbers and produce a sum?(Вы планировали, что обе стороны будут числами, и на выходе получится их сумма?) [+]Did you expect another type? (Вы ожидали другой тип?) [+]Maybe you forgot some details about this operation? (Может вы упустили какие-то детали операции?)
Удивительно. Сначала ассистент уведомляет об ошибке — конкатенация int
и string
не допустима.
Затем сообщает, что программа пытается выполнить эту операцию в строке 4.
И наконец, интересуется, какие из предполагаемых действий подлежали выполнению. В данном случае в наше намерение входило получение string
для дальнейшего использования. Разворачивая первое предположение, получаем краткую инструкцию по реализации задуманного:
In this case you should apply function str to the integer in order to convert it to string first, eg: str(42) + 'abc' В этом случае сначала следует применить функцию str к целому числу для преобразования его в строку, например str(42) + 'abc'
Таким образом новичок обретает фантастическую возможность получать мгновенную обратную связь по коду. Вы не только выясняете причину неработающего кода, но и параллельно узнаете что-то новое.
Отладка
Thonny позволяет проводить отладку кода. Создадим программу, содержащую ошибку “index out of range” (“индекс вне допустимого диапазона”).
my_list = ['one' , 'two' , 'three' , 'four'] for item in range(len(my_list)-1): print(my_list[item]) my_list.pop()
Выполняя код, получаем:
one two Traceback (most recent call last): File "/Users/martinandersson/Documents/python_dev/thonny/main.py", line 4, in <module> print(my_list[item]) IndexError: list index out of range
Это значит, что он выводит первые два элемента в списке и прекращает работу. Причина очевидна. Поскольку мы удаляем элементы из итерируемого списка, в итоге их количество перестает соответствовать условиям работы цикла.
Когда цикл выполнится 2 раза, в списке не останется элементов, при этом range(len(my_list)-1)
будет настаивать на продолжении его работы.
Для отладки кода кликните значок с жучком:
Продолжайте нажимать на “Step Into/ Шаг с заходом” (F7) для пошагового просмотра кода.
Далее Thonny демонстрирует, как вычисляется диапазон цикла:
Ниже следует наглядное представление внутренней работы цикла:
Отображается весь список и индекс в конце. В данном случае в качестве вывода получаем ‘one’
. Индекс 0
равен ‘one’
.
Однако вследствие применения pop(
в цикле у нас закончатся индексы.
Обратите внимание на ассистента: Thonny не смог предложить решения проблемы. При желании, кликнув на ссылку обратной связи, вы можете сообщить разработчикам об ошибке, тем самым помогая кому-то в будущем.
Заключение
Thonny — простой и удобный инструмент, который подойдет как новичкам, так и профессионалам при необходимости быстро отладить код.
Однако хотелось бы более удобного распределения элементов UI. Поскольку у многих разработчиков широкие экраны, лучше расположить окно ассистента не под заметками, а рядом с ними. То же самое относится и к оболочке. Если разместить ее справа от редактора, то в нашем распоряжении окажется больше строк.
Помимо этого, было бы классно, если бы полосы прокрутки, заметки и ассистент предполагали настройки темных тем.
Не помешала бы и функция автозаполнения, избавляющая от необходимости вводить весть синтаксис, например []
,{}
,’’
,()
.
Если вы новичок или вам нужен простой инструмент для отладки кода, то Thonny как нельзя лучше подходит для этих целей. К тому же она никогда не будет лишней в вашем арсенале, даже если в будущем вы перейдете к более сложным инструментам.
Благодарю за внимание! Успехов в программировании.
Перевод статьи