Addition, subtraction and multiplication are simple.
>> 10 + 3
13
>> 10 - 3
7
>> 10 * 3
30
But not division.
>> 10 / 3
3
Instead of getting something like 3.33333, we get leftover behavior from the C language which the Python language is implemented. There are some ways to get the expected answer.
Typing (which is tedious, easy to forget, and defeats the purpose of using Python).
>>float(10)/float(3)
3.3333333333333335
or
>>10.0/3.0
3.3333333333333335
Importing the future module. In future Python releases, this will be fixed. After running this, division should proceed normally within your session. Of course, you ask - "Why should I even have to do this?"
>>from __future__ import Division
>> 10/3
3.3333333333333335
Exponentiation is nice.
>> 10 ** 3
1000
But watch those parentheses,
2**2**2 gives 16, not 8. Why?
Because exponentiation is right associative. That is, Python is doing this:
2**(2**2)
not
(2**2)**2
Nice perk about exponentiation in Python. Python displays as many digits as your system memory allows. Python does this without breaking a sweat.
>>123456789**100
1417417260103558770214252423976142668502309843289216833019048237594 757708238986182489372231899746980921982728329402793285767462862882464121 635860400730716254039942351084846547018518131114125220170734365519774681 825663555080960088448187700306662591033835497547065849829393393851336850 513516716654954594842407071059129565467264692831108320130483612672587797 723547589358874240495338978427064891700798459028240889817739929243620390 292500203679620864971533914260827834601579209314189120626901904458486936 727622905582367388818325467159626747054599568953786703562122799941680845 141148189896305104641344839457223830507901762718528867396981775965176554 700698356765830690713630912519126290583362303892345035739308972274807594 103376959348593678587147932967060392101430789829817061010598621196674073 17346718937443597566001L
0 comments:
Post a Comment