HomePython Page 2 - Python 101 (part 2): If Wishes Were Pythons
Tax Evasion - Python
Begin your tour of Python with a look at its number and stringtypes, together with examples of how they can be used in simple Pythonprograms. Along the way, you'll also learn how to build conditionalexpressions, slice and dice strings, and accept user input from the commandline
The first - and simplest - object type you're likely to encounter is the number. I've already shown you a few examples of how Python treats numbers last time - but here's a quick refresher anyway:
There are four basic number types available in
Python:
Integers: These are plain-vanilla numbers like 23, 5748, -947 and 3; they are also the most commonly-used type.
Floats: These are typically decimal numbers, although Python also allows you to use the scientific notation to represent them - for example, 3.67, 98.573 or 5.347e-17.
Long integers: These are integer values which are too large to be handled by the regular Integer type - for example, 45734893498L or 53267282982L. Note the uppercase "L" appended to the end of a long integer, which makes this type easier to identify.
Complex numbers: You may remember these from algebra class (I don't, but that's probably because I slept my way through college) - 2.5+0.3j, 4.1-03.j and so on. These numbers can be broken up into "real" and "imaginary" parts...the "imaginary" part is what you bank, while the "real" part is what the government takes away in taxes.{mospagebreak title=Putting Two And Two Together} Most of the time, you'll be working with integers and floats; the other two types are typically used for specialized applications. And as the example above demonstrates, Python allows you to add, multiply, divide and otherwise mess with these numbers via simple arithmetic operators. Here's an example which demonstrates the important ones:
As with all other programming languages, division and
multiplication take precedence over addition and subtraction, although parentheses can be used to give a particular operation greater precedence. For example,
#!/usr/bin/python
print(10 + 2 * 4)
returns 18, while
#!/usr/bin/python
print((10 + 2) * 4)
returns 48.
It should be noted at this point that
Python does not support the popular auto-increment (++) and auto-decrement (--) operators you may have used in Perl, PHP and JavaScript.
There are also some built-in functions you can use with Python numbers - the most useful are abs() and pow(), which return the absolute value of a number and raise one number to the power of another. Take a look.