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):

    1. Obtain the radius of the circle.

    2. Compute the area using the formula area=radius×radius×3.14159area = radius \times radius \times 3.14159.

    3. 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 area or radius rather than arbitrary letters like x or y.

  • Tracing a Program: A method of reviewing a program by tracking the values in memory for variables as each line executes.

    • Line 2: radius is 20.

    • Line 5: area becomes 1256.636.

  • The print Statement: Can display multiple items simultaneously using the syntax print(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 True or False.

  • 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 a TypeError.

  • The eval() Function: Evaluates a string and converts it to a numeric value.

    • eval("34.5") returns 34.5 (float).

    • eval("3 + 4") returns 7 (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:

    1. Must consist only of letters, digits, and underscores (_).

    2. Must start with a letter or underscore; cannot start with a digit.

    3. Cannot be a Python Keyword (reserved word).

    4. Can be any length.

  • Keywords Examples: import, if, in, elif, False, True.

  • Case Sensitivity: area, Area, and AREA are 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 = 1 sets 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 / 2 is 2.0)

    • Integer Division: // (truncates fractional part; e.g., 5 // 2 is 2)

    • Exponentiation: ** (e.g., 2 ** 3 is 8)

    • 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.9 might display 0.09999999999999998).

    • Overflow: Value too large to be stored (245.0 ** 1000 results in OverflowError).

    • Underflow: Value too small, approximated to zero.

  • Scientific Notation: Use e or E. Example: 1.23456e+2 is 123.456; 1.23456e-2 is 0.0123456.

  • Precedence Rules:

    1. Parentheses (innermost first).

    2. Exponentiation (**).

    3. Multiplication, Division (/, //), and Remainder (%) (left to right).

    4. Addition and Subtraction (left to right).

Augmented Assignment Operators

  • These operators combine an operation and assignment: count += 1 is equivalent to count = 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.5 is equivalent to x = 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:

      1. If the number is odd and followed by .5, it rounds up (e.g., round(5.5) is 6).

      2. If the number is even and followed by .5, it rounds to the even number (e.g., round(6.5) is 6).

  • str(value): Converts a numeric value to a string.

  • Conversion Note: int() and round() return new values and do not change the original variable unless it is reassigned (x = int(x)).

  • int() vs eval(): int("003") works (returns 3), whereas eval("003") produces an error due to leading zeros.

Case Studies in Development

  • Problem 6: Convert Time: Given seconds, find minutes and remaining seconds.

    • minutes=seconds//60minutes = seconds // 60

    • remainingSeconds=seconds%60remainingSeconds = seconds \% 60

  • 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 with int, then divides by 100.0).

  • Problem 10: Computing Distances: Calculate distance between (x1,y1)(x_1, y_1) and (x2,y2)(x_2, y_2).

    • Formula: distance=(x2x1)2+(y2y1)2distance = \sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2}

    • 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 5a for eval(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 / 58.4

    • 42 // 58

    • 42 % 52

    • 5.1 ** 226.009999999999998

  • Check Point #7: Today is Tuesday, what is the day in 100 days (Saturday = 1)?

    • Tuesday is day 4. (4+100)%7=6(4 + 100) \% 7 = 6. Day 6 is Thursday.

  • Check Point #10: a = 1; result of a = 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").