Python Integral Types

| Page Views: 42

Python gives us two integral types: int and bool. These two types are immutable. This is how they are used in Boolean expressions:

  • 0 and False are False.
  • Any other integer and True are True.

Integers

In Python the size of an integer is only limited by the host machine's memory. Integers literals are written using base 10(decimal) by default. However, you can use other notations like Hexadecimal, Octal and Binary.

HEXADECIMAL

>>> 0xBEBEBE
12500670

OCTAL

>>> 0o6752222
1823890

BINARY

>>> 0b010101001100101011001011
5556939

Hexadecimal numbers have a leading 0x, Octal numbers a leading 0o while Binary numbers a leading 0b.

Creating Integer

Integer objects can be created by:

  • Assigning a literal value to an identifier.

    >>> age = 60
    >>> print(age)
    60
    
  • Invoking the relevant data type function and passing the literal value as a parameter:

    >>> age = int(65)
    >>> print(age)
    65
    

If you don't supply the literal value, then a default is assigned to the integer object.

>>> lines = int()
>>> print(lines)
0

What about if I supply floating point number:

>>> num_people = int(20.7)
>>> print(num_people)
20

What about if I supply a value that cannot be converted into an integer. A ValueError exception gets raised:

>>> num_people = int("I don't know")
Traceback (most recent call last):
  File "<input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: "I don't know"

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section.

About Me.

After completing his Software Engineering bachelors program, Oclemy(Clement Ochieng) these days is a man of two lives. At day he works for a startup in Nairobi, Kenya. At night he works tirelessly on building ProgrammingWizards TV, a tv channel for student coders and this website to help share the source code. In between he practices Meditation and Self actualization to help him keep balance. He also likes going for long solo walks to connect more with nature.




Recommendations


What do You Think


Previous Post Next Post