Learn Python
- Python basic
- Introduction to File Handling
- Basics of List Comprehension
- Introduction to Matplotlib
- Classes and Objects
- Introduction to Functions
- Python Numbers
- Creating Basic Plots
- Opening and closing files
- Function parameters and arguments
- Advanced Techniques
- Attributes and Methods
- Python Strings
- Scope and lifetime of variables
- Advanced Plotting
- Reading from files
- Performance and Limitations
- Encapsulation
- Python List
- Specialized Plots
- Writing to files
- Return statement and output
- Inheritance
- Python Tuple
- Advanced Customization
- Working with different file formats
- Lambda Functions
- Polymorphism
- Practical Applications
- Special Methods
Python Numbers
Working with Integers
In Python, integers (represented by the int data type) are whole numbers, including positive, negative, and zero. Unlike some other programming languages, integers in Python have unlimited precision, meaning they can theoretically store numbers as large as your computer's memory allows.
1. Representing integers
You can create integers simply by assigning whole numbers to variables:
age = 30 count = -10 binary_number = 0
Integers can also be represented in different bases (binary, octal, hexadecimal) for specific use cases. Python allows you to specify the base using an underscore prefix followed by the base indicator (e.g., 0b1101 for binary, 0o123 for octal, 0xCAFE for hexadecimal).
2. Operations on integers
Python supports basic arithmetic operations like addition (+), subtraction (-), multiplication (*), and integer division (//). These operations behave as you would expect for whole numbers.
There's also the modulo operator (%) that gives you the remainder after a division. For example, 10 % 3 would be 1 (remainder after dividing 10 by 3).
3. Things to keep in mind
When dividing integers by integers, Python performs integer division. This means the result will always be an integer, even if the mathematical answer is a fraction. The fractional part is truncated. To get a floating-point result, you can convert one of the operands to a float before division:
result1 = 10 // 3 # result1 will be 3 (integer division) result2 = 10.0 / 3 # result2 will be 3.3333... (float division)
Integers can't directly represent decimal places. If you need to store numbers with decimals, you should use the float data type.
It's time to take a quiz!
Test your knowledge and see what you've just learned.
Which of the following is a valid representation of an integer in Python?
Dall of the above
A0b1101
B0o123
C0xCAFE
Check Answer
What is the result of the operation 10 % 3?
A3
B1
C10
D0
Check Answer
What will be the result of 10 // 3 in Python?
D2.5
A3
B3.0
C4
Check Answer
Which data type should be used to store numbers with decimal places in Python?
Aint
Bfloat
Ccomplex
Dstr
Check Answer
How would you represent the binary number 1011 in Python?
C0b11
Dbinary(1011)
A0b1011
B1011b
Check Answer