Numbers
Working with Numbers in Python
1. Introduction
Discussing integers and floating-point numbers.
2. Recap
Numbers in Python: Integers (whole numbers) and Floats (with decimals).
3. Math Operators
Work as expected.
Combining integers with float results in a float.
4. Understanding Data Types
Use the type() function to determine the type of data.
Example: print(type(1)) outputs integer; print(type(1.1)) outputs float.
5. Conversion Between Data Types
Automatic conversions in arithmetic.
Example: 1 + 1.1 results in 2.1 (a float).
Division always results in a float.
Python's flexibility simplifies data type handling.
6. Converting Integers to Floats
Use the float() function.
Example: float(2) results in 2.0 .
7. Converting Floats to Integers
Use the int() function (truncates decimals).
Example: int(5.9) results in 5 .
Rounding: Use round() to round numbers.
Example: round(5.9) results in 6 .
8. Precision with Floating Point Numbers
Numbers 1
Floating point arithmetic might introduce minor errors.
Example: 1.1 * 3 might not result in an exact 3.3 .
While minor, it's essential to be aware of this behavior.
Prefer integers for precise arithmetic when possible.
Exercises - Data Types & Numbers
Exercise 1: Data Type Identification
Given the following values, identify their data type:
1. "Hello, World!"
2. 12345
3. 98.76
4. True
5. [1, 2, 3, 4, 5]
6. {"name": "John", "age": 30}
Exercise 2: Arithmetic Operations
Perform the following arithmetic operations and identify the result's data type:
1. 7+2.57+2.5
2. 8/28/2
3. 3×4.03×4.0
4. 10−4.110−4.1
Exercise 3: Type Conversion
Convert the following data types:
1. Convert the string "12345" to an integer.
2. Convert the integer 456 to a string.
3. Convert the float 78.9 to an integer.
4. Convert the integer 100 to a float.
Exercise 4: Working with Floats
Numbers 2
1. Multiply 0.1 by 3. What is the result? Is this what you expected?
2. Divide 5 by 2. What type of number is the result?
Exercise 5: Complex Data Type Manipulation
1. Given the list: [1,2,3,4,5], add a floating point number 6.7 to it.
[1,2,3,4,5]
2. Given the dictionary: "name":"Alice","age":25, change the age to a float and
increase it by 0.5.
"����":"�����","���":25
Exercise 6: Rounding Numbers
1. Round the number 7.65 to the nearest whole number.
2. Truncate the number 8.99 to remove its decimal part.
Exercise 7: Boolean Evaluation
Which of the following expressions will evaluate to True ?
1. 5.0 == 5
2. "5" == 5
3. 10.1 + 2.9 == 13
4. 3 * 0.1 == 0.3
Numbers 3