Every program needs a place to keep what it knows: a score, a name, a price. In this course you learn to keep values in variables, to change them step by step, to follow a program by hand, to tell the four kinds of value apart, to choose names that other people can read, and to put it all together in a small project. Every lesson ends with practice that checks your answers for you.
5 lessons, about 3 h 10 min5 simulations14 problems10 practice questionsPython in every lesson
A variable is a name that holds a value. The = sign stores the value on its right in the name on its left, so age = 12 is correct and 12 = age is an error. We use the name, without quotation marks, to get the value back. A variable can be given a new value, and then the old value is forgotten. A variable must be made before it is used, or Python shows a NameError.
A new value of a variable can be worked out from its old value: score = score + 10. The short forms +=, -=, *= and /= do the same. The order of the lines matters, so we follow a program with a trace table, one row for each line. To swap two variables we keep the first value in a third variable, or we write a, b = b, a. A swap written as a = b and then b = a does not work, because the first value is lost.
Every value has a type. An int is a whole number, a float has a decimal point, a str is text inside quotation marks and a bool is True or False. The function type() tells which one a value is. The same + sign adds numbers and joins text, so text that looks like a number must be changed with int() or float() before a sum. A float can show a very small error, as in 0.1 + 0.2, so we round when we show it.
A name can have letters, digits and underscores, but it cannot start with a digit, contain a space or a hyphen, or be a Python keyword. Small and capital letters are different, so score and Score are two variables. A good name says what the variable holds, and the usual style is small letters with underscores, as in total_marks. Never give a variable the name of a function that Python already has, such as str or print. A comment, which starts with #, explains the program to a person.
In this project we write a shop bill in four steps: the facts, the cost of each kind of item, the bill before tax, the tax and the total, and the display. We keep each fact in a variable, so that one change updates the whole bill. We check the answer by hand, change the facts to test it, and read an error message when it breaks. The project uses everything in this course: variables, updates, types and good names.
Log in to join the discussion.
Loading…