1. Python Basics1. Python Basics\1.1 Familiarizing Yourself with Python\1.1.3 Numbers

1.1.3 Numbers

 

Of course, computer programs deal in numbers as well as text. Any programming language, including Python, can act as a powerful calculator, because the syntax of the language includes all of the standard mathematical operations.

 

Create a new Python file, type the following and run it:

 

  1. print 4 + 5 / 3.0 * 369.3 + 17.2 - 6.5  

 

You should see this output:

 

630.2

 

When the program is run, the Python interpreter performs all of the calculation automatically, and then turns the number into a string for print.

 

Real life exercise: go find a regular calculator, and use it to do the same calculation. Unless you used a fancy calculator, it probably took longer this way. Python is a great calculator.

 

What happens if you take away the word print from the beginning of the program and just write the numbers? Python still performs the calculation internally, but without the print statement, it does not output anything.

 

Let’s do another one, just to get some practice under our belts. Create a new Python file, type the following and run it:

 

  1. print (4 + 5) * 9 + (3 + 8) * 12 - (1 + 2) + pow(2,5)  

 

You should see this output:

 

242

 

pow(2,5) is Python’s strange way of saying 2^5, or “two to the fifth power”.

 

You can also combine strings and numbers in print statements. Create a new Python file, type the following and run it:

 

  1. print "I have", 4 + 5, "apples."  

 

You should see the output:

 

I have 9 apples.

 

Note that Python has gone to the trouble of adding 4 and 5 before printing.

 

 

Top of Page