
Variables: More examples (Python debugging)

Upgrade for more content
True or false? "NameError" means we used the same variable name several times.
Lina has written a program, and this is her pseudocode: Note name and age for two users. Calculate the age difference between them and output the result. Here the pseudocode is translated to Python code and saved with the name "program". Let’s test the code. note name and age of two people Oh.
We got an error message! "program line" five. The program has an error on line five. It is a NameError. The name age1 "is not defined". Line five means the fifth instruction.
Let’s look for it. First Second Third Fourth The fifth instruction is: result equals age1 minus age2 This instruction, therefore, contains name errors. age1 is not defined. That means that the age1 variable is not created when used in instruction five. But we created - declared - the variable age1 up here in the code.
Oh, there's a slight difference. Do you see? When we declared the variable, we wrote a capital ‘A’, but tried to use a small ‘a’ later in the code! So we tried to use a variable that doesn’t exist! In Python it matters if it is upper or lower case letters when we give names to variables.
Let’s change to a lowercase "a" and test our code again. When we noted names and ages, then instruction 5 seemed to work. That problem is solved. Good! But we’ve received a new error message!
This time the message tells us number six is wrong. Now it's a TypeError. Wrong type of variable. must be str This means that something should be a text string. not int And this means that it should not be integers.
Instruction number six is the print instruction. Inside the parentheses of the print instruction there are several variables. Which of these variables are integers? n1 is text, "is" is text, result was obtained by taking an integer minus another integer it becomes an integer and not text. We have found the integer that should be text!
Now, let’s change result from an integer type of variable to a text string type. Ah, that’s quite easy to do: Write str and parenthesis before result and end with a parenthesis. Let’s test the code again. Input names and ages as before. Lina 16 Maria 15 Lina is one years older than Maria.
Now it works without any error messages at all! If you want to explore how different error messages look, you can deliberately enter errors in the code and see what error messages you receive.