Press "Enter" to skip to content

Python Notes 2 : Numbers & Strings

Numbers

  • ‘/’ symbol in python 2 performs a classical division where as in python 3 performs a absolute division
    • 3/2 = 1 (python 2)
    • 3/2 = 1.5 (python 3)
    • To get similar results in python 2, perform the following –
      • 3.0/2 = 1.5 (python 2)
      • 3/2.0 = 1.5 (python 2)
      • float(3)/2 = 1.5 (python 2)
      • import future module
        • from __future__ import division
        • 3/2 = 1.5  (python 2)

Floating point accuracy

Calculation involving floating point numbers behave weird in most of the programming languages. This is typically because of the way a floating number is represented & saved in memory.

A typical example strengthening the above statement would be –

0.1 + 0.2 – 0.3

A typical user would expect an answer of for the above expression. However, if you execute above statement in any of the modern programming day language, it would result in 5.551115123125783e-17.

The reason to this weird answer lies in the Representation error.

Representation error refers to the fact that not all decimal numbers can be exactly converted to binary (base 2) fractions.

For example –

0.1 (base 10) = 0.00011001100110011001100110011001100110011001100110011010…. (base 2)

0.1 (base 10) represents a never ending fraction if converted to base 2. As per standard, system only considers 53 bits of precision for a floating value.

Therefore, whenever any calculations are carried out on such floating decimals, errors are bound to occur for a novice programmer.

Strings

  • Reverse a string ->  s[::-1]
    • s = ‘Hello World’
    • s[::-1]
    • O/P -> ‘dlroW olleH’
  • Strings are immutable in nature -> Once a string is created, the elements within it cannot be changed or replaced
    • s = ‘Hello World’
    • s[0] = ‘x’
      • Error
        • s[0] = ‘X’ ; TypeError: ‘str’ object does not support item assignment

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *