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 cans for the same price as a bottle. To determine which is the better purchase, a program can compute the total volume of the six-pack in 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 = expressionExample:
cansPerPack = 6The 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 + 2is legal in Python. It looks up the current value ofcansPerPack, adds2, and stores the result back intocansPerPack(incrementing its value by2).In algebra, has no solution, but in programming, it is an update operation.
Variable Definition Analysis
Evaluating sequential variable definitions:
cats = 3(Valid: creates variablecatsinitialized to3)dogs = cats + 1(Valid: looks upcatsvalue3, adds1, assigns4todogs)parakeets = parakeets + 1(Invalid ifparakeetshas not been defined previously)10 = hamsters(Invalid: left-hand side must be a variable name, not a numeric literal)goldfish = cats(Valid: assigns the value stored incatstogoldfish)
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 ).
Number Literals Reference
Number | Type | Comment |
|---|---|---|
|
| An integer has no fractional part. |
|
| Integers can be negative. |
|
| Zero is an integer. |
|
| A number with a fractional part has type |
|
| An integer with a fractional part |
|
| Exponential notation: or . Always |
|
| Negative exponent: . Always |
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 like3.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 afloat(taxRate = 5.5), or even astr(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)
Names must start with a letter or an underscore (
_). The remaining characters must be letters, numbers, or underscores.Cannot use symbols such as
?,%,.,/, or spaces inside names.Names are case sensitive (
canVolumeandcanvolumeare different variables).Cannot use Python reserved words (e.g.,
if,class).
Naming Conventions (Good Practice)
Use descriptive names (e.g.,
cansPerPackinstead ofcpp).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 afloat)Exponentiation:
**(evaluated right-to-left)Floor Division:
//(truncates fractional part for positive integers)Modulus (Remainder):
%(yields remainder of division)
Operator Precedence and Rules
Exponentiation (
**) - evaluated right-to-left.Multiplication (
*), Division (/), Floor Division (//), Modulus (%) - evaluated left-to-right.Addition (
+), Subtraction (-) - evaluated left-to-right.Mixing
intandfloatresults in afloat(e.g.,7 + 4.0yields11.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)orround(x, n): Rounds to whole number orndecimal places.max(x1, x2, ...)/min(x1, x2, ...): Returns maximum / minimum value.
mathModule Functions (requiresfrom math import ...):sqrt(x): Square root ().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 * 100resulting in434.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, cosImport all:
from math import *Module prefix import:
import math(requiresmath.sqrt(x))
Compound Assignment Operators
total += cansis shortcut fortotal = total + canscount += 1incrementscountby1
Line Joining
Expressions inside parentheses can span multiple lines automatically.
Alternatively, use a backslash
\at the end of a line.
Problem Solving Methodology
First Do It By Hand: Work through concrete examples manually before coding.
Formulate Algorithms: Convert hand calculations into generalized algebraic formulas.
Implement and Test: Translate algorithm into Python code using descriptive variable names.