< previous | Table of Contents | < järgmine |
2.7 COMMON ERRORS
USER INPUT ERRORS
Since input()
returns a string, failing to convert this to the necessary type can lead to erroneous results.
# Taking two numbers as input num1 = input("Enter the first number: ") num2 = input("Enter the second number: ") # Trying to add the numbers without converting to integers sum = num1 + num2
If the user enters 3 and 4, the expected mathematical result is 7. However, without type conversion, the output will be the string concatenation 34, not the numeric addition.
If we tried, for example, multiplying the two variables without type conversion instead, we'd get a TypeError
as you cannot conduct such an operation on two strings.
UNINITIALIZED VARIABLES
Using variables before they have been initialized can lead to NameError
.
# x has not been defined. Trying to execute the print command will result in a NameError y = 10 print(x + y)
Here's an example in Thonny.
TYPE CONVERSION ERRORS
Trying to convert incompatible types such as a string of letters or words to int will raise a ValueError.
# Raises ValueError since "abc" cannot be converted to int int("abc")
Here's an example of what that would look like in Thonny.
LOSS OF DATA
Converting from a float to an int can lead to unexpected loss of data due to how Python handles the conversion as shown in the example below. So you should be careful. Converting from int to float, however, is a safe operation.
print(int(3.99)) # Outputs 3, not 4
< previous | Table of Contents | < järgmine |