Operators and Operands

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)



(exponentiation)

Example: so let us convert 645 minutes into hours:

(conversion)




(conversion2)

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:




(intconverter)

The type converter float can turn an integer, a float, or a syntactically legal string into a float:




(floatconverter)

The type converter str turns its argument into a string:




(strconverter)

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:



(concat)

The * operator also works on strings; it performs repetition. For example,




(repetition)

The modulus operator




(modulus)

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)
Next Section - Input