Introduction to Python Programming - Working with Numbers (
Page 3 of 4 )
You can also work with numbers in Python. If you want to do some simple math (or even complicated math) try this:
#!/usr/local/bin/python #this line must be included in every program
print 1 + 1
print 4 * 4
print 6 – 2
print 8 / 2
print 10 ** 2
print (1 + 1) * 2
The above code demonstrates a list of expressions. It would print out the following:
2
16
4
4
100
4
If you want to mix numbers and text together, you could do this:
#!/usr/local/bin/python #this line must be included in every program
print “Spam costs two dollars.”
print “If you bought two spams it would cost”, 2 + 2
print “If you order two spams but one is bad”
print “Your refund would be”, 4 - 2
print “Of course we do catering as well”
print “We charge 1.25 cents for more than 100 spams.”
print “So a thousand spams would cost you”, 1.25 * 1000
print “Spam to the third power is”, 2 * 2 * 2
This prints out the following:
Spam costs two dollars.
If you bought two spams it would cost 4
If you order two spams but one is bad
Your refund would be 2
Of course we do catering as well
We charge 1.25 cents for more than 100 spams.
So a thousand spams would cost you 1250
Spam to the third power is 8
You will notice that some of the above statements have two arguments. A good example is the second line: “If you bought two spams it would cost”, 2 + 2. The text part is one argument, and then the math (or expression) is a second. When you use more than one argument, you must separate them using a comma. You will also note that the expression 2 + 2 is not surrounded by quotations. If it were, then the program would have printed: If you bought two spams it would cost 2+2. Since there are no quotes, it sees it as a mathematical expression and prints the result instead.