Learn Functional Python in 10 Minutes

Learn Functional Python in 10 Minutes

In this article, you’ll learn what the functional paradigm is as well as how to use functional programming in Python. You’ll also learn about list comprehensions and other forms of comprehensions.

Functional paradigm

In an imperative paradigm, you get things done by giving the computer a sequence of tasks and then it executes them. While executing them, it can change states. For example, let’s say you originally set A to 5, then later on you change the value of A. You have variables in the sense that the value inside the variable varies.

In a functional paradigm, you don’t tell the computer what to do but rather you tell it what stuff is. What the greatest common divisor of a number is, what the product from 1 to n is and so on.

Because of this, variables cannot vary. Once you set a variable, it stays that way forever (note, in purely functional languages they are not called variables). Because of this, functions have no side effects in the functional paradigm. A side effect is where the function changes something outside of it. Let’s look at an example of some typical Python code:

a = 3
def some_func():
    global a
    a = 5

some_func()
print(a)

The output for this code is 5. In the functional paradigm, changing variables is a big no-no and having functions affect things outside of their scope is also a big no-no. The only thing a function can do is calculate something and return it as a result.

Now you might be thinking: “no variables, no side effects? Why is this good?”. Good question, gnarly stranger reading this.

If a function is called twice with the same parameters, it’s guaranteed to return the same result. If you’ve learnt about mathematical functions, you’ll know to appreciate this benefit. This is called referential transparency. Because functions have no side effects, if you are building a program which computes things, you can speed up the program. If the program knows that func(2) equates to 3, we can store this in a table. This prevents the program from repeatedly running the same function when we already know the answer.

Typically, in functional programming, we do not use loops. We use recursion. Recursion is a mathematical concept, usually, it means “feeding into itself”. With a recursive function, the function repeatedly calls itself as a sub-function. Here’s a nice example of a recursive function in Python:

def factorial_recursive(n):
    # Base case: 1! = 1
    if n == 1:
        return 1

    # Recursive case: n! = n * (n-1)!
    else:
return n * factorial_recursive(n-1)

Some programming languages are also lazy. This means that they don’t compute or do anything until the very last second. If you write some code to perform 2 + 2, a functional program will only calculate that when you actually need to use the resultant. We’ll explore laziness in Python soon.

Map

To understand map, let’s first look at what iterables are. An iterable is anything you can iterate over. Typically these are lists or arrays, but Python has many different types of iterables. You can even create your own objects which are iterable by implementing magic methods. A magic method is like an API that helps your objects become more Pythonic. You need to implement 2 magic methods to make an object an iterable:

class Counter:
    def __int__(self, low, high):
        # set class attributes inside the magic method __init__
        # for "inistalise"
        self.current = low
        self.high = high

    def __iter__(self):
        # first magic method to make this object iterable
        return self
    
    def __next__(self):
        # second magic method
        if self.current > self.high:
            raise StopIteration
        else:
            self.current += 1
return self.current - 1

The first magic method, “iter” or dunder iter (double underscore iter) returns the iterative object, this is often used at the start of a loop. Dunder next returns what the next object is.

Let’s go into a quick terminal session and check this out:

for c in Counter(3, 8):
print(c)

This will print

3
4
5
6
7
8

In Python, an iterator is an object which only has an iter magic method. This means that you can access positions in the object, but cannot iterate through the object. Some objects will have the magic method next and not the itermagic method, such as sets (talked about later in this article). For this article, we’ll assume everything we touch is an iterable object.

So now we know what an iterable object is, let’s go back to the map function. The map function lets us apply a function to every item in an iterable. Typically we want to apply a function to every item in a list, but know that it’s possible for most iterables. Map takes 2 inputs, the function to apply and the iterable object.

map(function, iterable)

Let’s say we have a list of numbers like so:

[1, 2, 3, 4, 5]

And we want to square every number, we can write code like this:

x = [1, 2, 3, 4, 5]
def square(num):
    return num*num

print(list(map(square, x)))

Functional functions in Python are lazy. If we didn’t include the “list()” the function would store the definition of the iterable, not the list itself. We need to explicitly tell Python “turn this into a list” for us to use this.

It’s a bit weird to go from non-lazy evaluation to lazy evaluation all of a sudden in Python. You’ll eventually get used to it if you think more in the functional mindset than an imperative mindset.

Now it’s nice to write a normal function like “square(num)” but it doesn’t look right. We have to define a whole function just to use it once in a map? Well, we can define a function in map using a lambda (anonymous) function.

Lambda expressions

A lambda expression is a one line function. Take, for instance, this lambda expression which squares a number given to it:

square = lambda x: x * x

Now let’s run this:

>>> square(3)

9

I hear you. “Brandon, where are the arguments? what the heck is this? that doesn’t look anything like a function?”

Well, it’s kind of confusing but can be explained. So we’re assigning something to the variable “square”. this part:

lambda x:

Tells Python that this is a lambda function, and the input is called x. Anything after the colon is what you do with the input, and it automatically returns whatever the resultant of that is.

To simplfy our square program into one line we can do:

x = [1, 2, 3, 4, 5]
print(list(map(lambda num: num * num, x)))

So in a lambda expression, all the arguments go on the left and the stuff you want to do with them go on the right. It gets a little messy, no one can deny that. The truth is that there’s a certain pleasure in writing code that only other functional programmers can read. Also, it’s super cool to take a function and turn it into a one-liner.

Reduce

Reduce is a function that turns an iterable into one thing. Typically you perform a computation on a list to reduce it down to one number. Reduce looks like this:

reduce(function, list)

We can (and often will) use lambda expressions as the function.

The product of a list is every single number multiplied together. To do this you would program:

product = 1
x = [1, 2, 3, 4]
for num in x:
product = product * num

But with reduce you can just write:

from functools import reduce

product = reduce((lambda x, y: x * y),[1, 2, 3, 4])

To get the same product. The code is shorter, and with knowledge of functional programming it is neater.

Filter

The filter function takes an iterable and filters out all the things you don’t want in that iterable.

Normally filter takes a function and a list. It applies the function to each item in the list and if that function returns True, it does nothing. If it returns False, it removes that item from the list.

The syntax looks like:

filter(function, list)

Let’s see a small example, without filter we’ll write:

x = range(-5, 5)
new_list = []

for num in x:
    if num < 0:
new_list.append(num)

With filter, this becomes:

x = range(-5, 5)
all_less_than_zero = list(filter(lambda num: num < 0, x))

Higher order functions

Higher order functions can take functions as parameters and return functions. A very simple example would look like:

def summation(nums):
    return sum(nums)

def action(func, numbers):
    return func(numbers)

print(action(summation, [1, 2, 3]))

# Output is 6

Or an even simpler example of the second definition, “return functions”, is:

def rtnBrandon():
    return "brandon"
def rtnJohn():
    return "john"

def rtnPerson():
    age = int(input("What's your age?"))

    if age == 21:
        return rtnBrandon()
    else:
return rtnJohn()

You know earlier how I said that pure functional programming languages didn’t have variables? Well, higher order functions are what makes this easier. You don’t need to store a variable anywhere if all you’re doing is passing data through a long tunnel of functions.

All functions in Python are first class objects. A first class object is defined as having one or more of these features:

  • Created at runtime
  • Assigned tro a variable or element in a data structure
  • Passed as an argument to a function
  • Returned as the result of a function

So all functions in Python are first class and can be used as a higher order function.

Partial application

Partial application is a bit weird, but are super cool. You can call a function without supplying all the arguments it requires. Let’s see this in an example. We want to create a function which takes 2 arguments, a base and an exponent, and returns base to the power of the exponent, like so:

def power(base, exponent):
return base ** exponent

Now we want to have a dedicated square function, to work out the square of a number using the power function:

def square(base):
return power(base, 2)

This works, but what if we want a cube function? or a function to the power of 4? Can we keep on writing them forever? Well, you could. But programmers are lazy. If you repeat the same thing over and over again, it’s a sign that there is a much quicker way to speed things up and that will allow you to not repeat things. We can use partial applications here. Let’s see an example of the square function using a partial application:

from functools import partial

square = partial(power, exponent=2)
print(square(2))

# output is 4

Isn’t that cool! We can call functions which require 2 arguments, using only 1 argument by telling Python what the second argument is.

We can also use a loop, to generate a power function that works from cubed all the way up to powers of 1000.

from functools import partial

powers = []
for x in range(2, 1001):
  powers.append(partial(power, exponent = x))
  
print(powers[0](3))
# output is 9

Functional programming isn’t Pythonic

You might have noticed, but a lot of the things we want to do in functional programming revolve around lists. Other than the reduce function & partial application, all the functions you have seen generate lists. Guido (the inventor of Python) dislikes functional stuff in Python because Python already has its own way to generate lists.

If you write “import this” into a Python IDLE session, you’ll get:

>>> import this

The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren’t special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one — and preferably only one — obvious way to do it.
Although that way may not be obvious at first unless you’re Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it’s a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea — let’s do more of those!

This is the Zen of Python. It’s a poem about what something being Pythonic means. The part we want to relate to here is:

In Python, map & filter can do the same things as a list comprehension (discussed next) can do. This breaks one of the rules of the Zen of Python, so these parts of functional programming aren’t seen as ‘pythonic’.

Another talking point is Lambda. In Python, a lambda function is a normal function. Lambda is syntactic sugar. Both of these are equivalent:

foo = lamda a: 2
  
def foo(a):
return 2

A regular function can do everything a lambda function can, but it doesn’t work the other way around. A lambda function cannot do everything that a regular function can do.

This was a short argument about why functional programming doesn’t fit into the whole Python ecosystem very well. You may have noticed I mentioned list comprehensions earlier, we’ll discuss them now.

List comprehensions

Earlier, I mentioned that anything you could do with map or filter, you could do with a list comprehension. This is the part where we’ll learn about them.

A list comprehension is a way to generate lists in Python. The syntax is:

[function for item in iterable]

So let’s square every number in a list, as an example:

print([x * x for x in [1, 2, 3, 4]])

Okay, so we can see how we can apply a function to every item in a list. How do we go around applying a filter? Well, look at this code from earlier:

x = range(-5, 5)

all_less_than_zero = list(filter(lambda num: num < 0, x))
print(all_less_than_zero)

We can convert this into a list comprehension like so:

x = range(-5, 5)

all_less_than_zero = [num for num in x if num < 0]

List comprehensions support if statements like this. You no longer need to apply a million functions to something to get what you want. In fact, if you’re trying to make some kind of list chances are that it’ll look cleaner and easier using a list comprehension.

What if we want to square every number below 0 in a list? Well, with lambda, map and filter you’ll write:

x = range(-5, 5)

all_less_than_zero = list(map(lambda num: num * num, list(filter(lambda num: num < 0, x))))

So that’s seems really long and slightly complicated. With a list comprehension it’s just:

x = range(-5, 5)

all_less_than_zero = [num * num for num in x if num < 0]

A list comprehension is only good for, well, lists. Map and filter work on any iterable, so what’s up with that? Well, you can use any comprehension for any iterable object you encounter.

Other comprehensions

You can create a comprehension of any iterable

Any iterable can be generated using a comprehension. Since Python 2.7, you can even generate a dictionary (hashmap).

# Taken from page 70 chapter 3 of Fluent Python by Luciano Ramalho

DIAL_CODES = [
    (86, 'China'),
    (91, 'India'),
    (1, 'United States'),
    (62, 'Indonesia'),
    (55, 'Brazil'),
    (92, 'Pakistan'),
    (880, 'Bangladesh'),
    (234, 'Nigeria'),
    (7, 'Russia'),
    (81, 'Japan'),
    ]

>>> country_code = {country: code for code, country in DIAL_CODES}
>>> country_code
{'Brazil': 55, 'Indonesia': 62, 'Pakistan': 92, 'Russia': 7, 'China': 86, 'United States': 1, 'Japan': 81, 'India': 91, 'Nigeria': 234, 'Bangladesh': 880}
>>> {code: country.upper() for country, code in country_code.items() if code < 66}
{1: 'UNITED STATES', 7: 'RUSSIA', 62: 'INDONESIA', 55: 'BRAZIL'}

If it’s an iterable, it can be generated. Let’s look at one last example of sets. If you don’t know what a set is, check out this other article I wrote. The TLDR is:

  • Sets are lists of elements, no element is repeated twice in that list
  • The order in sets do not matter.
# taken from page 87, chapter 3 of Fluent Python by Luciano Ramalho

>>> from unicodedata import name
>>> {chr(i) for i in range(32, 256) if 'SIGN' in name(chr(i), '')}
{'×', '¥', '°', '£', '©', '#', '¬', '%', 'µ', '>', '¤', '±', '¶', '§', '<', '=', '®', '
You may notice that sets have the same curly braces as dictionaries. Python is really smart. It’ll know whether you’re writing a dictionary comprehension or a set comprehension based on whether you provide the extra value for the dictionary or not. If you want to learn more about comprehensions, check out [this ](http://treyhunner.com/2015/12/python-list-comprehensions-now-in-color/ "this ")visual guide. If you want to learn more about comprehensions & generators, check out this [article](https://medium.freecodecamp.org/python-list-comprehensions-vs-generator-expressions-cef70ccb49db "article").
# Conclusion

Functional programming is beautiful and pure. Functional code can be clean, but it can also be messy. Some hardcore Python programmers dislike the functional paradigm in Python. You should use what you want to use, use the best tool for the job.




**Originally published by **[Brandon Skerritt](https://hackernoon.com/@brandonskerritt "Brandon Skerritt")** ***at *[hackernoon.com](https://hackernoon.com/learn-functional-python-in-10-minutes-to-2d1651dece6f "hackernoon.com")

===============================================================================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on [**Facebook**](https://www.facebook.com/Pythontutorial4u "**Facebook**") | [**Twitter**](https://twitter.com/codek_tv "**Twitter**")
# Learn More

☞ [Complete Python Bootcamp: Go from zero to hero in Python 3](http://deal.codetrick.net/p/S15_M7e-l "Complete Python Bootcamp: Go from zero to hero in Python 3")

☞ [Complete Python Masterclass](http://deal.codetrick.net/p/SkCfL7xbe "Complete Python Masterclass")

☞ [Learn Python by Building a Blockchain & Cryptocurrency](https://deal.codetrick.net/p/Hkf1gIuaf "Learn Python by Building a Blockchain & Cryptocurrency")

☞ [Python and Django Full Stack Web Developer Bootcamp](http://deal.codetrick.net/p/r1-quFMgce "Python and Django Full Stack Web Developer Bootcamp")

☞ [The Python Bible™ | Everything You Need to Program in Python](http://deal.codetrick.net/p/Skc18mgbl "The Python Bible™ | Everything You Need to Program in Python")

☞ [Learning Python for Data Analysis and Visualization](http://deal.codetrick.net/p/HywrG7e-l "Learning Python for Data Analysis and Visualization")

☞ [Python for Financial Analysis and Algorithmic Trading](http://deal.codetrick.net/p/BkBWKHZtb "Python for Financial Analysis and Algorithmic Trading")

☞ [The Modern Python 3 Bootcamp](http://edupioneer.net/p/HkOjAJUcM "The Modern Python 3 Bootcamp")
, '÷', '¢', '+'}

You may notice that sets have the same curly braces as dictionaries. Python is really smart. It’ll know whether you’re writing a dictionary comprehension or a set comprehension based on whether you provide the extra value for the dictionary or not. If you want to learn more about comprehensions, check out this visual guide. If you want to learn more about comprehensions & generators, check out this article.

Conclusion

Functional programming is beautiful and pure. Functional code can be clean, but it can also be messy. Some hardcore Python programmers dislike the functional paradigm in Python. You should use what you want to use, use the best tool for the job.

What's Python IDLE? How to use Python IDLE to interact with Python?

What's Python IDLE? How to use Python IDLE to interact with Python?

In this tutorial, you’ll learn all the basics of using **IDLE** to write Python programs. You'll know what Python IDLE is and how you can use it to interact with Python directly. You’ve also learned how to work with Python files and customize Python IDLE to your liking.

In this tutorial, you'll learn how to use the development environment included with your Python installation. Python IDLE is a small program that packs a big punch! You'll learn how to use Python IDLE to interact with Python directly, work with Python files, and improve your development workflow.

If you’ve recently downloaded Python onto your computer, then you may have noticed a new program on your machine called IDLE. You might be wondering, “What is this program doing on my computer? I didn’t download that!” While you may not have downloaded this program on your own, IDLE comes bundled with every Python installation. It’s there to help you get started with the language right out of the box. In this tutorial, you’ll learn how to work in Python IDLE and a few cool tricks you can use on your Python journey!

In this tutorial, you’ll learn:

  • What Python IDLE is
  • How to interact with Python directly using IDLE
  • How to edit, execute, and debug Python files with IDLE
  • How to customize Python IDLE to your liking

Table of Contents

What Is Python IDLE?

Every Python installation comes with an Integrated Development and Learning Environment, which you’ll see shortened to IDLE or even IDE. These are a class of applications that help you write code more efficiently. While there are many IDEs for you to choose from, Python IDLE is very bare-bones, which makes it the perfect tool for a beginning programmer.

Python IDLE comes included in Python installations on Windows and Mac. If you’re a Linux user, then you should be able to find and download Python IDLE using your package manager. Once you’ve installed it, you can then use Python IDLE as an interactive interpreter or as a file editor.

An Interactive Interpreter

The best place to experiment with Python code is in the interactive interpreter, otherwise known as a shell. The shell is a basic Read-Eval-Print Loop (REPL). It reads a Python statement, evaluates the result of that statement, and then prints the result on the screen. Then, it loops back to read the next statement.

The Python shell is an excellent place to experiment with small code snippets. You can access it through the terminal or command line app on your machine. You can simplify your workflow with Python IDLE, which will immediately start a Python shell when you open it.

A File Editor

Every programmer needs to be able to edit and save text files. Python programs are files with the .py extension that contain lines of Python code. Python IDLE gives you the ability to create and edit these files with ease.

Python IDLE also provides several useful features that you’ll see in professional IDEs, like basic syntax highlighting, code completion, and auto-indentation. Professional IDEs are more robust pieces of software and they have a steep learning curve. If you’re just beginning your Python programming journey, then Python IDLE is a great alternative!

How to Use the Python IDLE Shell

The shell is the default mode of operation for Python IDLE. When you click on the icon to open the program, the shell is the first thing that you see:

This is a blank Python interpreter window. You can use it to start interacting with Python immediately. You can test it out with a short line of code:

Here, you used print() to output the string "Hello, from IDLE!" to your screen. This is the most basic way to interact with Python IDLE. You type in commands one at a time and Python responds with the result of each command.

Next, take a look at the menu bar. You’ll see a few options for using the shell:

You can restart the shell from this menu. If you select that option, then you’ll clear the state of the shell. It will act as though you’ve started a fresh instance of Python IDLE. The shell will forget about everything from its previous state:

In the image above, you first declare a variable, x = 5. When you call print(x), the shell shows the correct output, which is the number 5. However, when you restart the shell and try to call print(x) again, you can see that the shell prints a traceback. This is an error message that says the variable x is not defined. The shell has forgotten about everything that came before it was restarted.

You can also interrupt the execution of the shell from this menu. This will stop any program or statement that’s running in the shell at the time of interruption. Take a look at what happens when you send a keyboard interrupt to the shell:

A KeyboardInterrupt error message is displayed in red text at the bottom of your window. The program received the interrupt and has stopped executing.

How to Work With Python Files

Python IDLE offers a full-fledged file editor, which gives you the ability to write and execute Python programs from within this program. The built-in file editor also includes several features, like code completion and automatic indentation, that will speed up your coding workflow. First, let’s take a look at how to write and execute programs in Python IDLE.

Opening a File

To start a new Python file, select File → New File from the menu bar. This will open a blank file in the editor, like this:

From this window, you can write a brand new Python file. You can also open an existing Python file by selecting File → Open… in the menu bar. This will bring up your operating system’s file browser. Then, you can find the Python file you want to open.

If you’re interested in reading the source code for a Python module, then you can select File → Path Browser. This will let you view the modules that Python IDLE can see. When you double click on one, the file editor will open up and you’ll be able to read it.

The content of this window will be the same as the paths that are returned when you call sys.path. If you know the name of a specific module you want to view, then you can select File → Module Browser and type in the name of the module in the box that appears.

Editing a File

Once you’ve opened a file in Python IDLE, you can then make changes to it. When you’re ready to edit a file, you’ll see something like this:

The contents of your file are displayed in the open window. The bar along the top of the window contains three pieces of important information:

  1. The name of the file that you’re editing
  2. The full path to the folder where you can find this file on your computer
  3. The version of Python that IDLE is using

In the image above, you’re editing the file myFile.py, which is located in the Documents folder. The Python version is 3.7.1, which you can see in parentheses.

There are also two numbers in the bottom right corner of the window:

  1. Ln: shows the line number that your cursor is on.
  2. Col: shows the column number that your cursor is on.

It’s useful to see these numbers so that you can find errors more quickly. They also help you make sure that you’re staying within a certain line width.

There are a few visual cues in this window that will help you remember to save your work. If you look closely, then you’ll see that Python IDLE uses asterisks to let you know that your file has unsaved changes:

The file name shown in the top of the IDLE window is surrounded by asterisks. This means that there are unsaved changes in your editor. You can save these changes with your system’s standard keyboard shortcut, or you can select File → Save from the menu bar. Make sure that you save your file with the .py extension so that syntax highlighting will be enabled.

Executing a File

When you want to execute a file that you’ve created in IDLE, you should first make sure that it’s saved. Remember, you can see if your file is properly saved by looking for asterisks around the filename at the top of the file editor window. Don’t worry if you forget, though! Python IDLE will remind you to save whenever you attempt to execute an unsaved file.

To execute a file in IDLE, simply press the F5 key on your keyboard. You can also select Run → Run Module from the menu bar. Either option will restart the Python interpreter and then run the code that you’ve written with a fresh interpreter. The process is the same as when you run python3 -i [filename] in your terminal.

When your code is done executing, the interpreter will know everything about your code, including any global variables, functions, and classes. This makes Python IDLE a great place to inspect your data if something goes wrong. If you ever need to interrupt the execution of your program, then you can press Ctrl+C in the interpreter that’s running your code.

How to Improve Your Workflow

Now that you’ve seen how to write, edit, and execute files in Python IDLE, it’s time to speed up your workflow! The Python IDLE editor offers a few features that you’ll see in most professional IDEs to help you code faster. These features include automatic indentation, code completion and call tips, and code context.

Automatic Indentation

IDLE will automatically indent your code when it needs to start a new block. This usually happens after you type a colon (:). When you hit the enter key after the colon, your cursor will automatically move over a certain number of spaces and begin a new code block.

You can configure how many spaces the cursor will move in the settings, but the default is the standard four spaces. The developers of Python agreed on a standard style for well-written Python code, and this includes rules on indentation, whitespace, and more. This standard style was formalized and is now known as PEP 8. To learn more about it, check out How to Write Beautiful Python Code With PEP 8.

Code Completion and Call Tips

When you’re writing code for a large project or a complicated problem, you can spend a lot of time just typing out all of the code you need. Code completion helps you save typing time by trying to finish your code for you. Python IDLE has basic code completion functionality. It can only autocomplete the names of functions and classes. To use autocompletion in the editor, just press the tab key after a sequence of text.

Python IDLE will also provide call tips. A call tip is like a hint for a certain part of your code to help you remember what that element needs. After you type the left parenthesis to begin a function call, a call tip will appear if you don’t type anything for a few seconds. For example, if you can’t quite remember how to append to a list, then you can pause after the opening parenthesis to bring up the call tip:

The call tip will display as a popup note, reminding you how to append to a list. Call tips like these provide useful information as you’re writing code.

Code Context

The code context functionality is a neat feature of the Python IDLE file editor. It will show you the scope of a function, class, loop, or other construct. This is particularly useful when you’re scrolling through a lengthy file and need to keep track of where you are while reviewing code in the editor.

To turn it on, select Options → Code Context in the menu bar. You’ll see a gray bar appear at the top of the editor window:

As you scroll down through your code, the context that contains each line of code will stay inside of this gray bar. This means that the print() functions you see in the image above are a part of a main function. When you reach a line that’s outside the scope of this function, the bar will disappear.

How to Debug in IDLE

A bug is an unexpected problem in your program. They can appear in many forms, and some are more difficult to fix than others. Some bugs are tricky enough that you won’t be able to catch them by just reading through your program. Luckily, Python IDLE provides some basic tools that will help you debug your programs with ease!

Interpreter DEBUG Mode

If you want to run your code with the built-in debugger, then you’ll need to turn this feature on. To do so, select Debug → Debugger from the Python IDLE menu bar. In the interpreter, you should see [DEBUG ON] appear just before the prompt (>>>), which means the interpreter is ready and waiting.

When you execute your Python file, the debugger window will appear:

In this window, you can inspect the values of your local and global variables as your code executes. This gives you insight into how your data is being manipulated as your code runs.

You can also click the following buttons to move through your code:

  • Go: Press this to advance execution to the next breakpoint. You’ll learn about these in the next section.
  • Step: Press this to execute the current line and go to the next one.
  • Over: If the current line of code contains a function call, then press this to step over that function. In other words, execute that function and go to the next line, but don’t pause while executing the function (unless there is a breakpoint).
  • Out: If the current line of code is in a function, then press this to step out of this function. In other words, continue the execution of this function until you return from it.

Be careful, because there is no reverse button! You can only step forward in time through your program’s execution.

You’ll also see four checkboxes in the debug window:

  1. Globals: your program’s global information
  2. Locals: your program’s local information during execution
  3. Stack: the functions that run during execution
  4. Source: your file in the IDLE editor

When you select one of these, you’ll see the relevant information in your debug window.

Breakpoints

A breakpoint is a line of code that you’ve identified as a place where the interpreter should pause while running your code. They will only work when DEBUG mode is turned on, so make sure that you’ve done that first.

To set a breakpoint, right-click on the line of code that you wish to pause. This will highlight the line of code in yellow as a visual indication of a set breakpoint. You can set as many breakpoints in your code as you like. To undo a breakpoint, right-click the same line again and select Clear Breakpoint.

Once you’ve set your breakpoints and turned on DEBUG mode, you can run your code as you would normally. The debugger window will pop up, and you can start stepping through your code manually.

Errors and Exceptions

When you see an error reported to you in the interpreter, Python IDLE lets you jump right to the offending file or line from the menu bar. All you have to do is highlight the reported line number or file name with your cursor and select Debug → Go to file/line from the menu bar. This is will open up the offending file and take you to the line that contains the error. This feature works regardless of whether or not DEBUG mode is turned on.

Python IDLE also provides a tool called a stack viewer. You can access it under the Debug option in the menu bar. This tool will show you the traceback of an error as it appears on the stack of the last error or exception that Python IDLE encountered while running your code. When an unexpected or interesting error occurs, you might find it helpful to take a look at the stack. Otherwise, this feature can be difficult to parse and likely won’t be useful to you unless you’re writing very complicated code.

How to Customize Python IDLE

There are many ways that you can give Python IDLE a visual style that suits you. The default look and feel is based on the colors in the Python logo. If you don’t like how anything looks, then you can almost always change it.

To access the customization window, select Options → Configure IDLE from the menu bar. To preview the result of a change you want to make, press Apply. When you’re done customizing Python IDLE, press OK to save all of your changes. If you don’t want to save your changes, then simply press Cancel.

There are 5 areas of Python IDLE that you can customize:

  1. Fonts/Tabs
  2. Highlights
  3. Keys
  4. General
  5. Extensions

Let’s take a look at each of them now.

Fonts/Tabs

The first tab allows you to change things like font color, font size, and font style. You can change the font to almost any style you like, depending on what’s available for your operating system. The font settings window looks like this:

You can use the scrolling window to select which font you prefer. (I recommend you select a fixed-width font like Courier New.) Pick a font size that’s large enough for you to see well. You can also click the checkbox next to Bold to toggle whether or not all text appears in bold.

This window will also let you change how many spaces are used for each indentation level. By default, this will be set to the PEP 8 standard of four spaces. You can change this to make the width of your code more or less spread out to your liking.

Highlights

The second customization tab will let you change highlights. Syntax highlighting is an important feature of any IDE that highlights the syntax of the language that you’re working in. This helps you visually distinguish between the different Python constructs and the data used in your code.

Python IDLE allows you to fully customize the appearance of your Python code. It comes pre-installed with three different highlight themes:

  1. IDLE Day
  2. IDLE Night
  3. IDLE New

You can select from these pre-installed themes or create your own custom theme right in this window:

Unfortunately, IDLE does not allow you to install custom themes from a file. You have to create customs theme from this window. To do so, you can simply start changing the colors for different items. Select an item, and then press Choose color for. You’ll be brought to a color picker, where you can select the exact color that you want to use.

You’ll then be prompted to save this theme as a new custom theme, and you can enter a name of your choosing. You can then continue changing the colors of different items if you’d like. Remember to press Apply to see your changes in action!

Keys

The third customization tab lets you map different key presses to actions, also known as keyboard shortcuts. These are a vital component of your productivity whenever you use an IDE. You can either come up with your own keyboard shortcuts, or you can use the ones that come with IDLE. The pre-installed shortcuts are a good place to start:

The keyboard shortcuts are listed in alphabetical order by action. They’re listed in the format Action - Shortcut, where Action is what will happen when you press the key combination in Shortcut. If you want to use a built-in key set, then select a mapping that matches your operating system. Pay close attention to the different keys and make sure your keyboard has them!

Creating Your Own Shortcuts

The customization of the keyboard shortcuts is very similar to the customization of syntax highlighting colors. Unfortunately, IDLE does not allow you to install custom keyboard shortcuts from a file. You must create a custom set of shortcuts from the Keys tab.

Select one pair from the list and press Get New Keys for Selection. A new window will pop up:

Here, you can use the checkboxes and scrolling menu to select the combination of keys that you want to use for this shortcut. You can select Advanced Key Binding Entry >> to manually type in a command. Note that this cannot pick up the keys you press. You have to literally type in the command as you see it displayed to you in the list of shortcuts.

General

The fourth tab of the customization window is a place for small, general changes. The general settings tab looks like this:

Here, you can customize things like the window size and whether the shell or the file editor opens first when you start Python IDLE. Most of the things in this window are not that exciting to change, so you probably won’t need to fiddle with them much.

Extensions

The fifth tab of the customization window lets you add extensions to Python IDLE. Extensions allow you to add new, awesome features to the editor and the interpreter window. You can download them from the internet and install them to right into Python IDLE.

To view what extensions are installed, select Options → Configure IDLE -> Extensions. There are many extensions available on the internet for you to read more about. Find the ones you like and add them to Python IDLE!

Conclusion

In this tutorial, you’ve learned all the basics of using IDLE to write Python programs. You know what Python IDLE is and how you can use it to interact with Python directly. You’ve also learned how to work with Python files and customize Python IDLE to your liking.

You’ve learned how to:

  • Work with the Python IDLE shell
  • Use Python IDLE as a file editor
  • Improve your workflow with features to help you code faster
  • Debug your code and view errors and exceptions
  • Customize Python IDLE to your liking

Now you’re armed with a new tool that will let you productively write Pythonic code and save you countless hours down the road. Happy programming!

Importance of Python Programming skills

Importance of Python Programming skills

Python is one among the most easiest and user friendly programming languages when it comes to the field of software engineering. The codes and syntaxes of python is so simple and easy to use that it can be deployed in any problem solving...

Python is one among the most easiest and user friendly programming languages when it comes to the field of software engineering. The codes and syntaxes of python is so simple and easy to use that it can be deployed in any problem solving challenges. The codes of Python can easily be deployed in Data Science and Machine Learning. Due to this ease of deployment and easier syntaxes, this platform has a lot of real world problem solving applications. According to the sources the companies are eagerly hunting for the professionals with python skills along with SQL. An average python developer in the united states makes around 1 lakh U.S Dollars per annum. In some of the top IT hubs in our country like Bangalore, the demand for professionals in the domains of Data Science and Python Programming has surpassed over the past few years. As a result of which a lot of various python certification courses are available right now.

Array in Python: An array is defined as a data structure that can hold a fixed number of elements that are of the same python data type. The following are some of the basic functions of array in python:

  1. To find the transverse
  2. For insertion of the elements
  3. For deletion of the elements
  4. For searching the elements

Along with this one can easily crack any python interview by means of python interview questions

Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Python Training

This video on Tkinter tutorial covers all the basic aspects of creating and making use of your own simple Graphical User Interface (GUI) using Python. It establishes all of the concepts needed to get started with building your own user interfaces while coding in Python.

This video on Tkinter tutorial covers all the basic aspects of creating and making use of your own simple Graphical User Interface (GUI) using Python. It establishes all of the concepts needed to get started with building your own user interfaces while coding in Python.

Learn More

☞ Complete Python Bootcamp: Go from zero to hero in Python 3

☞ Complete Python Masterclass

☞ Learn Python by Building a Blockchain & Cryptocurrency

☞ Python and Django Full Stack Web Developer Bootcamp

☞ The Python Bible™ | Everything You Need to Program in Python

☞ Learning Python for Data Analysis and Visualization

☞ Python for Financial Analysis and Algorithmic Trading

☞ The Modern Python 3 Bootcamp

Original video source: https://www.youtube.com/watch?v=VMP1oQOxfM0