Computer Programming for Engineering: Loops, Functions, and Sequences

Introduction to Loops

  • Definition of a Loop: A loop is a programming construct that repeats a process until a specified condition becomes false.
  • Purpose: It executes the same block of code repeatedly as long as the condition remains true.
  • Supported Loop Types in Python: Python supports two primary types of loops:   - while loop   - for loop

The While Loop

  • Syntax:
  while condition:
      statements
  ```
- **Identifying Values**: To solve problems using a `while` loop, three specific values must be identified:
  1. **Start**: The initial value of the loop control variable.
  2. **Step**: The increment or decrement value for each iteration.
  3. **Stop**: The condition that determines when the loop terminates.
- **Termination**: The loop will stop executing only if the condition evaluated becomes false.
- **Basic Example**: Printing "Python" 10 times.
  - Code:
    ```python
    i=1
    while i<=10:
        print("Python")
        i=i+1
&nbsp;&nbsp;&nbsp;&nbsp;```

# While Loop Logical Examples

- **Print all numbers from 1 to 5**:
&nbsp;&nbsp;- Start: 11
&nbsp;&nbsp;- Step: +1+1
&nbsp;&nbsp;- Stop: 55
&nbsp;&nbsp;- Code:
    ```python
    i=1
    while i<=5:
        print(i)
        i=i+1
&nbsp;&nbsp;&nbsp;&nbsp;```
- **Print odd numbers from 1 to 10**:
&nbsp;&nbsp;- Start: 11
&nbsp;&nbsp;- Step: +2+2
&nbsp;&nbsp;- Stop: 1010
&nbsp;&nbsp;- Code:
    ```python
    i=1
    while i<=10:
        print(i)
        i=i+2
&nbsp;&nbsp;&nbsp;&nbsp;```
- **Print even numbers from 2 to 10**:
&nbsp;&nbsp;- Start: 22
&nbsp;&nbsp;- Step: +2+2
&nbsp;&nbsp;- Stop: 1010
&nbsp;&nbsp;- Code:
    ```python
    i=2
    while i<=10:
        print(i)
        i=i+2
&nbsp;&nbsp;&nbsp;&nbsp;```
- **Print all numbers from 10 to 1 (Reverse)**:
&nbsp;&nbsp;- Start: 1010
&nbsp;&nbsp;- Step: 1-1
&nbsp;&nbsp;- Stop: 11
&nbsp;&nbsp;- Code:
    ```python
    i=10
    while i>=1:
        print(i)
        i=i-1
&nbsp;&nbsp;&nbsp;&nbsp;```

# Dynamic While Loops with User Input

- **Requirement**: Any variable represented by an alphabet (e.g., aa, bb, nn) implies that input must be gathered from the user.
- **Print all numbers from 1 to n**:
&nbsp;&nbsp;- Start: 11
&nbsp;&nbsp;- Step: +1+1
&nbsp;&nbsp;- Stop: nn
&nbsp;&nbsp;- Code:
    ```python
    n = int(input("Enter the n value"))
    i=1
    while i<=n:
        print(i)
        i=i+1
&nbsp;&nbsp;&nbsp;&nbsp;```
- **Print even numbers from 2 to n**:
&nbsp;&nbsp;- Start: 22
&nbsp;&nbsp;- Step: +2+2
&nbsp;&nbsp;- Stop: nn
&nbsp;&nbsp;- Code:
    ```python
    n = int(input("Enter the n value"))
    i=2
    while i<=n:
        print(i)
        i=i+2
&nbsp;&nbsp;&nbsp;&nbsp;```

# Series Calculation Using While Loops

- **Common Steps for Series Problems**:
&nbsp;&nbsp;1. Identify the starting and ending values.
&nbsp;&nbsp;2. Identify the difference between the first and next numbers in the series.
&nbsp;&nbsp;3. Define the loop condition.
&nbsp;&nbsp;4. Determine the increment or decrement value.
&nbsp;&nbsp;5. Declare a sum variable and initialize it (usually to 0 for addition or 1 for multiplication).

- **Calculate S=11+22+33++nnS = 1^1 + 2^2 + 3^3 + \dots + n^n**:
&nbsp;&nbsp;- Code:
    ```python
    n = int(input("Enter n value"))
    i=1
    sum=0
    while i<=n:
        sum = sum+pow(i,i)
        i=i+1
    print(sum)
&nbsp;&nbsp;&nbsp;&nbsp;```

- **Calculate S=1x+2x+3x++nxS = 1^x + 2^x + 3^x + \dots + n^x**:
&nbsp;&nbsp;- Code:
    ```python
    n = int(input("Enter n value"))
    x = int(input("Enter x value"))
    i=1
    sum=0
    while i<=n:
        sum = sum+pow(i,x)
        i=i+1
    print(sum)
&nbsp;&nbsp;&nbsp;&nbsp;```

- **Calculate S=12+23+34++nn+1S = \frac{1}{2} + \frac{2}{3} + \frac{3}{4} + \dots + \frac{n}{n+1}**:
&nbsp;&nbsp;- Code:
    ```python
    n = int(input("Enter n value"))
    i=1
    sum=0
    while i<=n:
        sum = sum+i/(i+1)
        i=i+1
    print(sum)
&nbsp;&nbsp;&nbsp;&nbsp;```

- **Calculate Z=4×8×12××nZ = 4 \times 8 \times 12 \times \dots \times n**:
&nbsp;&nbsp;- Code:
    ```python
    n = int(input("Enter n value"))
    i=4
    sum=1
    while i<=n:
        sum = sum*i
        i=i+4
    print(sum)
&nbsp;&nbsp;&nbsp;&nbsp;```

# The For Loop and Range Function

- **Syntax**:

python for variable in range(start value, End value, Step): Statements   ```

  • The range() Function Default Behaviors:   - The starting value defaults to 00.   - The step value defaults to 11.   - The loop stops at End value - 1 (the end value is exclusive).

  • For Loop Logical Examples:   - Print numbers 1 to 5:     - Explicit range: range(1, 6, 1)     - Implicit range: range(1, 6)   - Print odd numbers from 1 to 10:     - Range: range(1, 11, 2)   - Print even numbers from 2 to 10:     - Range: range(2, 11, 2)   - Print all numbers from 10 to 1:     - Range: range(10, 0, -1)   - Print even numbers from 10 to 2:     - Range: range(10, 1, -2)   - Print odd numbers from 9 to 1:     - Range: range(9, 0, -2)

Series Calculation Using For Loops

  • Calculate S=11+22+33++nnS = 1^1 + 2^2 + 3^3 + \dots + n^n:   - Code: python n = int(input("Enter the n value")) sum=0 for i in range(1, n+1, 1): sum = sum+pow(i,i) print(sum) &nbsp;&nbsp;&nbsp;&nbsp;

  • Calculate S=1x+2x+3x++nxS = 1^x + 2^x + 3^x + \dots + n^x:   - Code: python n = int(input("Enter the n value")) x = int(input("Enter x value")) sum=0 for i in range(1, n+1, 1): sum = sum+pow(i,x) print(sum) &nbsp;&nbsp;&nbsp;&nbsp;

  • Calculate S=12+23+34++nn+1S = \frac{1}{2} + \frac{2}{3} + \frac{3}{4} + \dots + \frac{n}{n+1}:   - Code: python n = int(input("Enter the n value")) sum=0 for i in range(1, n+1, 1): sum = sum+i/(i+1) print(sum) &nbsp;&nbsp;&nbsp;&nbsp;

  • Calculate Z=4×8×12××nZ = 4 \times 8 \times 12 \times \dots \times n:   - Code: python n = int(input("Enter the n value")) sum=1 for i in range(4, n+1, 4): sum = sum*i print(sum) &nbsp;&nbsp;&nbsp;&nbsp;

Iteration and Enhanced For Loops

  • General Concept: A for loop iterates over a collection of objects (like strings, lists, or tuples), performing the same operation on each object in sequence.
  • Syntax for Collections:
  for object in collection_of_objects:
      # code to execute on each object
&nbsp;&nbsp;```
- **String Example**:
&nbsp;&nbsp;- Input: `"UTAS"`
&nbsp;&nbsp;- Code:
    ```python
    for c in "UTAS":
        print(c)
&nbsp;&nbsp;&nbsp;&nbsp;```
&nbsp;&nbsp;- Output:
&nbsp;&nbsp;&nbsp;&nbsp;- U
&nbsp;&nbsp;&nbsp;&nbsp;- T
&nbsp;&nbsp;&nbsp;&nbsp;- A
&nbsp;&nbsp;&nbsp;&nbsp;- S

# Integrating Loops and Conditional Statements

- **Example 1**: Based on user input parity.
&nbsp;&nbsp;- Requirement: If input is odd, print 1 to 20 using `for` loop. Otherwise, print 20 to 1 using `while` loop.
&nbsp;&nbsp;- Code:
    ```python
    n=int(input("enter a number"))
    if n%2==1:
        for i in range(1,21,1):
            print(i)
    else:
        i=20
        while i>=1:
            print(i)
            i=i-1
&nbsp;&nbsp;&nbsp;&nbsp;```
- **Example 2**: Checking divisibility within a loop.
&nbsp;&nbsp;- Requirement: Print numbers 1 to 30. If a number is divisible by 5, output a specific message.
&nbsp;&nbsp;- Code:
    ```python
    for i in range(1,31,1):
        if i%5==0:
            print(i, "Number is divisible by 5")
        else:
            print(i, "Number is not divisible by 5")
&nbsp;&nbsp;&nbsp;&nbsp;```

# Procedural Programming: Functions

- **Motivation for Functions**:
&nbsp;&nbsp;- To handle repetitive sections of code more efficiently.
&nbsp;&nbsp;- To avoid rewriting entire scripts for small logical changes.
&nbsp;&nbsp;- To break programs into manageable pieces of functionality.
&nbsp;&nbsp;- **Modularity**: Functions allow internal logic to change without affecting other program parts.
- **Parameters and Results**:
&nbsp;&nbsp;- **Parameters**: Data supplied to the function.
&nbsp;&nbsp;- **Results/Output**: The final information returned by the function.
- **Syntax**:

python def function_name(parameters): function body statements   `` &nbsp;&nbsp;- Functions are defined using thedef` statement.   - The function body must be indented.   - Termination of indentation signifies the end of the function.

Function Execution and Flow

  • Function Definition vs. Calling:   - Python reads the definition, but the code inside is executed only when the function is called.   - Example: python def test(): print("UTAS") test() # This line calls the function &nbsp;&nbsp;&nbsp;&nbsp;
  • Functions with Parameters:   - Values passed during calling are assigned positional parameters.   - Example: add(2,3) assigns 22 to aa and 33 to bb.
  • Functions with Return Types:   - Syntax using type hinting: def add(a:int, b:int) -> int:   - Use the return statement to send a value back to the caller.

Advanced Function Examples

  • Greatest of Four Numbers:
  def greatestoffour(num1, num2, num3, num4):
      if num1>num2 and num1>num3 and num1>num4:
          return num1
      elif num2>num3 and num2>num4:
          return num2
      elif num3>num4:
          return num3
      else:
          return num4
&nbsp;&nbsp;```
- **Arithmetic Calculator Functions**:
&nbsp;&nbsp;- `addition(num1, num2)`: returns `num1 + num2`
&nbsp;&nbsp;- `subtraction(num1, num2)`: returns `num1 - num2`
&nbsp;&nbsp;- `multiplication(num1, num2)`: returns `num1 * num2`
&nbsp;&nbsp;- `division(num1, num2)`: returns `num1 / num2`
&nbsp;&nbsp;- `floordivision(num1, num2)`: returns `num1 // num2`
&nbsp;&nbsp;- `modulus(num1, num2)`: returns `num1 % num2`
&nbsp;&nbsp;- `exponent(num1, num2)`: returns `num1 ** num2`

# Sequence Types: Lists and Tuples

- **Definition**: A sequence is a positional ordered collection of items.
- **Indexing**: Python sequences use zero-based indexing.
&nbsp;&nbsp;- First item: `s[0]`
&nbsp;&nbsp;- Second item: `s[1]`
&nbsp;&nbsp;- Last item for nn items: `s[n-1]`
- **Classification**:
&nbsp;&nbsp;1. **Mutable**: Elements can be changed (e.g., Lists).
&nbsp;&nbsp;2. **Immutable**: Elements cannot be changed after creation (e.g., Tuples).
- **Content**:
&nbsp;&nbsp;- **Homogeneous**: All elements have the same type.
&nbsp;&nbsp;- **Heterogeneous**: Elements have different types (numbers, strings, objects, etc.).

# Python Lists

- **Characteristics**: Heterogeneous and Mutable.
- **Declaration**: Using square brackets `[]` with comma-separated items.
&nbsp;&nbsp;- `list1 = [1, 2, 3, 4]`
&nbsp;&nbsp;- `list2 = ['red', 'green', 'blue']`
&nbsp;&nbsp;- `list3 = ['hello', 100, 3.14, [1, 2, 3]]`
- **Modification Example**:

python list = [10, 20, 30, 40] list[1] = 100 # Changes 20 to 100   ```

  • List Operations:   - Accessing: Use index numbers (e.g., list2[0] returns 'u').   - Slicing: list3[2:5] (extracts items from index 2 to 4).   - Deleting:     - del list3[2] (removes item at index 2).     - del list3[1:5] (removes a range of items).   - Appending: var.append(44) (adds one element to the end).   - Extending: var.extend([55, 66, 77]) (adds multiple elements to the end).

Python Tuples

  • Characteristics: Heterogeneous and Immutable.
  • Declaration: Using parenthesis ().   - tup = ("78 Street", 3.8, 9826)
  • Immutability Details: You cannot change, add, or remove items once the tuple is created.
  • Special Cases:   - Empty tuple: Requires parentheses ().   - Single item tuple: Must use a trailing comma (e.g., (item,)).
  • Reassignment: While items inside cannot change, the variable itself can be reassigned to a new tuple.