This lesson on Python Basic Datatypes is hands-on and example-driven. You will identify and manipulate Python's primary primitive data types—integers, floats, booleans, and strings. You will verify types at runtime, perform explicit type conversions, and handle string formatting and quotation escaping correctly in your scripts.
What You'll Be Able To Do
- Identify and verify runtime data types using the type() function
- Cast variables between numeric, float, and string representations using built-in constructors
- Construct boolean expressions using strict title-cased True and False literals
- Format strings containing nested quotation marks using alternating delimiters or backslash escape characters
- Concatenate strings and numeric variables without triggering runtime type errors
Detailed Concept Walkthrough
1. Numeric Types and Type Inspection
Python distinguishes between whole numbers and real numbers with fractional components using distinct numeric datatypes. The type() function queries the runtime type assigned to any object or variable dynamically.
- Mechanism: Integers (int) represent positive or negative whole numbers without decimal points, whereas floating-point numbers (float) represent real numbers containing decimal points.
- Dynamic Typing: Python automatically infers the datatype upon variable assignment, eliminating the need for explicit datatype declarations in your source code.
- Inspection Mechanics: Passing either a variable name or a literal directly into type() evaluates and returns the object's class constructor name, such as <class 'int'> or <class 'float'>.
# Assigning numeric values
x1 = 5
x2 = 4.75
# Inspecting types dynamically
print(type(x1)) # <class 'int'>
print(type(-6)) # <class 'int'>
print(type(x2)) # <class 'float'>
Key Takeaway: Python automatically infers numeric types as int or float based on whether a decimal point is present.
2. Explicit Type Casting
Type casting converts an existing value from one datatype representation into another using built-in constructor functions. This allows data of differing types to be combined in expressions.
- Numeric Truncation: Passing a floating-point number into int() strips the decimal portion completely without rounding.
- Float Promotion: Passing an integer into float() appends a fractional component (.0) to represent the value in floating-point format.
- String Conversion: The str() function serializes numeric or boolean values into text format, enabling concatenation with other string literals.
# Casting between numeric types
converted_int = int(4.75) # Truncates to 4
converted_float = float(5) # Promotes to 5.0
# Converting an integer to string for concatenation
y = 10
message = str(y) + " dollars"
print(message) # '10 dollars'
Key Takeaway: Use int(), float(), and str() to explicitly cast incompatible types before combining them in expressions.
3. Boolean Datatype Semantics
The boolean type represents binary truth values corresponding directly to computational binary logic (1 and 0, on and off).
- Syntax Rule: Python booleans must strictly be written with initial capital letters as True or False.
- Namespace Distinction: Writing true or false in lowercase causes Python to interpret them as unassigned variable identifiers, raising a NameError.
- Type Mapping: The type() function identifies boolean literals and variables containing them as bool.
# Assigning boolean values
x3 = True
is_valid = False
# Verifying boolean type
print(type(x3)) # <class 'bool'>
print(type(is_valid)) # <class 'bool'>
Key Takeaway: Boolean literals require strict capitalization (True, False) to avoid variable lookup errors.
4. String Syntax, Escaping, and Printing
Strings are sequences of text characters delimited by single or double quotes, requiring escape strategies when literal quotation characters occur inside the text.
- Delimiter Equivalence: Single quotes ('...') and double quotes ("...") are functionally identical for defining strings.
- Quote Alternation: Enclose the string in double quotes if it contains an apostrophe, or single quotes if it contains double quotes, preventing premature string termination.
- Escape Characters: Prefixing an internal quote with a backslash (') instructs the parser to treat the character as literal text rather than a syntax delimiter.
- Display Behavior: Calling print() strips the enclosing quotes from the terminal display, while comma-separated arguments are separated by spaces automatically.
# Quote alternating strategy
phrase_1 = "I'm fine"
phrase_2 = 'Press "enter"'
# Backslash escaping strategy
phrase_3 = 'I\'m fine'
# Printing multiple values
print("red", "car") # Prints: red car
print(3, 5) # Prints: 3 5
Key Takeaway: Prevent syntax errors in strings with nested quotes by alternating quote styles or escaping internal quotes with a backslash.
Topics Covered in Python Basic Datatypes
- Integer Datatype and type() (0:00 - 0:45) — Introduces integer definitions and demonstrates type verification using the type() function.
- Floats and Casting (0:45 - 1:20) — Explains floating-point numbers and demonstrates numeric type casting with int() and float().
- Boolean Datatypes (1:20 - 1:55) — Details boolean truth logic and emphasizes mandatory capitalization of True and False.
- Strings and str() Casting (1:55 - 2:40) — Covers string definition, name resolution errors, and resolving concatenation errors using str().
- Quotation Escaping (2:40 - 3:25) — Demonstrates quote alternation and backslash escaping for strings containing internal quotation marks.
- Print Formatting Techniques (3:25 - 4:00) — Illustrates multi-argument printing with commas and contrasts print output with tuple display.
Python Cheat Sheet
-
type(object)— Returns datatype class of passed variable or literaltype(4.75) -
int(x)— Converts value to integer, truncating decimal portionint(4.75) -
float(x)— Converts value to float, adding decimal pointfloat(5) -
str(x)— Converts value into its string text representationstr(10) -
True / False— Capitalized literals defining boolean truth valuesx3 = True -
\' or \"— Escapes quotation mark inside matching string delimiters'I\'m fine' -
print(val1, val2)— Outputs values separated by spaces without quotesprint("red", "car")
Comparison Table
| Datatype | Type Name | Defining Characteristic | Example Value |
|---|---|---|---|
| Integer | int | Whole number without decimals | -6 |
| Float | float | Real number with decimal point | 4.75 |
| Boolean | bool | Binary truth value (capitalized) | True |
| String | str | Text sequence in matching quotes | "George" |
Common Pitfalls
- Mistake: Writing boolean values in lowercase such as true or false. Avoid: Always capitalize the first letter as True or False.
- Mistake: Concatenating an integer directly with a string using the plus operator. Avoid: Wrap the integer in str() before adding to strings.
- Mistake: Using unescaped matching quotation marks inside a string. Avoid: Alternate outer quote types or escape inner quotes with a backslash.
FAQs
- Why does int(4.75) return 4 instead of rounding up to 5? The int() function truncates the fractional portion entirely rather than performing mathematical rounding.
- Why does typing George without quotes cause an error? Python interprets unquoted words as variable identifiers and throws an error if no variable with that name exists.
- What happens when listing comma-separated items without print() in an interactive session? Python returns the values grouped inside parentheses as a formatted tuple rather than printing space-separated plain text.