02 Variables, Expressions, and Input/Output

A progressive guide to Python variables, expressions, program state, input conversion, and readable output.

Names and data

Programs work by storing information, computing new values, receiving information, and producing results. The central idea is that names, values, and operations work together to describe what a program should do.

A is a name associated with a . For example, a name such as price can refer to the price of an item, while quantity can refer to how many items are being considered. A descriptive name makes the purpose of data easier to understand.

A is the data itself. It may be a number, a string, a Boolean , or another supported kind of object. A name and its are related but different: answer is a name, while 4242 is a that the name might refer to.

A is a that the program intends not to change. Python commonly communicates this intention with uppercase names such as TAX_RATE and MAX_ATTEMPTS, but uppercase spelling is a convention rather than an enforcement mechanism.

A is a written directly in source code. Examples include 00, 3.143.14, the string "hello", True, and None.

Takeaway: Variables provide meaningful names, values provide data, constants communicate intended fixed rules, and literals write data directly in code.

and changing values

gives a a . In Python, = evaluates the on the right and then associates the result with the name on the left. For example, assigning 8080 to score makes score refer to that .

is evaluated in order. If score already refers to 8080, then an update equivalent to score = score + 5 first reads the old , computes 8585, and stores the new . This is why a statement such as x = x + 1 is valid in programming: it means to increase the current of x by 11, not to assert mathematical equality.

Multiple can bind several names at once, as in first, second = 10, 20. The first name receives 1010, and the second receives 2020.

combines an operation with . For instance, count += 2 has the same practical update effect as adding 22 to the current of count and storing the result. Other common forms include -=, *=, /=, and %=.

Keep separate variables when both an original and an updated are needed. Replacing price with a discounted result is appropriate only when the original price is no longer required.

Takeaway: Read from right to left as an evaluation followed by storage, and remember that execution order determines which is available.

Expressions and operators

An is code that produces a . A , a reference, an arithmetic calculation, a comparison, or a function call can serve as an . An statement commonly evaluates an on its right side before storing the result.

Arithmetic operators support calculations. Addition, subtraction, multiplication, division, floor division, remainder, and exponentiation can be written with +, -, *, /, //, %, and **. For example, 7+2=97 + 2 = 9, 7//2=37 \mathbin{//} 2 = 3, and 7 \mathbin{%} 2 = 1. The + operator can also join strings, such as combining a first name, a space, and a last name.

Comparison operators produce Boolean values. They include <, <=, >, >=, ==, and !=. The distinction between = and == is essential: = performs , while == tests whether two values are equal.

Logical operators combine conditions. and is true when both conditions are true, or is true when at least one condition is true, and not reverses a truth . For example, access may require both a valid ticket and sufficient age.

Parentheses make grouping explicit. Multiplication normally occurs before addition, so 2+3∗4=142 + 3 \mathbin{*} 4 = 14, whereas (2+3)∗4=20(2 + 3) \mathbin{*} 4 = 20. A useful order is parentheses, exponentiation, multiplication or division, addition or subtraction, comparisons, and then logical operations.

Operands must be compatible. Adding two numbers is appropriate, but adding a number directly to a string causes a type error. Convert a explicitly when the intended operation requires a different type.

Takeaway: Expressions calculate values, operators determine how values are combined, and parentheses make intent clear.

Following

A program’s is the complete collection of values that matter at a particular moment. State changes as statements execute.

Consider the sequence in which balance begins at 100100, decreases by 2525, and then increases by 1010. After the three statements, its successive values are 100100, 7575, and 8585. The current depends on every earlier that affected it.

A reliable tracing method is:

  1. List the important variables.

  2. Read statements from top to bottom.

  3. Record each ’s after every statement.

  4. Use the recorded current values when evaluating the next .

A should receive a before the program uses it. Using a name too early can cause an error or an unintended result, depending on the language and context.

Takeaway: Execution order matters because each statement reads the current state and may create a new state.

Receiving and converting

is information supplied to a program from outside it. In Python, () reads a line of text and returns a string. Even when a user enters digits, the returned data is text rather than a numeric .

When arithmetic is needed, convert the text explicitly. int(...) produces an integer when the text has the expected integer format, while float(...) produces a floating-point number when the text has the expected format. A conversion such as int("twenty") cannot succeed because the text does not represent an integer in the required form.

A typical data flow is:

  1. Read the first .

  2. Read the second .

  3. Convert the values to suitable types.

  4. Compute an using the converted values.

  5. Store the result in a .

For example, if two inputs represent 22 and 33, concatenating the unconverted strings produces "23", whereas converting them to integers before addition produces 55. Robust programs eventually validate and handle invalid data instead of assuming every response has the expected format.

Takeaway: Treat text received from () as text until an explicit, successful conversion gives it the type needed for the next operation.

Producing clear

is information produced by a program. Python’s print() function normally writes text to the screen, separates multiple arguments with spaces, and ends with a newline.

A program can print separate values, such as an item count and a price, or combine text and values with an . An evaluates expressions inside braces before displaying the resulting text. For example, inserting a calculated area displays the result of multiplying width by height rather than displaying the as unevaluated text.

Formatting controls presentation without changing the underlying . A price such as 12.512.5 can be displayed with two digits after the decimal point, producing a presentation such as $12.50.

A complete small calculation often follows this pattern:

  1. Read an item name.

  2. Convert a price to a floating-point .

  3. Convert a quantity to an integer.

  4. Compute a subtotal with price∗quantity\text{price} \mathbin{*} \text{quantity}.

  5. Compute tax using a named rate.

  6. Add subtotal and tax to obtain the total.

  7. Print each result with readable labels and formatting.

This pattern connects literals, variables, , expressions, , conversion, , and changing . Clear names and explicit parentheses make the data flow easier to verify.

Takeaway: Good presents computed values clearly, while good handling ensures that those values were obtained from appropriately typed data.