Logic errors in python

Syntax and logical errors

1. Syntax errors – usually the easiest to spot, syntax errors occur when you make a typo. Not ending an if statement with the colon is an example of an syntax error, as is misspelling a Python keyword (e.g. using whille instead of while). Syntax error usually appear at compile time and are reported by the interpreter.

Here is an example of a syntax error:

x = int(input('Enter a number: ')) whille x%2 == 0: print('You have entered an even number.') else: print('You have entered an odd number.')

Notice that the keyword whille is misspelled. If we try to run the program, we will get the following error:

C:Python34Scripts>python error.py File "error.py", line 3 whille x%2 == 0: ^ SyntaxError: invalid syntax

2. Logical errors – also called semantic errors, logical errors cause the program to behave incorrectly, but they do not usually crash the program. Unlike a program with syntax errors, a program with logic errors can be run, but it does not operate as intended.

Consider the following example of an logical error:

x = float(input('Enter a number: ')) y = float(input('Enter a number: ')) z = x+y/2 print('The average of the two numbers you have entered is:',z)

The example above should calculate the average of the two numbers the user enters. But, because of the order of operations in arithmetic (the division is evaluated before addition) the program will not give the correct answer:

>>> Enter a number: 3 Enter a number: 4 The average of the two numbers you have entered is: 5.0 >>>

To rectify this problem, we will simply add the parentheses: z = (x+y)/2

Now we will get the correct result:

>>> Enter a number: 3 Enter a number: 4 The average of the two numbers you have entered is: 3.5 >>>

Источник

Python Programming/Errors

In python there are three types of errors; syntax errors, logic errors and exceptions.

Contents

Syntax errors [ edit | edit source ]

Syntax errors are the most basic type of error. They arise when the Python parser is unable to understand a line of code. Syntax errors are almost always fatal, i.e. there is almost never a way to successfully execute a piece of code containing syntax errors. Some syntax errors can be caught and handled, like eval(«»), but these are rare.

In IDLE, it will highlight where the syntax error is. Most syntax errors are typos, incorrect indentation, or incorrect arguments. If you get this error, try looking at your code for any of these.

Logic errors [ edit | edit source ]

These are the most difficult type of error to find, because they will give unpredictable results and may crash your program. A lot of different things can happen if you have a logic error. However these are very easy to fix as you can use a debugger, which will run through the program and fix any problems.

A simple example of a logic error can be showcased below, the while loop will compile and run however, the loop will never finish and may crash Python:

#Counting Sheep #Goal: Print number of sheep up until 101. sheep_count=1 while sheep_count100: print("%i Sheep"%sheep_count) 

Logic errors are only erroneous in the perspective of the programming goal one might have; in many cases Python is working as it was intended, just not as the user intended. The above while loop is functioning correctly as Python is intended to, but the exit the condition the user needs is missing.

Exceptions [ edit | edit source ]

Exceptions arise when the python parser knows what to do with a piece of code but is unable to perform the action. An example would be trying to access the internet with python without an internet connection; the python interpreter knows what to do with that command but is unable to perform it.

Dealing with exceptions [ edit | edit source ]

Unlike syntax errors, exceptions are not always fatal. Exceptions can be handled with the use of a try statement.

Consider the following code to display the HTML of the website ‘example.com’. When the execution of the program reaches the try statement it will attempt to perform the indented code following, if for some reason there is an error (the computer is not connected to the internet or something) the python interpreter will jump to the indented code below the ‘except:’ command.

import urllib2 url = 'http://www.example.com' try: req = urllib2.Request(url) response = urllib2.urlopen(req) the_page = response.read() print(the_page) except: print("We have a problem.") 

Another way to handle an error is to except a specific error.

try: age = int(raw_input("Enter your age: ")) print("You must be  years old.".format(age)) except ValueError: print("Your age must be numeric.") 

If the user enters a numeric value as his/her age, the output should look like this:

Enter your age: 5 Your age must be 5 years old.

However, if the user enters a non-numeric value as his/her age, a ValueError is thrown when trying to execute the int() method on a non-numeric string, and the code under the except clause is executed:

Enter your age: five Your age must be numeric.

You can also use a try block with a while loop to validate input:

valid = False while valid == False: try: age = int(raw_input("Enter your age: ")) valid = True # This statement will only execute if the above statement executes without error. print("You must be  years old.".format(age)) except ValueError: print("Your age must be numeric.") 

The program will prompt you for your age until you enter a valid age:

Enter your age: five Your age must be numeric. Enter your age: abc10 Your age must be numeric. Enter your age: 15 You must be 15 years old.

In certain other cases, it might be necessary to get more information about the exception and deal with it appropriately. In such situations the except as construct can be used.

f=raw_input("enter the name of the file:") l=raw_input("enter the name of the link:") try: os.symlink(f,l) except OSError as e: print("an error occurred linking %s to %s: %s\n error no %d"%(f,l,e.args[1],e.args[0])) 
enter the name of the file:file1.txt enter the name of the link:AlreadyExists.txt an error occurred linking file1.txt to AlreadyExists.txt: File exists error no 17 enter the name of the file:file1.txt enter the name of the link:/Cant/Write/Here/file1.txt an error occurred linking file1.txt to /Cant/Write/Here/file1.txt: Permission denied error no 13

Источник

Читайте также:  Вывод чисел через пробел питон
Оцените статью