Institute of Computer Science
  1. Courses
  2. 2024/25 fall
  3. Introduction to Programming (MTAT.03.236)
ET
Log in

Introduction to Programming 2024/25 fall

  • Home Page
  • Introduction
  • Expressions
  • Conditional Execution
  • Functions
  • Iterations
  • Strings
  • Files
  • Lists
  • Graphics?
< previousTable 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

< previousTable of Contents< järgmine

  • Institute of Computer Science
  • Faculty of Science and Technology
  • University of Tartu
In case of technical problems or questions write to:

Contact the course organizers with the organizational and course content questions.
The proprietary copyrights of educational materials belong to the University of Tartu. The use of educational materials is permitted for the purposes and under the conditions provided for in the copyright law for the free use of a work. When using educational materials, the user is obligated to give credit to the author of the educational materials.
The use of educational materials for other purposes is allowed only with the prior written consent of the University of Tartu.
Terms of use for the Courses environment