Errors in Python

Errors in Python

In this tutorial we will talk about how to fix errors in Python.

Clearly at the beginning of programming in Python some mistakes will be made, but gradually they will decrease more and more.

It is important to understand how to manage them right away.

There are therefore various types of errors:

Lexical errors in Python

Lexical errors arise from the use of terms that do not belong to the language.

Let’s take an example immediately:

>>> a = integ(input())

Traceback (most recent call last):

File “<pyshell#31>”, line 1, in <module>

a = integ(input())

NameError: name ‘integ’ is not defined

In this case the integ doesn’t belong to the language, in fact the interpreter warns that it is not defined.

Syntactic errors in Python

Syntactic errors occur in many cases:

  • For example, when language keywords are used for other purposes.
  • When you forget to close a parenthesis (, [or {.
  • If within a condition there is only one = instead of the double equal ==.
  • If a colon (:) is missing at the end of the header of each compound statement, including the for, while, if and def statements (instructions that we will study later).
  • It can happen that the delimiters of the strings are not paired correctly or that the strings do not terminate properly.
  • Indentation errors. In fact, in Python we will see that indentation is fundamental. In my opinion, this is good because it allows you to write code that is clean and easily readable by other programmers.

Some examples of syntax errors in Python

Here is an example of using for as a variable to hold an integer value. For is in fact a keyword and cannot be used as a variable.

>>>for = 15

SyntaxError: invalid syntax


Here’s another example where we forget to open a round bracket:

>>>side = int(input))

SyntaxError: invalid syntax

Logical or semantic errors in Python

In this case, the error must be found in the algorithm resolution. Certainly from a logical point of view there will be something wrong, so we need to review the possible resolution again.

In the meantime, a simple suggestion is to understand which part is not working, going step by step, so as to focus only on that.

Runtime errors in Python

Runtime errors are execution errors, that is, they occur during program execution.

It can happen when exceptions occur, or if you throw an infinite loop or recursion for example.

We will see some cases in detail below.

Conclusioni

In this lesson we have covered some examples of possible programming errors in Python

Useful links

Python tutorial

Python Compiler

Install Python

Variables

Casting in Python

Exercises in Python

Exercises in Python

We develop some exercises in Python in order to consolidate what we have studied so far.

First exercise in Python

Calculate the area of ​​a circle by taking the radius as input.

So here is the solution to the simple problem in Python:

>>> radius = float(input())

5.5

>>> PiGreco = 3.14

>>> area = PiGreco*radius *radius

>>> print(‘the area of ​​the circle of radius’, radius, ‘ is:’, area)

the area of ​​the circle of radius 5.5 is 94,985.

The data to be taken as input is therefore only the radius. PiGreco is a constant value to which I assign the approximate value 3.14.

In Python there is no significant difference between declaring a constant or a variable.

Recall that the constant represents data that does not change during the execution of the program, unlike the variable.

Later we will use the math library and therefore the constant math.pi.

Second exercise in Python

Among the Python exercises that we will deal with today, there is also this very simple one:

Take the price of a product as input and discount it by 30%.

>>> price = float(input())

34.6

>>> price -= price *30/100

>>> price

24.22

The expression price -= price * 30/100 is nothing more than the abbreviated form of price = price – price * 30/100, as we explained in the lesson on assignment operators.

You could also write price * = 70/100 or price * = 0.7.

I did everything using a single variable because the price variable is no longer used within the program. If, on the other hand, it is necessary, it would be advisable to create another variable.

Third exercise in Python

We continue with other exercises in Python and therefore I propose the following:

Calculate the area of ​​a trapezoid by taking as input the major base, the minor base and the height.

The resolution of this algorithm is therefore very simple:

>>> B = int(input()) #I take the major base as input.

58

>>> b = int(input()) #I take the minor base as input.

30

>>> h = int(input()) #I take the height as input.

16

>>> area=(B+b)*h/2 #calculating the area of ​​the trapezium

>>> print(‘the trapezius area is: ‘, area) #I view the area

the trapezius area is 704.0.

Conclusion

In this tutorial I have explained some very simple exercises in Python, in the next lessons we will practice again.

Some useful links

Python tutorial

Python Compiler

Install Python

Variables

Assignment operators

Strings

Casting

How to find the maximum of N numbers

Python

Bubble sort

Matplotlib Plot

Python list sort

Python list sort

In this lesson I will talk about Python list sort method which is useful for quickly sorting a list in ascending or descending order.

So let’s create some examples to understand how it works.

Ascending / descending sorting of a list with Python list sort

I take as input a list of any numbers and apply the sort method on it to sort in ascending direction.


numbers = [1,7,9,3,4]
numbers.sort()
print(numbers)

Python list sort reverse parameter

We now sort in descending order using the optional reverse parameter. If reverse is False, the list is sorted in ascending order, it is in fact the default value, if reverse is True, the list is sorted in descending order.

Here is an example:


numbers = [1,7,9,3,4]
numbers.sort(reverse=True)
print(numbers)

Key parameter

The key parameter allows you to specify a sort order based on a function.

Let’s take an example by sorting a list based on the length of the names. We define a function that calculates the length of the names of an array.

We apply the sorting by setting the key with the defined function.

Here is the simple example of the Python list sort () algorithm:


names = ['Paul','Robert','Elena','Tom']

def len_names(array):
   return len(array)

names.sort(key=len_names)

print(names)

If we want to order in reverse order, just indicate the reverse parameter as well.


names = ['Paul','Robert','Elena','Tom']

def len_names(array):
   return len(array)

names.sort(reverse = True, key=len_names)

print(names)

Sorting example with Python list sort

In this example we try to sort a list of uppercase and lowercase letters.

This is an example:



names = ['B','a','C','s']
names.sort()

print(names)

In output we will have: [‘B’, ‘C’, ‘a’, ‘s’].

The result is not what we expected! Because? Obviously because each letter of the alphabet corresponds to a character of the ASCII encoding and the uppercase letters have a different encoding than the lowercase ones.

We can obtain a correct ordering for example by converting all the characters in the list to lowercase.


names = ['B','a','C','s']
names_order = [name.lower() for name in names]
names_order.sort()

print(names_order)

We could also write like this:


names = ['B','a','C','s']

for i in range(len(names)):
    names[i] = names[i].lower()

names.sort()

print(names)

Conclusion

In this lesson we have seen how to quickly sort a list using Python sort, in the next lessons we will study some sorting algorithms for educational purposes.

Some useful links

Python tutorial

Python Compiler

Install Python

Variables

Assignment operators

Strings

Casting

How to find the maximum of N numbers

Python

Bubble sort

Matplotlib Plot

Python Script Example

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

Swap Python

Swap Python

Given two variables we create a Python program to swap their values.

In this lesson, therefore, we will implement a simple algorithm for swap variables in Python, in order to also introduce the concept of multiple assignment.

Given in input the values ​​of two variables a and b, we want to swap their values, so that at the end a contains the value of b and b that of a.

So here’s an example:

If a = 5 and b = 4, we want that at the end of our algorithm it is a = 4 and b = 5.

So let’s think about a possible solution! Surely, to exchange these values, a possible solution could be to use a temporary support variable.

I call this third variable temp, and I proceed like this:

temp = a # in the temp variable I store the value of a

a = b #in a I store the value of the variable b

b = temp #in b I store the value of the temp variable which contains the value of a

So I get the exchange of values. In the end, in fact, I will have: a = 4 and b = 5.

But beware, there is another way to swap variables in Python.

I, therefore, introduce the concept of multiple assignment.

Swap Python – Multiple assignment

With multiple assignment in python, you can assign multiple variables at a time.

So for example:

a = b = 5

In this case both a and b take the value of 5.

Or another assignment I can make is this:

a, b = 5, 4

In this way I assign the value 5 to a and the value 4 to a b.

If I write later:

a, b = b, a

I get the exchange of the two values.

Swap program in Python

Here is the complete solution:

a = int (input (‘Insert a:’))
b = int (input (‘Insert b:’))
print (‘The values ​​entered are a:’, a, ‘and b:’, b)
print (‘Now exchange the values’)
a, b = b, a
print (‘The values ​​exchanged are a:’, a, ‘and b:’, b)


a = int (input ('Insert a:'))
b = int (input ('Insert b:'))
print ('The values ​​entered are a:', a, 'and b:', b)
print ('Now exchange the values')
a, b = b, a
print ('The values ​​exchanged are a:', a, 'and b:', b)

This is just a very simple example of swapping variables in python with multiple assignment.

Conclusion

In this lesson we have dealt with the study of swap variables in Python, in the next lessons we will apply this concept to many practical exercises.

Some useful links

Python tutorial

Python Compiler

Install Python

Variables

Assignment operators

Strings

Casting

How to find the maximum of N numbers

Python

Bubble sort

Matplotlib Plot