Python For Loops Explained

Python For Loops Explained

Python for loops are for iterating through sequences like lists, strings, dictionaries or ranges. In this tutorial you can understand everything.

A comprehensive introductory tutorial to Python loops. Learn and practice while and for loops, nested loops, the break and continue keywords, the range function and more!

Loops are important in Python or in any other programming language as they help you to execute a block of code repeatedly. You will often come face to face with situations where you would need to use a piece of code over and over but you don't want to write the same line of code multiple times.

In this Python loops tutorial you will cover the following topics :

  • The Python while loop: you'll learn how you can construct and use a while loop in data science applications. You'll do this by going over some interactive coding challenges.
  • Next, you'll move on to the for loop: once again, you'll learn how you can construct and use a for loop in a real-life context.
  • You'll also learn the difference between using a while loop and a for loop.
  • Also the topic of nested loops
  • After, you'll see how you can use the break and continue keywords.
  • The difference between the xrange() and range() functions
While Loop

The while loop is one of the first loops that you'll probably encounter when you're starting to learn how to program. It is arguably also one of the most intuitive ones to understand: if you think of the name of this loop, you will quickly understand that the word "while" has got to do something with "interval" or a "period of time". As you already know by now, the word "loop" refers to a piece of code that you execute repeatedly.

With all of this in mind, you can easily understand the following definition of the while loop:

A while loop is a programming concept that, when it's implemented, executes a piece of code over and over again while a given condition still holds true.

The above definition also highlights the three components that you need to construct the while loop in Python:

  • The while keyword;
  • A condition that transates to either True or False; And
  • A block of code that you want to execute repeatedly

That's all it takes!

How To Make A While Loop in Python

Now that you know what you need to construct a while loop, all that is left to do now is to look at a real-life example where the while loop is used before you start making exercises on your own! Consider the following example:

# Take user input
number = 2  

# Condition of the while loop
while number < 5 :  
    print("Thank you")
    # Increment the value of the variable "number by 1"
    number = number+1
Thank you
Thank you
Thank you

The code example above is a very simple while loop: if you think about it, the three components about which you read before are all present: the while keyword, followed by a condition that translates to either True or False (number < 5) and a block of code that you want to execute repeatedly:

print("Thank you")
number = number + 1

If you go into detail in the above code, you see that there is a variable number in which you store an integer 2. Since the value in number is smaller than 5, you print out "Thank you" and increase the value of number with one. While the value in number stays smaller than 5, you continue to execute the two lines of code that are contained within the while loop:

"Thank you"
"Thank you"

You print out "Thank you" two more times before the value of number is equal to 5 and the condition doesn't evaluate to True any more. Because the condition now evaluates to False, you will exit the while loop and continue your program if it contains any more code. In this case, there isn't any more code so your program will stop.

The above example is a bit basic, you can also include conditionals, or, in other words, an if condition, to make it even more customized. Take a look at the following example:

# Take user input
number = 2 

# Condition of the while loop
while number < 5 :  
    # Find the mod of 2
    if number%2 == 0:  
        print("The number "+str(number)+" is even")
    else:
        print("The number "+str(number)+" is odd")

    # Increment `number` by 1
    number = number+1
The number 2 is even
The number 3 is odd
The number 4 is even

Now, let's practice!

Write a function collatz() which lets the user input an integer in a variable named number. If number is even, then it should print the result of number/2. If number is odd, then collatz() should print and return 3 * number + 1. The program should keep calling the function collatz() on the number until it returns a 1.

Note that this is actually an implementation of collatz sequence, which in short is a mathematical problem where you choose a number and you keep doing the above calculations until you arrive at a result of 1.

Below, you can find the solution:

def collatz(number):
    # Is the mod of 2 equal to 0?
    if number % 2 == 0:
        print(number // 2)
        return number // 2

    # If the mod of 2 isn't equal to 0, print `3 * number + 1`
    elif number % 2 == 1:
        result = 3 * number + 1
        print(result)
        return result

# Ask input from the user    
n = input("Give me a number: ")

# As long as `n` is not equal to `1`, run `collatz()`
while n != 1:
    n = collatz(int(n))
Give me a number: 5
16
8
4
2
1
For Loop

You can tackle the for loop in the same way as the while loop. As you probably would have expected, the "for" component in "for loop" refers to something that you do for a certain number of times.

If you keep all the above in mind, you can easily define the for loop as follows:

A for loop is a programming concept that, when it's implemented, executes a piece of code over and over again "for" a certain number of times, based on a sequence.

In contrast to the while loop, there isn't any condition actively involved - you just execute a piece of code repeatedly for a number of times. In other words, while the while loop keeps on executing the block of code contained within it only till the condition is True, the for loop executes the code contained within it only for a specific number of times. This "number of times" is determined by a sequence or an ordered list of things.

You'll learn more about the difference between while and for loops in a bit, but for now, concentrate on the following pieces that you need in order to create a for loop:

  • The for keyword
  • A variable
  • The in keyword
  • The range() function, which is an built-in function in the Python library to create a sequence of numbers
  • The code that you want to execute repeatedly

For Loops in Python

# Print "Thank you" 5 times
for number in range(5):
    print("Thank you")
Thank you
Thank you
Thank you
Thank you
Thank you

As you can see, the components that you saw in the above section return in this small example of a for loop in Python: the for keyword, the variable number, the in keyword, the range() function and the code that you want to execute multiple times, print("Thank you").

That isn't so hard, right?

Let's consider another example of a for loop, where you make use of two variables to define your control flow:

languages = ['R', 'Python',  'Scala', 'Java', 'Julia']

for index in range(len(languages)):
   print('Current language:', languages[index])
Current language: R
Current language: Python
Current language: Scala
Current language: Java
Current language: Julia

As you can see, you start off the loop with the for keyword. Next, you make use of a variables index and languages, the in keyword, and the range() function to create a sequence of numbers. Additionally, you see that you also use the len() function in this case, as the languages list is not numerical. The piece of code that you want to execute repeatedly is a print statement, namely, print('Current language :', languages[index]).

In the loop above, you mean to express that for every index in the range len(languages), you want to print the the data science programming language. Now, len(languages) is 5, so the statement could also be rewritten as:

for index in range(5):
    print('Current language:', languages[index])
Current language: R
Current language: Python
Current language: Scala
Current language: Java
Current language: Julia

And this once again gives you the same result!

While versus For Loops in Python

Let's revisit the very first while loop example once again to determine what now exactly are the differences between while and for loops. You already read above that the difference lies in the condition that is or is not involved, but how does this reflect in the code and how can you maybe switch between the two?

# Take user input
number = 2  

while number < 5 :
    print("Thank you")
    # Increment `number` by 1
    number = number+1
Thank you
Thank you
Thank you

You can use for loop to print the statement "Thank you" in a more controlled manner:

# Print "Thank you" 3 times
for number in range(3) :  
    print("Thank you")
Thank you
Thank you
Thank you

See how easy it was to convert the while loop into an equivalent for loop?

How does it work, you ask? Well it's simple.

In a for loop, the integer mentioned inside the range function is the range or the number of times the control needs to loop and execute the code in the for loop's clause.

Note that the range() function's count starts from 0 and not from 1. That means that, in the above example, the count should be like 0,1,2 and not 1,2,3. That's how number counting in a computer's memory works. So, while designing a for loop, always keep in mind that you have to consider the count of range from 0 and not from 1.

Tip: this is the same for lists in Python, for example. If you'd like to know more about Python lists, consider checking out DataCamp's 18 Most Common Python List Questions tutorial.

Now, there is another interesting difference between a for loop and a while loop. A for loop is faster than a while loop. To understand this you have to look into the example below.

import timeit

# A for loop example
def for_loop():
    for number in range(10000) :  
        # Execute the below code 10000 times
        sum = 3+4
        #print(sum)

timeit.timeit(for_loop)
267.0804728891719
import timeit

# A while loop example
def while_loop():
    i =0
    while i<10000:
        sum = 3+4
        #print(sum)
        i+=1

timeit.timeit(while_loop)
884.9233417965908

In the code chunk above, you have two loops with around 10000 iterations. Both look the same at first sight, until you look behind the scenes and understand how these two loops work. Hint: the timeit() function gives you a clue of what might be the difference!

Remember: all Python code is compiled with a C compiler, which means that the code that you see above is first broken down into byte-codes and then it's processed by the underlying C compiler.

When the execution of the for loop in the above example starts, the Python interpretor talks to the underlying C compiler and then creates a list object of size 10000. Next, it calls an iterator to touch upon the index on each of the 10000 items in the list.

The execution of the while loop, on the other hand, doesn't create any list object. In fact, the underlying C compiler calls the boolean comparison operator for the condition i<10000 9999 times.

You can already imagine that iterating over an already created list object with 10000 elements is easier for the compiler than performing a boolean operation repeatedly for 9999 times, the time performance of a for loop is better than that of a while loop. This is clearly reflected in the execution time: the time for the for loop to complete is a lot smaller than the time the while loop needs to complete.

# Set `fib_no` to 55, the number until where you want to print
fib_no = 55

# Set `first_no` to 0
first_no = 0

# Set `second_no` to 1
second_no = 1

# Set the counter `count` to 0 
count = 0

# while loop to print the fibonacci series until the `fib_no`
while first_no <= fib_no:
       # Print `first_no`
       print(first_no)
       
       # Fibonnacci number
       nth = first_no + __________
       
       # update values of `first_no` and `second_no`
       first_no = ____________
       second_no = ___
       
       # Set counter `count` +1

Now try out the for loop! Note that you want to specify the range from 0 to 11, since you want to display only the numbers in the sequence up to 55, which is the 11th number in the sequence.

# Initialize `first_no` to `0`
first_no = 0

# Initialize `second_no` to `1`
second_no = 1

# Initialize `numbers`
numbers = ___________

# Find and display Fibonacci series
for num in _______:
           if(num <= 1):
           # Update only `nth`
                      nth = ___
           else:
           # Update the values `nth`, `first_no` and `second_no`
                      nth = first_no + second_no
                      first_no = second_no
                      second_no = __________
                      
           # Print `nth`
           print(nth)
Nested Loops

As you can notice in an example above, there is an if-else condition inside the while loop which enables you to introduce further conditions in your code.

Hold on!

This is not the only way that you can customize your loop. You can also include some more while loop inside you existing code and this is known as a nested loop. You can modify the above example to include another while loop like below:

# Take user input
number = 2 

# condition of the while loop
while number < 5 :  
    # condition of the nested while loop    
    while number % 2 == 0: 
        print("The number "+ str(number)+" is even")

In the above example there is another while loop which is "nested" inside the outer loop, this inner loop puts in another check to see if the number % (mod) 2 is 0.

In other words, it checks if the number is even and then it prints the statement "The number is even".

But there's a catch: if you look closely, you can see that like the previous code the number=number+1 statement is missing this time. Since you aren't incrementing the variable number anywhere, the value of the variable remains the same every time and the code enters an infinite loop. That means that, once it enters the loop, it never leaves and prints the statement an infinite number of times because the variable number will always be set to 2. This number is, of course, less than 5 and an even number.

Let's now take a look at what a nested for loop would look like:

# Print the below statement 3 times
for number in range(3) :  
    print("-------------------------------------------")
    print("I am outer loop iteration "+str(number))
    # Inner loop
    for another_number in range(5):  
        print("****************************")
        print("I am inner loop iteration "+str(another_number))
-------------------------------------------
I am outer loop iteration 0
****************************
I am inner loop iteration 0
****************************
I am inner loop iteration 1
****************************
I am inner loop iteration 2
****************************
I am inner loop iteration 3
****************************
I am inner loop iteration 4
-------------------------------------------
I am outer loop iteration 1
****************************
I am inner loop iteration 0
****************************
I am inner loop iteration 1
****************************
I am inner loop iteration 2
****************************
I am inner loop iteration 3
****************************
I am inner loop iteration 4
-------------------------------------------
I am outer loop iteration 2
****************************
I am inner loop iteration 0
****************************
I am inner loop iteration 1
****************************
I am inner loop iteration 2
****************************
I am inner loop iteration 3
****************************
I am inner loop iteration 4

The above code is a modified version of the first for loop example. Note how a second for loop is used inside the outer loop.

Go ahead and execute the code.

You will find out that the control enters the first for loop and the value of the variable number is initialized as 0. The first print statement is printed, and then control enters the second for loop, where the value of the variable another_number is initialized to 0. The first print statement in the second for loop is printed once.

Now, the control returns to the inner for loop once again and the value of another_number is again initialized to the next integer followed by printing the statement inside the print() function.

The aforementioned process continues until the control has traversed through the end of the range() function, which is 5 in this case, and then the control returns back to the outermost loop, initializes the variable number to the next integer, prints the statement inside the print() function, visits the inner loop and then repeats all of the above steps until the range() function is traversed.

This journey of the control traveling from the outermost loop, traversing of the inner loop and then back again to the outer for loop continues until the control has covered the entire range, which is 3 times in your case.

Now that you have read some explanations on nested loops, it's time to get started yourself! Write a Python program to construct the following pattern, using a nested for loop:

# Initialize the first five rows
n = _

# Start the loop to print the first five rows
for i in range(_):
    for j in range(i):
        print('* ', end="")
    print('')

# Start the loop to print the remaining rows in decreasing order of stars
for i in range(n,0,-1):
    for j in range(_):
        print('* ', end="")
    print('')
break and continue Keywords: Creating Infinite Loops

You can use break and continue in any loop you create. These keywords aren't restricted to breaking intentional infinite loops, but they should be used carefully. Both keywords make it harder for others -including yourself in a couple of months when you look back to your code- to understand the control flow in the loop and where the condition ends. Additionally, you don't need to use the break and continue keywords: as you have seen up until now, you were doing perfectly fine without them!

However, in some cases, it can be more clear to write intentional infinite loops rather than the traditional for and while loops that you have seen up until now. Of course, in those cases the use of these keywords is encouraged!

Breaking and Continuing While Loops in Python

Fortunately, there is a way to break out of the above situation of infinite loop and that is using the break keyword.

# Take user input
number = 2 

# Condition of the while loop
while number < 5 :  
    # condition of the nested while loop
    while number % 2 == 0:  
        print("The number "+str(number)+" is even")
        break

    number+=1

When you run the above code it doesn't go inside an infinite loop anymore.

"What is this sorcery!" you scream. - I say relax, it's no sorcery.

What happens is that when the control encounters the break keyword it understands that it has to exit the loop (inner loop in this case) and executes the next line of code. It therefore breaks out of the inner while loop and proceeds to the outer loop and continues doing it's usual stuff until the condition in the outer while loop holds true.

You should consider the fact that a line of code must exists after the break keyword or else it won't have any effect. Try to remove the line of code after the break keyword in the above example and then execute the code.

What if you sneak in the continue keyword after the break statement? You can follow the code below:

# Take user input
number = 2 

while number < 5 :
    while number % 2 == 0: 
        print("The number "+str(number)+" is even")
        break

    continue

    number+=1

The above code is a slightly modified version of the break keyword example.

When you run the above code you will again encounter an infinite loop. Before you start pulling your hair in frustration, take a closer look. You will notice that there's a continue keyword after the break. What the continue keyword does is that it transfers the control back to the outermost loop even before the variable number is incremented and because of this the code goes into an infinite loop.

Breaking and Continuing For Loops

What if you did not want to execute the inner for loop in the above example for the entire range? You can use a break statement in a similar way that you have done in the case of the while loop.

# Print the below statement 3 times
for number in range(3) : 
    print("-------------------------------------------")
    print("I am outer loop iteration "+str(number))
    for another_number in range(3):
        print("****************************")
        print("I am inner loop iteration "+str(another_number))
        break

In the above example, the break keyword after the inner loop instructs the control to break away from the inner loop, after which the control travels back to the outer loop.

Run the below code example:

# Print the below statement 3 times
for number in range(3) :  
    print("-------------------------------------------")
    print("I am outer loop iteration "+str(number))
    continue
    for another_number in range(3):
        print("****************************")
        print("I am inner loop iteration "+str(another_number))
        break

In the above code only the outermost loop is executed and the control doesn't even touch the inner loop.

"Why?" you ask.

Take a closer look at the code. There's a continue keyword just after the second print statement in the outermost loop. What it does is that it instructs the control to jump back to the outer for loop and start over again and that's why the control never touches the inner loop.

Unlike the while loop, you don't need a piece of code after the break keyword in the for loop. A break loop alone will work just fine inside a for loop.

range() versus xrange()

These two functions are similar to one another, but if you're using Python 3, you'll only have the range() function available. In Python 3.x, the xrange() function is renamed as range(). That means that if you try to use the xrange() function with Python 3, you will get NameError: name 'xrange' is not defined error.

To understand how these two functions are similar, consider the following example:

# Print the below statement 3 times
for number in range(5,10,2) :  
    print("I am number : "+str(number))
I am number : 5
I am number : 7
I am number : 9

By running the code above, you will see how the variable number's value is skipped by a factor of 2, and that's because of the parameters in the range() function.

The first parameter in this function is the start parameter. That is the point from where the control starts counting. The second parameter is the stop parameter which is the point where the control has to stop and the last parameter is the step function, which defines the factor by which the control has to jump while counting.

So, in the above case, the control start from 5 then it traverses the loop till 9 while adding 2 during every count. This means 5, 5+2=7, 7+2=9.

You have learned how the range() function is used to define the number of times your code has to loop. Now, in Python 2.x, you'll also find another way to do this and that's with the xrange() function. Run the below code:

# Print the below statement 3 times
for number in xrange(10) :  
    print("I am number : "+str(number))
I am number : 0
I am number : 1
I am number : 2
I am number : 3
I am number : 4
I am number : 5
I am number : 6
I am number : 7
I am number : 8
I am number : 9

What difference did you see in the output of the above code vs the output of the code without the xrange() function? No difference?

That's right. You won't see any difference in the output of the code.

So why should you use the xrange() function? You'll get to this a little later on the tutorial. First run the code below:

print(xrange(10))
print(range(10))
xrange(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

You can see that in the output of the above code, there is a difference in the output of both the print statements. In the print statement, which contains the xrange() function, you get the xrange() function object printed. This is different in the print statement that has the range() function: there, you get a list of integers from 0 until 9.

Now, this is exactly what the difference between the range() function and the xrange() function is.

When you define the range() function, a list of the entire range is stored in the RAM and presented to you. However, when you define the xrange() function, a list is not stored in the memory. Instead, the xrange() function generates integers in the entire range when you need it. This way, the xrange() function makes helps in conserving memory in resource-starved system.

Hone Your Python Skills!

Congrats, you have made it to the end of this tutorial. Now that you have learned how to use loops in Python, go ahead and practice. The more you practice, the better!

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