Python Language FundamentalsIntroductionPython is a general-purpose programming language widely used in business analytics because it combines readable syntax with powerful tools for data manipulation, visualization, statistics, and machine learning. Before analysts can work effectively with libraries such as pandas, NumPy, or scikit-learn, they must understand Python’s core language features. These features determine how values are represented, how calculations are performed, how decisions are expressed, and how information moves into and out of a program. This chapter develops the foundations required to write small Python programs in notebooks and scripts. The emphasis is not merely on memorizing syntax. A business analyst must understand the relationship between data, types, operations, expressions, and program output. A calculation that produces a plausible number can still be wrong if the underlying type, unit, rounding rule, or operator has been misunderstood. Learning ObjectivesBy the end of this chapter, you should be able to: - recognize basic Python syntax and indentation rules;
- create, name, and update variables;
- distinguish common scalar data types;
- use arithmetic, comparison, logical, assignment, and membership operators;
- construct and evaluate expressions;
- accept input and produce formatted output;
- convert values safely between compatible types;
- apply common built-in functions;
- identify common errors and improve code quality in notebooks and scripts;
- explain how fundamental Python skills support business analytics.
1. Python as an Analytical LanguagePython programs are sequences of statements. A statement instructs the interpreter to perform an action, such as assigning a value, displaying a result, or importing a module. Python is interpreted: code is generally executed by an interpreter rather than compiled into a standalone machine-code program before every run. In practice, modern Python implementations perform internal compilation steps, but the important learner-level distinction is that Python provides immediate interactive feedback. A notebook organizes code into executable cells, together with text, tables, and visualizations. It is useful for exploration and explanation. A script is a saved Python file, normally with a .py extension, that can be executed repeatedly. Notebooks support experimentation; scripts support reproducibility, automation, and deployment. Python is case-sensitive. The names sales, Sales, and SALES refer to different identifiers. Comments begin with # and are ignored by the interpreter: # Calculate the average transaction value
average_value = total_sales / transaction_count Good comments explain purpose or reasoning, not obvious syntax. For example, # Apply the 10% discount agreed in the promotion is more useful than # Divide by 10. Indentation and code blocksPython uses indentation to identify blocks of code. It does not use braces for this purpose. Consistent indentation is therefore part of the language syntax. Four spaces are the conventional indentation level. revenue = 125000
if revenue > 100000:
print("Target achieved")The indented statement belongs to the if block. Inconsistent indentation can produce an IndentationError or, more seriously, cause a statement to belong to the wrong block. 2. Variables and NamesA variable is a name bound to an object. The assignment operator = associates a name with a value: units_sold = 240
unit_price = 19.50
product_name = "Notebook" In the statement units_sold = 240, the number 240 is an object and units_sold is a name referring to it. Assignment is not a mathematical claim that two quantities are permanently equal. It is an instruction to bind or rebind a name. Python permits reassignment: units_sold = 240
units_sold = 275 After the second statement, the value associated with units_sold is 275. Naming rules and conventionsAn identifier may contain letters, digits, and underscores, but it cannot begin with a digit. It cannot contain spaces, and it must not be a Python keyword such as if, class, or return. Recommended conventions include: - use descriptive names such as
monthly_revenue rather than mr; - use lowercase words separated by underscores for ordinary variables;
- avoid names that shadow built-in functions, such as
sum, list, or input; - use constants such as tax rates consistently, often with uppercase names;
- preserve units in names when confusion is possible, for example
distance_km or price_usd.
Multiple assignment is possible: quantity, price = 8, 12.50 The statement assigns 8 to quantity and 12.50 to price. A useful related operation is swapping: quantity, price = price, quantity Although this is concise, it should be used only when the meaning remains clear. 3. Scalar Data TypesA scalar is a single value rather than a collection of values. The most important built-in scalar types for introductory analytics are int, float, complex, bool, str, and NoneType. | Type | Meaning | Example |
|---|
int | Integer with no fractional component | 42 | float | Floating-point real number | 19.75 | complex | Number with real and imaginary parts | 2 + 3j | bool | Logical truth value | True | str | Sequence of text characters | "Retail" | NoneType | Absence of a value | None |
The type() function reports an object’s type: amount = 1250.0
print(type(amount)) # <class 'float'> Integers and floating-point numbersIntegers are suitable for counts, such as the number of customers. Floating-point numbers represent approximate real values, such as prices, rates, and measurements. A decimal-looking value is normally a float: customers = 125 # int
conversion_rate = 0.084 # float Floating-point representation is binary and finite. Consequently, some decimal fractions cannot be represented exactly. For example: print(0.1 + 0.2) The displayed result may be 0.30000000000000004. This is not a failure of arithmetic; it reflects representation and rounding. For ordinary analytical display, use formatting or round(). For applications requiring exact decimal currency calculations, consider the decimal module and an explicit rounding policy. Boolean valuesA Boolean value is either True or False. Boolean expressions arise from comparisons: profit = 4200
is_profitable = profit > 0 Python also evaluates some values as false in conditions. These include False, None, numeric zero, and empty strings or collections. This behavior is called truth-value testing. It is convenient, but analysts should ensure that “empty” and “zero” have the intended business meaning. StringsStrings represent text and may be enclosed in single or double quotation marks: region = "North"
status = 'Approved' Strings can be concatenated with + and repeated with *: label = "Region: " + region
separator = "-" * 20 Formatted string literals, or f-strings, are generally clearer: revenue = 125000
print(f"Revenue: ${revenue:,.2f}")Here :,.2f means use thousands separators and display two digits after the decimal point. Formatting changes presentation; it does not change the underlying numeric value. Strings are indexed from zero: code = "AB-204"
print(code[0]) # A
print(code[-1]) # 4 A slice uses the half-open interval [start:stop], including start but excluding stop: print(code[0:2]) # AB The special value NoneNone represents the absence of a value. It is not the same as zero, an empty string, or False:
manager = None
if manager is None:
print("Manager has not been assigned")Use is None rather than == None as the standard identity test. 4. Operators and ExpressionsAn expression combines values, names, operators, and function calls to produce a result. For example, quantity * unit_price is an expression. Arithmetic operators| Operator | Meaning | Example | Result |
|---|
+ | Addition | 7 + 3 | 10 | - | Subtraction | 7 - 3 | 4 | * | Multiplication | 7 * 3 | 21 | / | True division | 7 / 3 | 2.333... | // | Floor division | 7 // 3 | 2 | % | Remainder | 7 % 3 | 1 | ** | Exponentiation | 2 ** 3 | 8 |
True division with / returns a floating-point result, even when both operands are integers. Floor division returns the floor of the quotient, which means the greatest integer less than or equal to the mathematical quotient. For positive values, it resembles truncation; for negative values, the distinction matters. The remainder operator is useful for testing divisibility or identifying cycles: if customer_id % 2 == 0:
segment = "Even ID"Operator precedencePython evaluates expressions according to precedence. Exponentiation is performed before multiplication and division, which are performed before addition and subtraction. Parentheses should be used when they improve clarity or change the intended order. result_1 = 10 + 2 * 3 # 16
result_2 = (10 + 2) * 3 # 36 Do not rely on memorized precedence when a business rule is important. Parentheses make the rule visible. Comparison operatorsComparison operators produce Boolean values: revenue >= target
cost != budget
region == "North" The operators are ==, !=, <, <=, >, and >=. The single equals sign assigns a value; the double equals sign tests equality. Confusing them is a common error. Python supports chained comparisons: 0 <= discount_rate <= 1 This is equivalent to testing both conditions, with the middle expression evaluated appropriately. It is useful when validating rates or ranges. Logical operatorsand requires both operands to be true, or requires at least one, and not reverses truth value:
eligible = age >= 18 and account_active
priority = high_value or overdue
not_completed = not completed Python uses short-circuit evaluation. In A and B, if A is false, Python does not need to evaluate B. In A or B, if A is true, B may not be evaluated. This can improve efficiency, but expressions should remain readable. Membership and identityThe in operator tests membership: "North" in ["North", "South"] The is operator tests object identity, not ordinary value equality. Use is primarily for singleton objects such as None; use == to compare values. Assignment operatorsAugmented assignment updates a variable: sales = 1000
sales += 250
sales *= 1.10 The second statement is conceptually equivalent to sales = sales + 250. Such operators are convenient, but the changing unit and meaning of a variable should remain clear. 5. Input, Output, and Type ConversionThe print() function displays values. It accepts multiple arguments and supports separators and ending characters: print("North", 125000, sep=" | ")The input() function reads text from a user and always returns a string: quantity_text = input("Enter quantity: ")
quantity = int(quantity_text)A common mistake is assuming that input such as "25" is already numeric. It is text until explicitly converted. Conversion functionsCommon conversions include: int("25")
float("19.95")
str(125)
bool(1)Conversion can fail. For example, int("twenty") raises ValueError, and int("12.5") also fails because the text is not an integer literal. A robust script validates input and handles expected errors: try:
quantity = int(input("Quantity: "))
if quantity < 0:
print("Quantity cannot be negative")
except ValueError:
print("Enter a whole number")Conversion is not merely a technical step. It expresses an assumption about the data. Converting a decimal quantity to int may discard information if done deliberately with int(12.9), which returns 12. It does not perform conventional rounding. Use round() when the business rule requires rounding, and document the rule. 6. Common Built-in FunctionsPython provides built-in functions that do not require an import. Important examples include: | Function | Purpose | Example |
|---|
abs(x) | Absolute value | abs(-8) → 8 | round(x, n) | Round for presentation or specified precision | round(3.14159, 2) → 3.14 | min(...) | Smallest value | min(4, 7, 2) → 2 | max(...) | Largest value | max(4, 7, 2) → 7 | sum(iterable) | Sum numeric items | sum([4, 7, 2]) → 13 | len(x) | Number of items or characters | len("ABC") → 3 | type(x) | Type of an object | type(4) | isinstance(x, T) | Tests whether an object has a type | isinstance(4, int) | sorted(x) | Returns a sorted version | sorted([3, 1]) → [1, 3] |
The built-in round() uses Python’s rounding behavior, including ties-to-even in relevant cases. Therefore, financial or regulatory applications should define their rounding requirements explicitly rather than assuming that every halfway value rounds upward. For a list of revenue values, the arithmetic mean can be calculated as: mean = (x₁ + x₂ + ⋯ + xₙ) ÷ n where x₁, …, xₙ are the observations and n is the number of observations, assuming n > 0. In Python: revenues = [1200, 1500, 1300]
mean_revenue = sum(revenues) / len(revenues) The result is 1333.3333333333333. If the list is empty, division by zero occurs, so production code should define how missing observations are treated. 7. Worked Example: A Sales-Performance CalculationSuppose a representative records 48 units sold at a price of $37.50 each. The business offers a 10% discount, and shipping revenue of $60 is added. The calculation is: units = 48
unit_price = 37.50
discount_rate = 0.10
shipping = 60.00
gross_sales = units * unit_price
discount = gross_sales * discount_rate
net_sales = gross_sales - discount + shipping
print(f"Gross sales: ${gross_sales:,.2f}")
print(f"Discount: ${discount:,.2f}")
print(f"Net sales: ${net_sales:,.2f}")The arithmetic is: - Gross sales = 48 × $37.50 = $1,800.00.
- Discount = 10% × $1,800.00 = $180.00.
- Net sales = $1,800.00 − $180.00 + $60.00 = $1,680.00.
The code separates intermediate values rather than placing the entire calculation in one expression. This makes review, testing, and later modification easier. It also makes the units and business meaning visible. 8. Illustrative Case: Retail Promotion ValidationBackgroundA fictional online retailer wants a small Python script to validate a promotional order before it enters the sales system. The promotion applies a 15% discount to orders of at least $100 before shipping. Orders must have a positive quantity and a nonnegative shipping charge. ProblemThe analyst must calculate the pre-discount subtotal, determine eligibility, apply the discount when appropriate, and display a clear total. The script should reject invalid numerical input. Approach and solutiontry:
quantity = int(input("Units: "))
unit_price = float(input("Unit price: $"))
shipping = float(input("Shipping: $"))
if quantity <= 0 or unit_price < 0 or shipping < 0:
print("Invalid order values")
else:
subtotal = quantity * unit_price
eligible = subtotal >= 100
discount_rate = 0.15 if eligible else 0.0
discount = subtotal * discount_rate
total = subtotal - discount + shipping
print(f"Subtotal: ${subtotal:,.2f}")
print(f"Discount: ${discount:,.2f}")
print(f"Total: ${total:,.2f}")
except ValueError:
print("Quantity must be a whole number and prices must be numeric.")For an order of 4 units at $30 each and $8 shipping, the subtotal is $120.00, the discount is $18.00, and the total is $110.00. The conditional expression value_if_true if condition else value_if_false provides a compact assignment, but it should be used only when the condition remains easy to read. Outcome and learning pointsThe case illustrates several foundational ideas: input arrives as text, conversion makes numerical operations possible, validation protects business rules, Boolean expressions determine eligibility, and formatted output communicates results. In a production system, additional controls would be required, including currency precision, tax rules, authentication, logging, and protection against malformed or malicious input. 9. Notebooks, Scripts, and ReproducibilityIn a notebook, cells can be executed out of order. This creates hidden state: a variable may exist because an earlier cell was run, even though the visible sequence does not show that dependency. Analysts should periodically restart the kernel and run all cells from top to bottom. Scripts normally execute in a defined order. A good script uses a clear entry point and avoids accidental execution during import: def main():
print("Analysis started")
if __name__ == "__main__":
main()Although functions are studied more fully later, this pattern supports reuse and testing. Both notebooks and scripts should use meaningful names, avoid unnecessary repeated calculations, preserve input assumptions, and record versions or sources when the analysis informs a business decision. 10. Errors, Testing, and Professional PracticeThree broad error categories are important: - Syntax errors occur when code violates Python grammar, such as a missing colon.
- Runtime errors occur while valid-looking code executes, such as division by zero or invalid conversion.
- Logical errors produce an incorrect result without necessarily raising an error, such as applying a discount to shipping when the policy excludes it.
Analytical work is especially vulnerable to logical errors. Test boundary cases: zero quantity, exactly $100, a value just below $100, negative input, empty text, and unusually large values. Compare outputs with an independent hand calculation or spreadsheet when practical. Security and governance also matter. Do not execute unknown code copied from the internet, expose confidential customer information in notebook outputs, or embed passwords and API keys in scripts. Use approved storage and access controls for sensitive data. A technically correct calculation can still violate privacy, contractual, or organizational requirements. 11. Best Practices and LimitationsEffective foundational Python practice includes: - make units and assumptions explicit;
- prefer descriptive names over clever abbreviations;
- use parentheses to clarify business logic;
- validate external input;
- avoid using floating-point values blindly for exact currency requirements;
- distinguish missing values from zero;
- format results for readers but retain raw values for computation;
- test boundary conditions and restart notebooks to verify reproducibility;
- separate calculation from presentation when code becomes complex.
Python’s built-in types are powerful but limited. Scalar values do not by themselves provide data-quality rules, database constraints, audit trails, or domain-specific currency behavior. Larger analytical tasks require collections, functions, modules, and specialized libraries. Nevertheless, errors in advanced analytics often originate in basic operations performed incorrectly, making these fundamentals essential. Chapter SummaryPython fundamentals provide the base for reliable business analytics. Python statements are organized through syntax and indentation, while variables bind descriptive names to objects. Scalar types—including integers, floating-point numbers, Booleans, strings, and None—determine what operations are valid and how values behave. Operators construct expressions for arithmetic, comparison, logic, assignment, membership, and identity. Input normally arrives as text and must be converted before numerical processing. Output can be made understandable through print() and f-string formatting. Built-in functions such as sum(), len(), min(), max(), round(), and isinstance() support common tasks. Professional analysts must also validate input, test boundary cases, recognize floating-point and rounding limitations, protect sensitive information, and distinguish logical errors from syntax or runtime errors. These practices make notebooks and scripts more accurate, reproducible, and useful for business decisions. Key TermsVariable: A name bound to a value or object. Assignment: The operation of binding a name to an object using =. Identifier: A valid name used for a variable, function, or other Python object. Statement: An instruction that Python executes. Expression: A combination of values, names, operators, and calls that produces a result. Scalar: A single value rather than a collection. Integer: A whole-number value represented by type int. Floating-point number: An approximate real-number value represented by type float. Boolean: A truth value, either True or False. String: Text represented by type str. None: A special value representing absence of a value.
Operator: A symbol or keyword that performs an operation. Type conversion: Transforming a value from one data type to another. Indentation: Leading whitespace used to define Python code blocks. Notebook: An interactive document containing executable code cells and explanatory material. Script: A saved Python program, commonly stored in a .py file. Short-circuit evaluation: Stopping a logical expression when its result is already determined. Truth-value testing: Evaluating an object as true or false in a condition. Floating-point representation: The finite binary representation used for many decimal-looking numbers. Reproducibility: The ability to obtain the same analytical result by following the same documented process. Review QuestionsShort Answer Questions- What is the difference between assignment with
= and equality testing with ==? - Why does
input() usually require type conversion before arithmetic is performed? - Distinguish a floating-point value from an integer value.
- What does
None represent, and how should it normally be tested? - What is the purpose of indentation in Python?
Long Answer Questions- Explain Python’s principal scalar data types and give a business-analytics example for each.
- Describe arithmetic, comparison, and logical operators, including situations in which each category is useful.
- Explain floating-point representation and discuss why exact currency requirements may need special handling.
- Compare the advantages and risks of using notebooks and scripts for business analysis.
- Describe three categories of programming errors and explain why logical errors may be especially difficult to detect.
Analytical / Application Questions- Design a Python solution that accepts quantity, unit price, and tax rate, validates that each is sensible, and calculates the final amount. State your assumptions about tax and rounding.
- A business rule gives a 20% discount for orders with a subtotal of at least $250, excluding shipping. Write the expressions needed to calculate eligibility, discount, and final total, and test the boundary cases of $249.99 and $250.00.
- A notebook produces a different result when cells are run in a different order. Analyze the likely cause and propose a procedure for making the analysis reproducible.
Multiple Choice Questions with AnswersQuestion 1Which statement correctly tests whether the variable revenue is equal to 1000? A. revenue = 1000 B. revenue == 1000 C. revenue := 1000 D. revenue equals 1000 Correct Answer: B. revenue == 1000 Question 2What is the result of 7 // 3 in Python? A. 2 B. 2.3333333333333335 C. 1 D. 3 Correct Answer: A. 2 Question 3What type does input() return before conversion? A. int B. float C. str D. bool Correct Answer: C. str Question 4Which expression correctly checks that discount_rate lies between 0 and 1 inclusive? A. discount_rate > 0 or discount_rate < 1 B. 0 <= discount_rate <= 1 C. discount_rate = 0..1 D. discount_rate in 0, 1 Correct Answer: B. 0 <= discount_rate <= 1 Question 5What is the result of len("North")? A. 4 B. 5 C. 6 D. The string's memory size Correct Answer: B. 5 Question 6Which value represents the absence of a value in Python? A. 0 B. False C. None D. "" Correct Answer: C. None Question 7What does int("12.5") do? A. Returns 12.5 as an integer B. Rounds and returns 13 C. Raises a ValueError D. Returns the string unchanged Correct Answer: C. Raises a ValueError Question 8If quantity = 48 and unit_price = 37.50, what is quantity * unit_price? A. $1,580.00 B. $1,680.00 C. $1,800.00 D. $1,875.00 Correct Answer: C. $1,800.00 Question 9Which operator tests whether a value occurs in a collection or sequence? A. is B. in C. == D. contains Correct Answer: B. in Question 10Which practice best reduces hidden-state problems in a notebook? A. Run cells in any order and trust displayed results B. Restart the kernel and run all cells from top to bottom C. Convert every value to a string D. Avoid comments and variable names Correct Answer: B. Restart the kernel and run all cells from top to bottom
|