float. We will see more about numeric types later in the tutorial.
# this is the first comment
spam = 1 # and this is the second comment
# ... and now a third!
text = "# This is not a comment because it's inside quotes."
>>> 2 + 2
4
>>> 50 - 5*6 20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5 # division always returns a floating point number 1.6
9
Python Tutorial, Release 3.7.0
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 %:
>>> 17 / 3 # classic division returns a float 5.666666666666667
>>>
>>> 17 // 3 # floor division discards the fractional part 5
>>> 17 % 3 # 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 powers1:
The equal sign (=) is used to assign a value to a variable. Afterwards, no result is displayed before the next interactive prompt:
If a variable is not “defined” (assigned a value), trying to use it will give you an error:
There is full support for floating point; operators with mixed type operands convert the integer operand to floating point:
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:
This variable should be treated as read-only by the user. Don’t explicitly assign a value to it — you would create an independent local variable with the same name masking the built-in variable with its magic behavior.
1 Since ** has higher precedence than -, -3**2 will be interpreted as -(3**2) and thus result in -9. To avoid this and get
تعليقات
إرسال تعليق