Numbers, strings/shaare/R2PqPQ
Numbers (int and float)
- int: Whole numbers (e.g.,
10,1024). No overflow due to arbitrary precision. - float: Numbers with decimals (e.g.,
3.14159). Uses IEEE 754 representation; small precision differences possible.
import math
print(type(1.0))
print("When comparing floats directly, we may run into precision issues:")
print("0.1 * 3 == 0.3: ", 0.1 * 3 == 0.3)
print("To tackle this, we can use the math.isclose() function:")
print("math.isclose(0.1 * 3, 0.3): ", math.isclose(0.1 * 3, 0.3))
Arithmetic Operations
+,-,*,//true division → float//floor division → integer or float%modulo → remainder**→ power
print(8/2)
print(type(8/2))
print(5/3)
print(8//2)
print(type(8//2))
print(5//3)
print(5//3.0)
print(5%3) # 1 as the result, and 2 remaining
Strings
String Manipulation
- Strings are ordered, immutable sequences of characters.
- Use single or double quotes consistently; triple quotes for multi-line strings or docstrings.
single_line_str = "Double quoted"
single_line_str2 = 'Single quoted'
command_template = """
I will not be indented
I will be indented
"""
print(command_template)
Format Output using f-string
Tip: f-strings allow inline expression evaluation and formatting, making string construction concise and readable.
math_division = 7/2
print(f"Result: {math_division}")
print(f"Result: {7/2}")
Common Operations and Essential String Methods
- Concatenation (
+): Joins strings. - Length (
len()): Gets the number of characters. - Indexing (
[]): Access a character by position (0-based). - Slicing (
[:]): Extract substrings. .lower() / .upper().strip() / .lstrip() / .rstrip().startswith() / .endswith().split() / .join().replace()
course_title = " Python strings "
print(course_title)
print(f"Result of .strip(): {course_title.strip()}")
print(f"Result of .lstrip(): {course_title.lstrip()}")
print(f"Result of .rstrip(): {course_title.rstrip()}")
print(f"Result of .upper(): {course_title.upper()}")
print(f"Result of .lower(): {course_title.lower()}")
filename = "file.yaml"
print(filename.startswith("file"))
print(filename.endswith("yaml"))
path = "/usr/local/bin"
path_parts = path.split("/")
print(f"path parts: {path_parts}")
print(f"joined path paths: {"\\".join(path_parts)}")
print(path + "/python")
print(len(path))
print(path[3])
print(path[3:10])
print(path[3:])
print(path[:10])
String Immutability
Strings are immutable, meaning you cannot change a string in place; operations that seem to modify a string actually create and return a new string object.
course_title = " Python strings "
print(course_title)
print(f"Result of .strip(): {course_title.strip()}")
print(f"Result of .lstrip(): {course_title.lstrip()}")
print(f"Result of .rstrip(): {course_title.rstrip()}")
print(f"Result of .upper(): {course_title.upper()}")
print(f"Result of .lower(): {course_title.lower()}")
print(course_title)
(97)