2.1-2.7 zybooks

Overview of Variables and Data Types

Numbers and character strings are fundamental data types used in Python programs to store, manipulate, and display information.

  • Chapter Goals:

    • Define and use variables and constants.

    • Understand the properties and limitations of integers and floating-point numbers.

    • Appreciate the importance of comments and good code layout.

    • Write arithmetic expressions and assignment statements.

    • Create programs that read and process inputs, and display results.

    • Learn how to use Python strings.

    • Create simple graphics programs using basic shapes and text.

Defining Variables and Assignment

When a program carries out computations, values must be stored in memory for later use. A variable is a storage location in a computer program that has a name and holds a value.

  • Definition of Variable: A symbol in a program that identifies a storage location that can hold different values.

  • Parking Space Metaphor: A variable is similar to a parking space in a garage. The parking space has an identifier (e.g., "J 053") and holds a vehicle. A variable has a name (e.g., cansPerPack) and holds a value (e.g., 6).

The Soft Drink Problem Scenario

A store offers a six-pack of 12 fl oz12\,\text{fl oz} cans for the same price as a 2 liter2\,\text{liter} bottle. To determine which is the better purchase, a program can compute the total volume of the six-pack in liters (12 fl oz≈0.355 liters12\,\text{fl oz} \approx 0.355\,\text{liters}).

Assignment Statements

An assignment statement places a new value into a variable.

  • Definition of Assignment: Placing a new value into a variable.

  • Syntax: variableName = expression

  • Example: cansPerPack = 6

    • The left-hand side consists of a variable.

    • The right-hand side is an expression that yields a value.

    • The first time a variable is assigned a value, it is created and initialized with that value.

    • Subsequent assignments overwrite the previous contents of the variable.

Assignment vs. Algebraic Equality

The = operator in Python represents assignment, not algebraic equality.

  • An assignment statement is an instruction to place a value into a variable location.

  • cansPerPack = cansPerPack + 2 is legal in Python. It looks up the current value of cansPerPack, adds 2, and stores the result back into cansPerPack (incrementing its value by 2).

  • In algebra, x=x+2x = x + 2 has no solution, but in programming, it is an update operation.

Variable Definition Analysis

Evaluating sequential variable definitions:

  1. cats = 3 (Valid: creates variable cats initialized to 3)

  2. dogs = cats + 1 (Valid: looks up cats value 3, adds 1, assigns 4 to dogs)

  3. parakeets = parakeets + 1 (Invalid if parakeets has not been defined previously)

  4. 10 = hamsters (Invalid: left-hand side must be a variable name, not a numeric literal)

  5. goldfish = cats (Valid: assigns the value stored in cats to goldfish)

Data Types and Number Literals

Every value in Python belongs to a specific data type. A value's data type determines how it is represented in computer memory and what operations can be performed on it.

  • Definition of Type: A named set of values and the operations that can be carried out with them.

  • Definition of Primitive Type: A data type provided by the programming language itself.

  • Definition of User-Defined Data Type: A data type defined by the programmer using class definitions.

  • Definition of Number Literal: A constant value explicitly written in a program (e.g., -2, 6.02214115E23).

Primary Numeric Types
  • Integer (int): A whole number without a fractional part (e.g., counting discrete items like soda cans).

  • Floating-Point (float): A number that can have a fractional part (e.g., continuous measurements like 0.355 liters0.355\,\text{liters}).

Number Literals Reference

Number

Type

Comment

6

int

An integer has no fractional part.

-6

int

Integers can be negative.

0

int

Zero is an integer.

0.5

float

A number with a fractional part has type float.

1.0

float

An integer with a fractional part .0 has type float.

1E6

float

Exponential notation: 1×1061 \times 10^6 or 10000001000000. Always float.

2.96E-2

float

Negative exponent: 2.96×10−2=0.02962.96 \times 10^{-2} = 0.0296. Always float.

Common Numeric Format Errors:

  • 100,000 (Error: Do not use commas as separators in Python numbers)

  • 3 1/2 (Error: Do not use fractions; use decimal notation like 3.5)

Dynamic Typing Properties

In Python, data types are associated with the value, not the variable name itself.

  • A variable can store an int (e.g., taxRate = 5), then later store a float (taxRate = 5.5), or even a str (taxRate = "Non-taxable").

  • Best Practice: Keep storing values of the same initial type in a variable to avoid unexpected type errors. Initialize with float (e.g., taxRate = 5.0) if the variable is expected to hold fractional numbers.

Variable Naming Rules and Conventions
Naming Rules (Mandatory)
  1. Names must start with a letter or an underscore (_). The remaining characters must be letters, numbers, or underscores.

  2. Cannot use symbols such as ?, %, ., /, or spaces inside names.

  3. Names are case sensitive (canVolume and canvolume are different variables).

  4. Cannot use Python reserved words (e.g., if, class).

Naming Conventions (Good Practice)
  • Use descriptive names (e.g., cansPerPack instead of cpp).

  • Camel Case: Capitalize word boundaries inside variable names starting with lowercase (e.g., cansPerPack).

  • Constants: Use ALL_CAPS for constant names (e.g., BOTTLE_VOLUME).

  • Class Names: Start with an uppercase letter for user-defined data types.

Constants and Comments
Constants
  • A constant is a variable whose value should not change after initial assignment.

  • Python does not enforce constants strictly; programmers use all uppercase letters by convention (e.g., BOTTLE_VOLUME = 2.0).

  • Using named constants eliminates "magic numbers" and clarifies code intent.

Comments
  • A comment is text for human readers that is ignored by the Python interpreter.

  • Indicated by the # symbol. Everything from # to the end of the line is ignored.

  • Use comments at the top of files to explain program purpose and next to complex calculations.

Common Errors & Programming Tips
  • Undefined Variables: A variable must be defined and initialized before it is used.

  • Magic Numbers: Avoid unexplained numeric literals in expressions; replace them with named constants.

Arithmetic Operations and Expressions

Python supports basic arithmetic operators:

  • Addition: +

  • Subtraction: -

  • Multiplication: *

  • Division: / (always yields a float)

  • Exponentiation: ** (evaluated right-to-left)

  • Floor Division: // (truncates fractional part for positive integers)

  • Modulus (Remainder): % (yields remainder of division)

Operator Precedence and Rules
  1. Exponentiation (**) - evaluated right-to-left.

  2. Multiplication (*), Division (/), Floor Division (//), Modulus (%) - evaluated left-to-right.

  3. Addition (+), Subtraction (-) - evaluated left-to-right.

  4. Mixing int and float results in a float (e.g., 7 + 4.0 yields 11.0).

Mathematical Functions and the math Module

Python provides built-in functions and standard libraries:

  • Built-in Functions:

    • abs(x): Returns absolute value.

    • round(x) or round(x, n): Rounds to whole number or n decimal places.

    • max(x1, x2, ...) / min(x1, x2, ...): Returns maximum / minimum value.

  • math Module Functions (requires from math import ...):

    • sqrt(x): Square root (x\sqrt{x}).

    • trunc(x): Truncates floating-point to integer.

    • sin(x), cos(x), tan(x): Trigonometric functions (in radians).

    • radians(x) / degrees(x): Converts between degrees and radians.

    • log(x) / log(x, base): Natural or base-specific logarithm.

Common Calculation Pitfalls
  • Roundoff Errors: Floating-point binary representation errors (e.g., 4.35 * 100 resulting in 434.99999999999994).

  • Unbalanced Parentheses: Parentheses counts must remain balanced at all points in an expression.

Special Topics and Problem Solving
Alternative Module Imports
  • Multiple imports: from math import sqrt, sin, cos

  • Import all: from math import *

  • Module prefix import: import math (requires math.sqrt(x))

Compound Assignment Operators
  • total += cans is shortcut for total = total + cans

  • count += 1 increments count by 1

Line Joining
  • Expressions inside parentheses can span multiple lines automatically.

  • Alternatively, use a backslash \ at the end of a line.

Problem Solving Methodology
  1. First Do It By Hand: Work through concrete examples manually before coding.

  2. Formulate Algorithms: Convert hand calculations into generalized algebraic formulas.

  3. Implement and Test: Translate algorithm into Python code using descriptive variable names.