Operators and Operands¶
- Operators are special tokens that represent computations like addition, multiplication and division.
The following are all legal Python expressions whose meaning is more or less clear:
20+32 hour-1 hour*60+minute minute/60 5**2 (5+9)*(15-7)
- The tokens
+
,-
, and*
, and the use of parenthesis for grouping, mean in Python what they mean in mathematics. - The asterisk (
*
) is the token for multiplication, and **
is the token for exponentiation.
- When a variable name appears in the place of an operand, it is replaced with its value before the operation is performed.
Example: so let us convert 645 minutes into hours:
In Python 3, the division operator
/
always yields a floating point result.- The floor division uses the token //.
- if it has to adjust the number it always moves it to the left on the number line.
- So 6 // 4 yields 1, but -6 // 4 yields -2!
Type converter functions¶
- Here we’ll look at three more Python functions,
int
,float
andstr
, which will (attempt to) convert their arguments into typesint
,float
andstr
respectively. - We call these type converter functions.
The int
function can take a floating point number or a string, and turn
it into an int. For floating point numbers, it discards the decimal portion
of the number — a process we call truncation towards zero on
the number line. Let us see this in action:
The type converter float
can turn an integer, a float, or a syntactically legal
string into a float:
The type converter str
turns its argument into a string:
Operations on strings¶
In general, you cannot perform mathematical operations on strings, even if the strings look like numbers "15"+2
is an error
- Interestingly, the
+
operator does work with strings, but for strings, the+
operator represents concatenation. - Concatenation means joining the two operands by linking them end-to-end. For example:
The *
operator also works on strings; it performs repetition. For example,
The modulus operator¶
- The modulus operator works on integers (and integer expressions) and gives the remainder when the first number is divided by the second.
- In Python, the modulus operator is a percent sign (
%
). - It has the same precedence as the multiplication operator.
- You can check whether one number is divisible by another
x % 10
yields the right-most digit ofx
(in base 10).x % 100
yields the last two digits.
It is also extremely useful for doing conversions, say from seconds, to hours, minutes and seconds. So let’s write a program to ask the user to enter some seconds, and we’ll convert them into hours, minutes, and remaining seconds.
1 2 3 4 5 6 7 | total_secs = int(input("How many seconds, in total?"))
hours = total_secs // 3600
secs_still_remaining = total_secs % 3600
minutes = secs_still_remaining // 60
secs_finally_remaining = secs_still_remaining % 60
print("Hrs=", hours, " mins=", minutes, "secs=", secs_finally_remaining)
|