Python script example

In this lesson we will learn how to create some examples of Python scripts, so let’s leave the interactive mode seen so far.

One way to create scripts in Python is to use for example the simple notepad. You write the code and save the file giving a suitable name and a .py extension, making sure you have selected all the files.

To run the script just go to the command prompt, enter the path to the file and press enter, as shown in the screenshot below:

Here’s how to start the prompt:

 examples of Python scripts

Once the prompt is open I go to the specified path, in my case the Python_exercises folder and then I start the script I created previously called area_square.py.

Here the script will run. In fact, I am asked to enter the data, as I had planned.

Prompt

I have shown you this simple way to get acquainted, we, in this tutorial, will work with the IDLE editor that we installed with Python.

Then we start the IDLE and, once opened, go to the File menu and choose New file. This will open the editor with which you can write the source text.

First Python script example

So let’s make our first script.

Take the side of a square as input, calculate and display the area.

Possible solution:

“’

first script

Let’s calculate the area of ​​a square

“’

side = int(input(‘Insert the side of the square:‘))

area = side * side

print(‘The area of the square is: ‘, area)

The text inserted between quotes “’ is the comment that can be clearly left out, as I have already explained to you in the other lessons.

Note that I have entered the message in the input: ‘Insert the side of the square’ to give a message to the user.

Python script example – save the file

Now let’s save the file with the .py extension by going to the File menu and then on Save As. So let’s give the name of area_quadrato.py for simplicity.

We check that there are no errors by going to the Run menu and then Check Module.

If everything is ok, we can run our program by going to Run Module always in the Run menu, alternatively you can press the F5 button.

Here is the figure that shows the step to take:

save script

This will start the program in the Shell window and ask you to insert the side of the square.

In this lesson we have developed an example script in Python.

Some useful links

Python tutorial

Python Compiler

Install Python

Assignment operators

How to find the maximum of N numbers

Python

Bubble sort

Matplotlib Plot

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *