Variable and Names in Python

Variable and Names in Python

Now you can print things with print and you can do math. The next step is to learn about variables.

In programming, a variable is nothing more than a name for something so you can use the name rather than the something as you code.

Programmers use these variable names to make their code read more like English and because they have lousy memories.

If they didn’t use good names for things in their software, they’d get lost when they tried to read their code again.

``````1 cars = 100
2 space_in_a_car = 4.0
3 drivers = 30
4 passengers = 90
5 cars_not_driven = cars -drivers
6 cars_driven = drivers
7 carpool_capacity = cars_driven * space_in_a_car
8 average_passengers_per_car = passengers / cars_driven
9
10
11 print "There are", cars, "cars available."
12 print "There are only", drivers, "drivers available."
13 print "There will be", cars_not_driven, "empty cars today."
14 print "We can transport", carpool_capacity, "people today."
15 print "We have", passengers, "to carpool today."
16 print "We need to put about", average_passengers_per_car, "in each car."``````

Output

`````` There are 100 cars available.
There are only 30 drivers available.
There will be 70 empty cars today.
We can transport 120.0 people today.
We have 90 to carpool today.
We need to put about 3 in each car``````

Study Drills

When I wrote this program the first time I had a mistake, and Python told me about it like this:

`````` Traceback (most recent call last):
File "ex4.py", line 8, in <module>
average_passengers_per_car = car_pool_capacity / passenger
NameError: name 'car_pool_capacity' is not defined``````

Explain this error in your own words. Make sure you use line numbers and explain why.

1. I used 4.0 for space_in_a_car, but is that necessary? What happens if it’s just 4?

2. Remember that 4.0 is a “fl oating point” number. Find out what that means.

3. Write comments above each of the variable assignments.

4. Make sure you know what = is called (equals) and that it’s making names for things.

5. Remember that _ is an underscore character.

6. Try running Python as a calculator like you did before and use variable names to do your calculations. Popular variable names are also i, x, and j.

Common Student Question

What is the difference between = (single- equal) and == (double- equal)?

The = (single- equal) assigns the value on the right to a variable on the left. The == (double- equal) tests if two things have the same value, and you’ll learn about this in Exercise 27.

Can we write x=100 instead of x = 100?

You can, but it’s bad form. You should add space around operators like this so that it’s easier to read.

What do you mean by “read the file backward”?

Very simple. Imagine you have a file with 16 lines of code in it. Start at line 16, and compare it to my file at line 16. Then do it again for 15, and so on, until you’ve read the whole file backward.