Now you can print things with print and you can do math. The next step is to learn about Python variables. In programming a variable is nothing more than a name for something, similar to how my name “Akar” is a name for, “The human who wrote this book.” 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.

Let’s take an simple example for this we can use X and assign it a value 23 and when we need it we call it and use it.

Python Variable Example

I want you to copy the exact code and run it.

cars = 100
space_in_a_car = 4
drivers = 30
passengers = 90
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven

print (“There are”, cars, “cars available.”)
print (“There are only”, drivers, “drivers available.”)
print (“There will be”, cars_not_driven, “empty cars today.”)
print (“We can transport”, carpool_capacity, “people today.”)
print (“We have”, passengers, “to carpool today.”)
print (“We need to put about”, average_passengers_per_car, “in each car.”)

This is a perfect example to explain all about variables. Now run this code

To use any variable we need, to define it use “=” symbol. We can use math algorithm on python variables and use them as many time as we want. You can use a variable multiple time in a script and redefine it in can if required. A variable can be assigned to another variable also.

available_cars = 2
new_cars = 1
available_cars = new_cars + available_cars

In above example we added new cars in available cars and assigned this value back to available cars.

Possible Error

Lets see a code

drivers = 30
carpool_capacity = cars_driven * space_in_a_car
cars_driven = drivers
average_passengers_per_car = passengers / cars_driven

run this code and you will get error like below:-

Now lets understand it setup by step

  1. We ran our command in the Terminal to run the ex1.py script.
  2. It Traceback the error
  3. Python tells us that the file ex1.py have error at line 2.
  4. This is the code where we have error
  5. and the ERROR

But wait we have defined cars_driven in our code then why does python throw an error? That’s because we have define cars_driven in line number 3 and are using it in line number 2. We have to define the variable before we use it.

 

Exercise For today

Use int() and float() functions with variables.

 

 

no comments

Leave me comment