Arvutiteaduse instituut
  1. Kursused
  2. 2024/25 sügis
  3. Programmeerimise alused (MTAT.03.236)
EN
Logi sisse

Programmeerimise alused 2024/25 sügis

  • 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

  • Arvutiteaduse instituut
  • Loodus- ja täppisteaduste valdkond
  • Tartu Ülikool
Tehniliste probleemide või küsimuste korral kirjuta:

Kursuse sisu ja korralduslike küsimustega pöörduge kursuse korraldajate poole.
Õppematerjalide varalised autoriõigused kuuluvad Tartu Ülikoolile. Õppematerjalide kasutamine on lubatud autoriõiguse seaduses ettenähtud teose vaba kasutamise eesmärkidel ja tingimustel. Õppematerjalide kasutamisel on kasutaja kohustatud viitama õppematerjalide autorile.
Õppematerjalide kasutamine muudel eesmärkidel on lubatud ainult Tartu Ülikooli eelneval kirjalikul nõusolekul.
Courses’i keskkonna kasutustingimused