Learning Python: From Zero to Hero

First of all, what is Python? According to its creator, Guido van Rossum, Python is a:

First of all, what is Python? According to its creator, Guido van Rossum, Python is a:

“high-level programming language, and its core design philosophy is all about code readability and a syntax which allows programmers to express concepts in a few lines of code.”

For me, the first reason to learn Python was that it is, in fact, a beautifulprogramming language. It was really natural to code in it and express my thoughts.

Another reason was that we can use coding in Python in multiple ways: data science, web development, and machine learning all shine here. Quora, Pinterest and Spotify all use Python for their backend web development. So let’s learn a bit about it.

The Basics

1. Variables

You can think about variables as words that store a value. Simple as that.


In Python, it is really easy to define a variable and set a value to it. Imagine you want to store number 1 in a variable called “one.” Let’s do it:

one = 1

How simple was that? You just assigned the value 1 to the variable “one.”

two = 2
some_number = 10000

And you can assign any other value to whatever other variables you want. As you see in the table above, the variable “two” stores the integer 2, and “some_number” stores 10,000.

Besides integers, we can also use booleans (True / False), strings, float, and so many other data types.

# booleans
true_boolean = True
false_boolean = False
string

my_name = "Leandro Tk"

float

book_price = 15.80

2. Control Flow: conditional statements

If” uses an expression to evaluate whether a statement is True or False. If it is True, it executes what is inside the “if” statement. For example:

if True:
print("Hello Python If")

if 2 > 1:
print("2 is greater than 1")

2 is greater than 1, so the “print” code is executed.

The “else” statement will be executed if the “if” expression is false.

if 1 > 2:
print("1 is greater than 2")
else:
print("1 is not greater than 2")

1 is not greater than 2, so the code inside the “else” statement will be executed.

You can also use an “elif” statement:

if 1 > 2:
print("1 is greater than 2")
elif 2 > 1:
print("1 is not greater than 2")
else:
print("1 is equal to 2")

3. Looping / Iterator

In Python, we can iterate in different forms. I’ll talk about two: while and for.


While Looping: while the statement is True, the code inside the block will be executed. So, this code will print the number from 1 to 10.

num = 1

while num <= 10:
print(num)
num += 1

The while loop needs a “loop condition.” If it stays True, it continues iterating. In this example, when num is 11 the loop condition equals False.

Another basic bit of code to better understand it:


loop_condition = True

while loop_condition:
print("Loop Condition keeps: %s" %(loop_condition))
loop_condition = False

The loop condition is True so it keeps iterating — until we set it to False.

For Looping: you apply the variable “num” to the block, and the “for” statement will iterate it for you. This code will print the same as while code: from 1 to 10.

for i in range(1, 11):
print(i)

See? It is so simple. The range starts with 1 and goes until the 11th element (10 is the 10th element).

List: Collection | Array | Data Structure

Imagine you want to store the integer 1 in a variable. But maybe now you want to store 2. And 3, 4, 5 …


Do I have another way to store all the integers that I want, but not in millions of variables? You guessed it — there is indeed another way to store them.

List is a collection that can be used to store a list of values (like these integers that you want). So let’s use it:

my_integers = [1, 2, 3, 4, 5]

It is really simple. We created an array and stored it on my_integer.

But maybe you are asking: “How can I get a value from this array?”

Great question. List has a concept called index. The first element gets the index 0 (zero). The second gets 1, and so on. You get the idea.

To make it clearer, we can represent the array and each element with its index. I can draw it:

Using the Python syntax, it’s also simple to understand:

my_integers = [5, 7, 1, 3, 4]
print(my_integers[0]) # 5
print(my_integers[1]) # 7
print(my_integers[4]) # 4

Imagine that you don’t want to store integers. You just want to store strings, like a list of your relatives’ names. Mine would look something like this:

relatives_names = [
"Toshiaki",
"Juliana",
"Yuji",
"Bruno",
"Kaio"
]

print(relatives_names[4]) # Kaio

It works the same way as integers. Nice.

We just learned how Lists indices work. But I still need to show you how we can add an element to the List data structure (an item to a list).

The most common method to add a new value to a List is append. Let’s see how it works:

bookshelf = []
bookshelf.append("The Effective Engineer")
bookshelf.append("The 4 Hour Work Week")
print(bookshelf[0]) # The Effective Engineer
print(bookshelf[1]) # The 4 Hour Work Week

append is super simple. You just need to apply the element (eg. “The Effective Engineer”) as the append parameter.

Well, enough about Lists. Let’s talk about another data structure.

Dictionary: Key-Value Data Structure

Now we know that Lists are indexed with integer numbers. But what if we don’t want to use integer numbers as indices? Some data structures that we can use are numeric, string, or other types of indices.


Let’s learn about the Dictionary data structure. Dictionary is a collection of key-value pairs. Here’s what it looks like:

dictionary_example = {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}

The key is the index pointing to the value. How do we access the Dictionaryvalue? You guessed it — using the key. Let’s try it:

dictionary_tk = {
"name": "Leandro",
"nickname": "Tk",
"nationality": "Brazilian"
}

print("My name is %s" %(dictionary_tk["name"])) # My name is Leandro
print("But you can call me %s" %(dictionary_tk["nickname"])) # But you can call me Tk
print("And by the way I'm %s" %(dictionary_tk["nationality"])) # And by the way I'm Brazilian

I created a Dictionary about me. My name, nickname, and nationality. Those attributes are the Dictionary keys.

As we learned how to access the List using index, we also use indices (keysin the Dictionary context) to access the value stored in the Dictionary.

In the example, I printed a phrase about me using all the values stored in the Dictionary. Pretty simple, right?

Another cool thing about Dictionary is that we can use anything as the value. In the Dictionary I created, I want to add the key “age” and my real integer age in it:

ictionary_tk = { "name": "Leandro", "nickname": "Tk", "nationality": "Brazilian", "age": 24} print("My name is %s" %(dictionary_tk["name"])) # My name is Leandroprint("But you can call me %s" %(dictionary_tk["nickname"])) # But you can call me Tkprint("And by the way I'm %i and %s" %(dictionary_tk["age"], dictionary_tk["nationality"])) # And by the way I'm Brazilian

Here we have a key (age) value (24) pair using string as the key and integer as the value.

As we did with Lists, let’s learn how to add elements to a Dictionary. The key pointing to a value is a big part of what Dictionary is. This is also true when we are talking about adding elements to it:


dictionary_tk = {
"name": "Leandro",
"nickname": "Tk",
"nationality": "Brazilian"
}

dictionary_tk['age'] = 24

print(dictionary_tk) # {'nationality': 'Brazilian', 'age': 24, 'nickname': 'Tk', 'name': 'Leandro'}

We just need to assign a value to a Dictionary key. Nothing complicated here, right?

Iteration: Looping Through Data Structures

As we learned in the Python Basics, the List iteration is very simple. We Python developers commonly use For looping. Let’s do it:

bookshelf = [
"The Effective Engineer",
"The 4 hours work week",
"Zero to One",
"Lean Startup",
"Hooked"
]

for book in bookshelf:
print(book)

So for each book in the bookshelf, we (can do everything with it) print it. Pretty simple and intuitive. That’s Python.

For a hash data structure, we can also use the for loop, but we apply the key :

dictionary = { "some_key": "some_value" }

for key in dictionary:
print("%s --> %s" %(key, dictionary[key]))

some_key --> some_value

This is an example how to use it. For each key in the dictionary , we printthe key and its corresponding value.

Another way to do it is to use the iteritems method.

dictionary = { "some_key": "some_value" }

for key, value in dictionary.items():
print("%s --> %s" %(key, value))

some_key --> some_value

We did name the two parameters as key and value, but it is not necessary. We can name them anything. Let’s see it:

dictionary_tk = {
"name": "Leandro",
"nickname": "Tk",
"nationality": "Brazilian",
"age": 24
}

for attribute, value in dictionary_tk.items():
print("My %s is %s" %(attribute, value))

My name is Leandro My nickname is Tk My nationality is Brazilian My age is 24

We can see we used attribute as a parameter for the Dictionary key, and it works properly. Great!

Classes & Objects

A little bit of theory:

Objects are a representation of real world objects like cars, dogs, or bikes. The objects share two main characteristics: data and behavior.


Cars have data, like number of wheels, number of doors, and seating capacity They also exhibit behavior: they can accelerate, stop, show how much fuel is left, and so many other things.

We identify data as attributes and behavior as methods in object-oriented programming. Again:

Data → Attributes and Behavior → Methods

And a Class is the blueprint from which individual objects are created. In the real world, we often find many objects with the same type. Like cars. All the same make and model (and all have an engine, wheels, doors, and so on). Each car was built from the same set of blueprints and has the same components.

Python Object-Oriented Programming mode: ON

Python, as an Object-Oriented programming language, has these concepts: class and object.


A class is a blueprint, a model for its objects.

So again, a class it is just a model, or a way to define attributes and behavior(as we talked about in the theory section). As an example, a vehicle class has its own attributes that define what objects are vehicles. The number of wheels, type of tank, seating capacity, and maximum velocity are all attributes of a vehicle.

With this in mind, let’s look at Python syntax for classes:

class Vehicle:
pass

We define classes with a class statement — and that’s it. Easy, isn’t it?

Objects are instances of a class. We create an instance by naming the class.

car = Vehicle()
print(car) # <main.Vehicle instance at 0x7fb1de6c2638>

Here car is an object (or instance) of the class Vehicle.

Remember that our vehicle class has four attributes: number of wheels, type of tank, seating capacity, and maximum velocity. We set all these attributeswhen creating a vehicle object. So here, we define our class to receive data when it initiates it:

class Vehicle:
def init(self, number_of_wheels, type_of_tank, seating_capacity, maximum_velocity):
self.number_of_wheels = number_of_wheels
self.type_of_tank = type_of_tank
self.seating_capacity = seating_capacity
self.maximum_velocity = maximum_velocity

We use the init method. We call it a constructor method. So when we create the vehicle object, we can define these attributes. Imagine that we love the Tesla Model S, and we want to create this kind of object. It has four wheels, runs on electric energy, has space for five seats, and the maximum velocity is 250km/hour (155 mph). Let’s create this object:

tesla_model_s = Vehicle(4, 'electric', 5, 250)

Four wheels + electric “tank type” + five seats + 250km/hour maximum speed.

All attributes are set. But how can we access these attributes’ values? We send a message to the object asking about them. We call it a method. It’s the object’s behavior. Let’s implement it:

class Vehicle:
def init(self, number_of_wheels, type_of_tank, seating_capacity, maximum_velocity):
self.number_of_wheels = number_of_wheels
self.type_of_tank = type_of_tank
self.seating_capacity = seating_capacity
self.maximum_velocity = maximum_velocity

def number_of_wheels(self):
    return self.number_of_wheels

def set_number_of_wheels(self, number):
    self.number_of_wheels = number

This is an implementation of two methods: number_of_wheels and set_number_of_wheels. We call it getter & setter. Because the first gets the attribute value, and the second sets a new value for the attribute.

In Python, we can do that using @property (decorators) to define gettersand setters. Let’s see it with code:

class Vehicle:
def init(self, number_of_wheels, type_of_tank, seating_capacity, maximum_velocity):
self.number_of_wheels = number_of_wheels
self.type_of_tank = type_of_tank
self.seating_capacity = seating_capacity
self.maximum_velocity = maximum_velocity

@property
def number_of_wheels(self):
    return self.__number_of_wheels

@number_of_wheels.setter
def number_of_wheels(self, number):
    self.__number_of_wheels = number

And we can use these methods as attributes:

tesla_model_s = Vehicle(4, 'electric', 5, 250)
print(tesla_model_s.number_of_wheels) # 4
tesla_model_s.number_of_wheels = 2 # setting number of wheels to 2
print(tesla_model_s.number_of_wheels) # 2

This is slightly different than defining methods. The methods work as attributes. For example, when we set the new number of wheels, we don’t apply two as a parameter, but set the value 2 to number_of_wheels. This is one way to write pythonic getter and setter code.

But we can also use methods for other things, like the “make_noise” method. Let’s see it:

class Vehicle:
def init(self, number_of_wheels, type_of_tank, seating_capacity, maximum_velocity):
self.number_of_wheels = number_of_wheels
self.type_of_tank = type_of_tank
self.seating_capacity = seating_capacity
self.maximum_velocity = maximum_velocity

def make_noise(self):
    print('VRUUUUUUUM')

When we call this method, it just returns a string VRRRRUUUUM.

tesla_model_s = Vehicle(4, 'electric', 5, 250)
tesla_model_s.make_noise() # VRUUUUUUUM

Encapsulation: Hiding Information

Encapsulation is a mechanism that restricts direct access to objects’ data and methods. But at the same time, it facilitates operation on that data (objects’ methods).


“Encapsulation can be used to hide data members and members function. Under this definition, encapsulation means that the internal representation of an object is generally hidden from view outside of the object’s definition.” — Wikipedia

All internal representation of an object is hidden from the outside. Only the object can interact with its internal data.

First, we need to understand how public and non-public instance variables and methods work.

Public Instance Variables

For a Python class, we can initialize a public instance variable within our constructor method. Let’s see this:


Within the constructor method:


class Person:
def init(self, first_name):
self.first_name = first_name

Here we apply the first_name value as an argument to the public instance variable.

tk = Person('TK')
print(tk.first_name) # => TK

Within the class:

class Person:
first_name = 'TK'

Here, we do not need to apply the first_name as an argument, and all instance objects will have a class attribute initialized with TK.

tk = Person()
print(tk.first_name) # => TK

Cool. We have now learned that we can use public instance variables and class attributes. Another interesting thing about the public part is that we can manage the variable value. What do I mean by that? Our object can manage its variable value: Get and Set variable values.

Keeping the Person class in mind, we want to set another value to its first_name variable:

tk = Person('TK')
tk.first_name = 'Kaio'
print(tk.first_name) # => Kaio

There we go. We just set another value (kaio) to the first_name instance variable and it updated the value. Simple as that. Since it’s a public variable, we can do that.

Non-public Instance Variable

We don’t use the term “private” here, since no attribute is really private in Python (without a generally unnecessary amount of work). — PEP 8

As the public instance variable , we can define the non-public instance variable both within the constructor method or within the class. The syntax difference is: for non-public instance variables , use an underscore (_) before the variable name.

“‘Private’ instance variables that cannot be accessed except from inside an object don’t exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member)” — Python Software Foundation

Here’s an example:

class Person:
def init(self, first_name, email):
self.first_name = first_name
self._email = email

Did you see the email variable? This is how we define a non-public variable :

tk = Person('TK', '[email protected]')
print(tk._email) # [email protected]
We can access and update it. Non-public variables are just a convention and should be treated as a non-public part of the API.

So we use a method that allows us to do it inside our class definition. Let’s implement two methods (email and update_email) to understand it:

class Person:
def init(self, first_name, email):
self.first_name = first_name
self._email = email

def update_email(self, new_email):
    self._email = new_email

def email(self):
    return self._email

Now we can update and access non-public variables using those methods. Let’s see:

tk = Person('TK', '[email protected]')
print(tk.email()) # => [email protected]

tk._email = '[email protected]' -- treat as a non-public part of the class API

print(tk.email()) # => [email protected]
tk.update_email('[email protected]')
print(tk.email()) # => [email protected]

  1. We initiated a new object with first_name TK and email [email protected]
  2. Printed the email by accessing the non-public variable with a method
  3. Tried to set a new email out of our class
  4. We need to treat non-public variable as non-public part of the API
  5. Updated the non-public variable with our instance method
  6. Success! We can update it inside our class with the helper method


Public Method

With public methods, we can also use them out of our class:

class Person:
def init(self, first_name, age):
self.first_name = first_name
self._age = age

def show_age(self):
    return self._age

Let’s test it:

tk = Person('TK', 25)
print(tk.show_age()) # => 25

Great — we can use it without any problem.

Non-public Method

But with non-public methods we aren’t able to do it. Let’s implement the same Person class, but now with a showage non-public method using an underscore ().

class Person:
def init(self, first_name, age):
self.first_name = first_name
self._age = age

def _show_age(self):
    return self._age

And now, we’ll try to call this non-public method with our object:

tk = Person('TK', 25)
print(tk._show_age()) # => 25

We can access and update it. Non-public methods are just a convention and should be treated as a non-public part of the API.

Here’s an example for how we can use it:

class Person:
def init(self, first_name, age):
self.first_name = first_name
self._age = age

def show_age(self):
    return self._get_age()

def _get_age(self):
    return self._age

tk = Person('TK', 25)
print(tk.show_age()) # => 25

Here we have a _get_age non-public method and a show_age public method. The show_age can be used by our object (out of our class) and the _get_age only used inside our class definition (inside show_age method). But again: as a matter of convention.

Encapsulation Summary

With encapsulation we can ensure that the internal representation of the object is hidden from the outside.

Inheritance: behaviors and characteristics

Certain objects have some things in common: their behavior and characteristics.


For example, I inherited some characteristics and behaviors from my father. I inherited his eyes and hair as characteristics, and his impatience and introversion as behaviors.

In object-oriented programming, classes can inherit common characteristics (data) and behavior (methods) from another class.

Let’s see another example and implement it in Python.

Imagine a car. Number of wheels, seating capacity and maximum velocity are all attributes of a car. We can say that an ElectricCar class inherits these same attributes from the regular Car class.

class Car:
def init(self, number_of_wheels, seating_capacity, maximum_velocity):
self.number_of_wheels = number_of_wheels
self.seating_capacity = seating_capacity
self.maximum_velocity = maximum_velocity

Our Car class implemented:

my_car = Car(4, 5, 250)
print(my_car.number_of_wheels)
print(my_car.seating_capacity)
print(my_car.maximum_velocity)

Once initiated, we can use all instance variables created. Nice.

In Python, we apply a parent class to the child class as a parameter. An ElectricCar class can inherit from our Car class.

class ElectricCar(Car):
def init(self, number_of_wheels, seating_capacity, maximum_velocity):
Car.init(self, number_of_wheels, seating_capacity, maximum_velocity)

Simple as that. We don’t need to implement any other method, because this class already has it (inherited from Car class). Let’s prove it:

my_electric_car = ElectricCar(4, 5, 250)
print(my_electric_car.number_of_wheels) # => 4
print(my_electric_car.seating_capacity) # => 5
print(my_electric_car.maximum_velocity) # => 250

Beautiful.

That’s it!

We learned a lot of things about Python basics:


  • How Python variables work
  • How Python conditional statements work
  • How Python looping (while & for) works
  • How to use Lists: Collection | Array
  • Dictionary Key-Value Collection
  • How we can iterate through these data structures
  • Objects and Classes
  • Attributes as objects’ data
  • Methods as objects’ behavior
  • Using Python getters and setters & property decorator
  • Encapsulation: hiding information
  • Inheritance: behaviors and characteristics

Congrats! You completed this dense piece of content about Python.

If you want a complete Python course, learn more real-world coding skills and build projects, try One Month Python Bootcamp. See you there


By : TK























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