Let’s try some simple Python commands. Start the interpreter and wait for the primary prompt, >>>. (It shouldn’t take long.)
The interpreter acts as a simple calculator: you can type an expression at it and it will write the value. Expression syntax is straightforward: the operators +, -, * and / work just like in most other languages (for example, Pascal or C); parentheses (()) can be used for grouping. For example:
>>> 4 + 2
6
>>> 100 - 10*6
40
>>> (150 - 5*6) / 4
30.0
>>> 22 / 7 # division returns a floating point value
3.142857142857143
The integer numbers (e.g. 2, 4, 20) have type int, the ones with a fractional part (e.g. 5.0, 1.6) have type float. We will see more about numeric types later in the tutorial.
Division (/) always returns a float. To do floor division and get an integer result (discarding any fractional result) you can use the // operator; to calculate the remainder you can use %:
>>> 22//7 # floor division discards the fractional part
3
>>> 22 % 4 # the % operator returns the remainder of the division
2
>>> 5 * 3 + 2 # result * divisor + remainder
17
With Python, it is possible to use the ** operator to calculate powers [1]:
>>> 5 ** 3 # 5 cube means 5^3
125
>>> 2 ** 8 # 2 to the power of 7
256
The equal sign (=) is used to assign a value to a variable. Afterwards, no result is displayed before the next interactive prompt:
>>> width = 10
>>> height = 15 * 9
>>> width * height
1350
There is full support for floating point; operators with mixed type operands convert the integer operand to floating point:
>>> 4 * 3.14 / 2.5
5.024
>>> 9.0 / 2
4.5
In interactive mode, the last printed expression is assigned to the variable _. This means that when you are using Python as a desk calculator, it is somewhat easier to continue calculations, for example:
>>> tax = 14.5 / 100
>>> price = 200.50
>>> price * tax
29.07249999999999
>>> price + _
229.5725
>>> round(_, 2)
229.57
Advertisement Powered By Google Adsense
python python tutorial learn python learning python python code learning java python language python documentation python tutor python basics python download python online python for dummies how to learn python