Elementary Programming in Python Study Guide
Introduction and Motivations for Elementary Programming
Background: Building on Chapter 1 (which focused on setting up and running initial programs), Chapter 2 shifts toward solving practical problems programmatically.
Core Learning Objectives: Understanding basic Python data types, variables, constants, operators, expressions, and input/output (I/O) mechanics.
Program Development Methodology:
Phase 1: Problem-solving: Designing an algorithm before writing code.
Phase 2: Implementation: Translating the algorithm into Python source code.
Writing a Simple Program: Computing the Area of a Circle
Problem: Calculate the area of a circle using the formula area = radius \times radius \times ̀̀\pì̀.
Algorithm (Phase 1):
Obtain the radius of the circle.
Compute the area using the formula .
Display the result to the console.
Implementation (Phase 2):
radius = 20(Step 1: Assign value).area = radius * radius * 3.14159(Step 2: Compute).print("The area for the circle of radius ", radius, " is ", area)(Step 3: Display results).
Concept - Variable: A name that references a value stored in the computer's memory. It is recommended to use descriptive names like
areaorradiusrather than arbitrary letters likexory.Tracing a Program: A method of reviewing a program by tracking the values in memory for variables as each line executes.
Line 2:
radiusis 20.Line 5:
areabecomes 1256.636.
The
printStatement: Can display multiple items simultaneously using the syntaxprint(item1, item2, ..., itemk). Numbers are automatically converted to strings for display.
Python Data Types and Identification
Definitions:
Data Type: Specifies the type of value a variable holds, such as integers or text.
Literal: A constant value that appears directly in a program (e.g.,
5,5.0).
Built-in Python Data Types:
Integers (
int): Represents whole numbers (e.g.,25).Real numbers (
float): Numbers with a fractional part (e.g.,25.8). A number with a decimal point is a float even if the decimal part is zero (1.0).String: Text characters enclosed in single or double quotes (e.g.,
"Ahmad",'Python').Boolean: Logical values
TrueorFalse.
Dynamic Typing: In Python, you do not need to define the type of a variable before use; the interpreter figures out the type based on the value assigned.
Reading Input from the Console
The
input()Function: Used to prompt the user to enter a value. Syntax:variable = input("Enter a value: ").String Input Caveat: The
input()function always returns the value as a string. Adding strings results in concatenation; adding a string to a number results in aTypeError.The
eval()Function: Evaluates a string and converts it to a numeric value.eval("34.5")returns34.5(float).eval("3 + 4")returns7(integer).
Reading a Number from User:
x = eval(input("Enter x: ")).IPO Model: Most simple programs follow the Input, Process, Output structure.
Line Continuation:
Implicit: Statements inside parentheses can span multiple lines.
Explicit: Use the backslash
\as a line continuation symbol to manually split a long statement.
Identifiers and Naming Rules
Identifier Definition: Names that identify elements like variables and functions.
Naming Rules:
Must consist only of letters, digits, and underscores (
_).Must start with a letter or underscore; cannot start with a digit.
Cannot be a Python Keyword (reserved word).
Can be any length.
Keywords Examples:
import,if,in,elif,False,True.Case Sensitivity:
area,Area, andAREAare three distinct identifiers.
Variables, Assignment Statements, and Expressions
Assignment Operator: The equal sign (
=) is used to assign values to variables.Syntax:
variable = expression.Expressions: A computation involving values, variables, and operators that evaluate to a single value.
Scope: The part of the program where a variable can be referenced. A variable must be created and assigned a value before it can be used in an expression.
Multiple Assignment:
i = j = k = 1sets all three variables to 1.
Simultaneous Assignments
Syntax:
var1, var2, ..., varn = exp1, exp2, ..., expn.Swapping Values: Python allows values to be swapped efficiently without a temporary variable using
x, y = y, x.Multiple Input: Used to obtain several values in one line:
x1, y1 = eval(input("Enter two values separated by comma: ")).
Named Constants and Naming Conventions
Constant: An identifier representing a permanent value that does not change during execution.
Python Syntax: There is no specific keyword for constants; they are variables named using ALL_UPPERCASE letters (e.g.,
PI = 3.14159).Naming Styles:
Variables/Functions: Use lowercase. For multiple words, use
camelCase(e.g.,computeArea) or underscores (e.g.,compute_area).Constants: Uppercase with underscores (e.g.,
MAX_VALUE).
Numeric Operators and Precedence
Basic Operators:
Addition:
+Subtraction:
-Multiplication:
*Float Division:
/(e.g.,4 / 2is2.0)Integer Division:
//(truncates fractional part; e.g.,5 // 2is2)Exponentiation:
**(e.g.,2 ** 3is8)Remainder (Modulo):
%(yields the remainder of a division)
Operator Properties:
Unary: Operators with one operand (e.g., the negative sign in
-5).Binary: Operators with two operands (e.g.,
4 - 5).
Remainder Applications: Determining if a number is even (
num % 2 == 0) or odd (num % 2 == 1), and clock/calendar arithmetic.Precision and Storage:
Integers are stored precisely.
Floating-point numbers are approximations (e.g.,
1.0 - 0.9might display0.09999999999999998).Overflow: Value too large to be stored (
245.0 ** 1000results inOverflowError).Underflow: Value too small, approximated to zero.
Scientific Notation: Use
eorE. Example:1.23456e+2is123.456;1.23456e-2is0.0123456.Precedence Rules:
Parentheses (innermost first).
Exponentiation (
**).Multiplication, Division (
/,//), and Remainder (%) (left to right).Addition and Subtraction (left to right).
Augmented Assignment Operators
These operators combine an operation and assignment:
count += 1is equivalent tocount = count + 1.Operators:
+=,-=,*=,/=,//=,%=,**=.Evaluation Order: Augmented assignments are performed last, after all other operators in the expression are evaluated.
Example:
x /= 4 + 5.5 * 1.5is equivalent tox = x / (4 + 5.5 * 1.5).
Type Conversions and Rounding
Implicit Conversion: If an integer and float are in a binary operation, Python converts the integer to a float.
int(value): Returns the integer part of a float (truncates, does not round). It can also convert a numeric string to an integer.round(value): Rounds to the nearest whole value.Banker's Rounding:
If the number is odd and followed by
.5, it rounds up (e.g.,round(5.5)is6).If the number is even and followed by
.5, it rounds to the even number (e.g.,round(6.5)is6).
str(value): Converts a numeric value to a string.Conversion Note:
int()andround()return new values and do not change the original variable unless it is reassigned (x = int(x)).int()vseval():int("003")works (returns3), whereaseval("003")produces an error due to leading zeros.
Case Studies in Development
Problem 6: Convert Time: Given seconds, find minutes and remaining seconds.
Problem 7: Keeping Two Digits After Decimal Points: Calculate sales tax (6%) and display it with exactly two decimals.
Method:
int(tax * 100) / 100.0(Multiplies by 100 to shift decimals, truncates withint, then divides by 100.0).
Problem 10: Computing Distances: Calculate distance between and .
Formula:
Python expression:
((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)) ** 0.5
Questions & Discussion
Check Point #1: Printout of
width=5.5; height=2; print("area is", width*height)?Result:
area is 11.0.
Check Point #3: What happens if the user enters
5aforeval(input("Enter radius: "))?Result: Runtime error.
Check Point #4: Valid identifiers?
Valid:
miles,Test,apps,y,iF.Invalid:
a+b,b-a,4#R,$4,#44.Keywords:
elif,if.
Check Point #6: Evaluate expressions:
42 / 5→8.442 // 5→842 % 5→25.1 ** 2→26.009999999999998
Check Point #7: Today is Tuesday, what is the day in 100 days (Saturday = 1)?
Tuesday is day 4. . Day 6 is Thursday.
Check Point #10:
a = 1; result ofa = 56 * a + 6?Result:
62.
Self-Test Question: ‘What is the result of
eval("1 + 3 * 2")?’Answer:
7.
Self-Test Question: ‘What function reads a string?’
Answer:
input("Enter a string").