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:
-
whileloop -forloop
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
```
# While Loop Logical Examples
- **Print all numbers from 1 to 5**:
- Start:
- Step:
- Stop:
- Code:
```python
i=1
while i<=5:
print(i)
i=i+1
```
- **Print odd numbers from 1 to 10**:
- Start:
- Step:
- Stop:
- Code:
```python
i=1
while i<=10:
print(i)
i=i+2
```
- **Print even numbers from 2 to 10**:
- Start:
- Step:
- Stop:
- Code:
```python
i=2
while i<=10:
print(i)
i=i+2
```
- **Print all numbers from 10 to 1 (Reverse)**:
- Start:
- Step:
- Stop:
- Code:
```python
i=10
while i>=1:
print(i)
i=i-1
```
# Dynamic While Loops with User Input
- **Requirement**: Any variable represented by an alphabet (e.g., , , ) implies that input must be gathered from the user.
- **Print all numbers from 1 to n**:
- Start:
- Step:
- Stop:
- Code:
```python
n = int(input("Enter the n value"))
i=1
while i<=n:
print(i)
i=i+1
```
- **Print even numbers from 2 to n**:
- Start:
- Step:
- Stop:
- Code:
```python
n = int(input("Enter the n value"))
i=2
while i<=n:
print(i)
i=i+2
```
# Series Calculation Using While Loops
- **Common Steps for Series Problems**:
1. Identify the starting and ending values.
2. Identify the difference between the first and next numbers in the series.
3. Define the loop condition.
4. Determine the increment or decrement value.
5. Declare a sum variable and initialize it (usually to 0 for addition or 1 for multiplication).
- **Calculate **:
- 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)
```
- **Calculate **:
- 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)
```
- **Calculate **:
- 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)
```
- **Calculate **:
- Code:
```python
n = int(input("Enter n value"))
i=4
sum=1
while i<=n:
sum = sum*i
i=i+4
print(sum)
```
# 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 . - The step value defaults to . - The loop stops atEnd 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 : - 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) Calculate : - 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) Calculate : - 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) Calculate : - Code:
python n = int(input("Enter the n value")) sum=1 for i in range(4, n+1, 4): sum = sum*i print(sum)
Iteration and Enhanced For Loops
- General Concept: A
forloop 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
```
- **String Example**:
- Input: `"UTAS"`
- Code:
```python
for c in "UTAS":
print(c)
```
- Output:
- U
- T
- A
- S
# Integrating Loops and Conditional Statements
- **Example 1**: Based on user input parity.
- Requirement: If input is odd, print 1 to 20 using `for` loop. Otherwise, print 20 to 1 using `while` loop.
- 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
```
- **Example 2**: Checking divisibility within a loop.
- Requirement: Print numbers 1 to 30. If a number is divisible by 5, output a specific message.
- 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")
```
# Procedural Programming: Functions
- **Motivation for Functions**:
- To handle repetitive sections of code more efficiently.
- To avoid rewriting entire scripts for small logical changes.
- To break programs into manageable pieces of functionality.
- **Modularity**: Functions allow internal logic to change without affecting other program parts.
- **Parameters and Results**:
- **Parameters**: Data supplied to the function.
- **Results/Output**: The final information returned by the function.
- **Syntax**:
python
def function_name(parameters):
function body statements
``
- 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 - Functions with Parameters:
- Values passed during calling are assigned positional parameters.
- Example:
add(2,3)assigns to and to . - Functions with Return Types:
- Syntax using type hinting:
def add(a:int, b:int) -> int:- Use thereturnstatement 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
```
- **Arithmetic Calculator Functions**:
- `addition(num1, num2)`: returns `num1 + num2`
- `subtraction(num1, num2)`: returns `num1 - num2`
- `multiplication(num1, num2)`: returns `num1 * num2`
- `division(num1, num2)`: returns `num1 / num2`
- `floordivision(num1, num2)`: returns `num1 // num2`
- `modulus(num1, num2)`: returns `num1 % num2`
- `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.
- First item: `s[0]`
- Second item: `s[1]`
- Last item for items: `s[n-1]`
- **Classification**:
1. **Mutable**: Elements can be changed (e.g., Lists).
2. **Immutable**: Elements cannot be changed after creation (e.g., Tuples).
- **Content**:
- **Homogeneous**: All elements have the same type.
- **Heterogeneous**: Elements have different types (numbers, strings, objects, etc.).
# Python Lists
- **Characteristics**: Heterogeneous and Mutable.
- **Declaration**: Using square brackets `[]` with comma-separated items.
- `list1 = [1, 2, 3, 4]`
- `list2 = ['red', 'green', 'blue']`
- `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.