✦ VidyaVerseOpen interactive version

← Programming Concepts in Mechanical Engineering (25ME34I)

Control Structures: Conditional Statements and Loops

Programming Concepts in Mechanical Engineering (25ME34I) · C-25 Diploma Mechanical, Semester III

Read with diagrams, search and self-test

LEARNING OBJECTIVES

After studying this chapter you will be able to:

• Write decision-making programs using if, if-else, if-elif-else and nested if statements.

• Repeat tasks using for loops (with range) and while loops.

• Use loop-control statements break, continue and pass, and the loop-else clause.

• Choose between a for loop and a while loop for an engineering task.

3.1 Introduction

Normally Python executes statements one after another (sequence). Control structures change this order. Conditional statements let a program choose between alternatives, and loops let it repeat statements. With these two tools a program can take decisions like a machine operator and work tirelessly like a machine.

Every condition is an expression that evaluates to True or False, built using comparison operators (== != > < >= <=) and logical operators (and or not). A block of statements controlled by a condition is identified by indentation (4 spaces) after a colon.

3.2 The if Statement

The simple if executes a block only when the condition is True; otherwise the block is skipped.

if condition:
    statement(s)      # executed only if condition is True
temp = float(input("Coolant temperature (°C): "))
if temp > 90:
    print("WARNING: Engine overheating!")
print("Check complete")
OUTPUT
Coolant temperature (°C): 95
WARNING: Engine overheating!
Check complete

3.3 The if-else Statement

if-else provides two alternative paths: one when the condition is True and the other when it is False. Exactly one of them is executed.

if condition:
    block-1           # condition True
else:
    block-2           # condition False
marks = float(input("Enter marks: "))
if marks >= 35:
    print("Result: PASS")
else:
    print("Result: FAIL")
OUTPUT
Enter marks: 48
Result: PASS

Engineering example – acceptance of a product for transport. A transport trolley can carry loads between 5 kg and 50 kg.

weight = float(input("Product weight (kg): "))
if 5 <= weight <= 50:
    print("Weight acceptable for transport")
else:
    print("Weight NOT acceptable - re-pack the product")
OUTPUT
Product weight (kg): 62
Weight NOT acceptable - re-pack the product

Python allows chained comparisons: 5 <= weight <= 50 means weight >= 5 and weight <= 50.

3.4 The if-elif-else Ladder

When there are more than two alternatives, elif (short for "else if") is used. Conditions are tested from top to bottom; the block of the first True condition is executed and the rest are skipped. The final else is optional and runs when all conditions are False.

if condition1:
    block-1
elif condition2:
    block-2
elif condition3:
    block-3
else:
    block-4

Fig. 3.1 if-elif-else ladder for pipeline pressure warning

# Pipeline pressure monitoring
p = float(input("Pipeline pressure (bar): "))
if p < 2:
    print("LOW pressure - check pump")
elif p <= 6:
    print("NORMAL pressure")
elif p <= 8:
    print("HIGH pressure - caution")
else:
    print("DANGER - open relief valve!")
OUTPUT
Pipeline pressure (bar): 7.5
HIGH pressure - caution

Advantages of elif: checks many conditions in order, avoids deeply nested if statements, makes code readable and stops checking as soon as one condition is satisfied (efficient).

3.5 Nested if Statements

An if statement placed inside another if is called a nested if. It is used when one condition is meaningful only when another condition is already satisfied.

temperature = float(input("Temperature (°C): "))
pressure = float(input("Pressure (bar): "))
if temperature < 80:
    if pressure < 100:
        print("Machine is SAFE")
    else:
        print("Unsafe: pressure too high")
else:
    print("Unsafe: temperature too high")
OUTPUT
Temperature (°C): 70
Pressure (bar): 110
Unsafe: pressure too high

3.6 Loops

A loop repeats a block of statements. Each repetition is called an iteration. Python has two loops: for and while.

3.6.1 The for loop and range()

The for loop iterates over a sequence (range of numbers, list, string, tuple, dictionary). It is used when the number of repetitions is known in advance.

for variable in sequence:
    statement(s)

range() generates a sequence of integers:

CallNumbers generated
range(5)0, 1, 2, 3, 4
range(1, 6)1, 2, 3, 4, 5
range(0, 21, 5)0, 5, 10, 15, 20
range(10, 0, -2)10, 8, 6, 4, 2

The stop value is never included.

# Load table for a bolt: stress at different loads
area = 84.3     # stress area of M12 bolt, mm^2
for load in range(5000, 25001, 5000):
    print(f"Load {load:6d} N  -> stress {load/area:6.1f} MPa")
OUTPUT
Load   5000 N  -> stress   59.3 MPa
Load  10000 N  -> stress  118.6 MPa
Load  15000 N  -> stress  177.9 MPa
Load  20000 N  -> stress  237.2 MPa
Load  25000 N  -> stress  296.6 MPa
for ch in "LATHE":
    print(ch, end=" ")
OUTPUT
L A T H E

3.6.2 The while loop

The while loop repeats a block as long as its condition is True. The condition is checked before every iteration. It is used when the number of repetitions is not known in advance – for example, "keep heating until temperature reaches 100 °C".

initialisation
while condition:
    statement(s)
    update
# Tank filling: 50 litres added every minute
level, minute = 0, 0
while level < 400:
    level += 50
    minute += 1
print("Tank full in", minute, "minutes")
OUTPUT
Tank full in 8 minutes
REMEMBER

The loop variable must be updated inside a while loop. If the condition never becomes False, the loop runs forever (infinite loop). Press Ctrl+C to stop such a program.

3.6.3 for loop vs while loop

for loopwhile loop
Used when the number of iterations is knownUsed when iterations depend on a condition
Iterates over a sequence or range()Repeats while a condition is True
Loop variable is updated automaticallyProgrammer must update the variable
Less chance of infinite loopInfinite loop possible if update is missed
Example: print table, process 10 readingsExample: run motor until limit switch, accept input until valid

3.7 Loop Control Statements

break

break terminates the loop immediately; control passes to the first statement after the loop.

continue

continue skips the remaining statements of the current iteration and goes to the next iteration.

pass

pass does nothing. It is a placeholder where a statement is syntactically required but no action is needed yet (empty function, class or block).

Fig. 3.2 Effect of break and continue

print("break   :", end=" ")
for i in range(1, 11):
    if i == 6:
        break
    print(i, end=" ")
print("\ncontinue:", end=" ")
for i in range(1, 6):
    if i == 3:
        continue
    print(i, end=" ")
print("\npass    :", end=" ")
for i in range(1, 4):
    if i == 2:
        pass        # placeholder, no effect
    print(i, end=" ")
OUTPUT
break   : 1 2 3 4 5
continue: 1 2 4 5
pass    : 1 2 3
Stateme ntActionTypical use
breakEnds the loop at onceStop searching once a faulty part is found
continueSkips to next iterationSkip a component that is under maintenance
passDoes nothingPlaceholder for code to be written later

Engineering example – checking machine components for faults.

parts = ["bearing", "skip", "shaft", "gear",
         "FAULT:belt", "coupling"]
for p in parts:
    if p == "skip":
        continue                 # part under maintenance
    if p.startswith("FAULT"):
        print("Fault found ->", p, "- stopping line")
        break
    print("Checked OK :", p)
OUTPUT
Checked OK : bearing
Checked OK : shaft
Checked OK : gear
Fault found -> FAULT:belt - stopping line

The else clause of loops

A loop may have an else block that runs only if the loop ended normally (not through break).

readings = [72, 75, 78, 74]
for r in readings:
    if r > 90:
        print("Overheat at", r)
        break
else:
    print("All readings normal")
OUTPUT
All readings normal

3.8 Practice Programs (Week 3)

Program 3.1 – Even or odd

Algorithm: Start → read N → if N % 2 == 0 print "Even" else print "Odd" → Stop.

Fig. 3.3 Flowchart: even or odd

# Program 3.1: Even or odd
n = int(input("Enter an integer: "))
if n % 2 == 0:
    print(n, "is EVEN")
else:
    print(n, "is ODD")
OUTPUT
Enter an integer: 17
17 is ODD

Program 3.2 – Multiplication table using a for loop

# Program 3.2: Multiplication table
n = int(input("Enter the number: "))
for i in range(1, 11):
    print(f"{n:3d} x {i:2d} = {n*i:4d}")
OUTPUT
Enter the number: 7
  7 x  1 =    7
  7 x  2 =   14
  7 x  3 =   21
  7 x  4 =   28
  7 x  5 =   35
  7 x  6 =   42
  7 x  7 =   49
  7 x  8 =   56
  7 x  9 =   63
  7 x 10 =   70

Program 3.3 – Factorial using a while loop

N! = 1 × 2 × 3 × ... × N, with 0! = 1. Factorials are used in permutations and in the binomial and Poisson distributions of quality control.

Fig. 3.4 Flowchart: factorial using while loop

# Program 3.3: Factorial using while loop
n = int(input("Enter a non-negative integer: "))
if n < 0:
    print("Factorial not defined for negative numbers")
else:
    fact, i = 1, 1
    while i <= n:
        fact = fact * i
        i += 1
    print(f"{n}! = {fact}")
OUTPUT
Enter a non-negative integer: 6
6! = 720

Program 3.4 – Grade of a student (elif ladder)

m = float(input("Enter percentage: "))
if m >= 85:
    grade = "Distinction"
elif m >= 60:
    grade = "First Class"
elif m >= 50:
    grade = "Second Class"
elif m >= 35:
    grade = "Pass"
else:
    grade = "Fail"
print("Grade:", grade)
OUTPUT
Enter percentage: 78
Grade: First Class

Program 3.5 – Largest of two numbers

a = float(input("First number : "))
b = float(input("Second number: "))
if a > b:
    print("Largest =", a)
else:
    print("Largest =", b)
OUTPUT
First number : 25
Second number: 40
Largest = 40.0

Program 3.6 – Sum of N natural numbers and average of readings

n = int(input("How many readings? "))
total = 0
for k in range(1, n + 1):
    x = float(input(f"Reading {k}: "))
    total += x
print(f"Sum = {total:.2f}, Average = {total/n:.3f}")
OUTPUT
How many readings? 5
Reading 1: 12.1
Reading 2: 12.4
Reading 3: 11.9
Reading 4: 12.0
Reading 5: 12.6
Sum = 61.00, Average = 12.200

Program 3.7 – Shaft diameter acceptance (tolerance check)

A shaft is specified as 25 ± 0.02 mm.

d = float(input("Measured diameter (mm): "))
LSL, USL = 24.98, 25.02
if d < LSL:
    print("REJECT - undersize (scrap)")
elif d > USL:
    print("REWORK - oversize (re-machine)")
else:
    print("ACCEPT - within tolerance")
OUTPUT
Measured diameter (mm): 25.03
REWORK - oversize (re-machine)

Program 3.8 – Input validation with while loop

rpm = float(input("Enter spindle speed (rpm): "))
while rpm <= 0:
    print("Speed must be positive, try again")
    rpm = float(input("Enter spindle speed (rpm): "))
print("Speed accepted:", rpm)
OUTPUT
Enter spindle speed (rpm): -3
Speed must be positive, try again
Enter spindle speed (rpm): 0
Speed must be positive, try again
Enter spindle speed (rpm): 1500
Speed accepted: 1500.0

Program 3.9 – Fibonacci series and sum of digits

n = int(input("How many Fibonacci terms? "))
a, b = 0, 1
for _ in range(n):
    print(a, end=" ")
    a, b = b, a + b
print()
num = int(input("Enter a number: "))
s, t = 0, num
while t > 0:
    s += t % 10
    t //= 10
print("Sum of digits of", num, "=", s)
OUTPUT
How many Fibonacci terms? 10
0 1 1 2 3 5 8 13 21 34
Enter a number: 4527
Sum of digits of 4527 = 18

Program 3.10 – Leap year and positive/negative/zero

y = int(input("Year: "))
if (y % 4 == 0 and y % 100 != 0) or y % 400 == 0:
    print(y, "is a leap year")
else:
    print(y, "is not a leap year")
x = float(input("Number: "))
if x > 0:
    print("Positive")
elif x < 0:
    print("Negative")
else:
    print("Zero")
OUTPUT
Year: 2024
2024 is a leap year
Number: -8
Negative

3.9 Solved Exam Questions

Q1. A user inputs a product's weight. Write an if-else condition to check whether the weight is within the acceptable range for transport. (7 marks)

Answer: See the program in Section 3.3. The acceptable range is taken as 5 kg to 50 kg. The condition 5 <= weight <= 50 is True for acceptable weights, so the if block prints "acceptable"; otherwise the else block prints "not acceptable". The value is read with float(input()) because weight can have decimals.

Q2. You are programming a system that checks pipeline pressure and outputs warnings for low, medium or high pressure. How would you use elif? (7 marks)

Answer: An if-elif-else ladder is ideal because there are more than two ranges and exactly one message must be shown. The first condition checks low pressure; if false, elif checks the medium range; the final else handles high pressure. See Fig.

3.1 and the program in Section 3.4. Only the first True branch is executed, so the ranges need not repeat their lower limits.

Q3. Differentiate between break, continue and pass with examples in an engineering program that processes a list of machine components. (6 marks)

Answer: break ends the loop as soon as a faulty component is found (no need to check further). continue skips a component that is under maintenance and moves to the next one. pass is a do-nothing placeholder, e.g. if part == "spare": pass where handling will be added later. See the table and the component-checking program in Section 3.7.

Q4. Differentiate between for loop and while loop. When would you use each in an engineering context? (6 marks)

Answer: Refer the comparison table in Section 3.6.3. Use a for loop to compute stress for loads from 5 kN to 25 kN in steps of 5 kN, or to process 25 samples of a control chart (count known). Use a while loop to keep running a pump until the tank is full, or to keep asking until the operator enters a valid speed (count unknown).

Q5. Explain the nested if statement with a suitable example.

Answer: A nested if is an if inside another if; the inner condition is tested only when the outer condition is True. Example: a machine is safe only if temperature is below 80 °C and, in that case, pressure is below 100 bar. See Section 3.5.

Q6. What is an infinite loop? How can it be avoided?

Answer: A loop whose condition never becomes False, e.g. while i <= 5: without i += 1. Avoid it by updating the loop variable, using a for loop when the count is known, or using break under a safety condition. Intentional infinite loops (while True:) are used in Raspberry Pi monitoring programs, with Ctrl+C to stop them.

3.10 Multiple Choice Questions

1. Which keyword is used for multiple conditions after if? a) else if b) elseif c) elif d) ifelse

Answer: (c) Reason: Python uses elif; "else if" written as two words would need nesting.

2. range(2, 10, 3) generates a) 2, 5, 8 b) 2, 5, 8, 11 c)3,6,9 d)2,4,6,8

Answer: (a) Reason: Start 2, step 3, stop before 10: 2, 5, 8.

3. Which statement terminates a loop immediately? a) continue b) pass c) break d) exit

Answer: (c) Reason: break transfers control to the statement after the loop.

4. Which statement skips the rest of the current iteration? a) break b) continue c) pass d) return

Answer: (b) Reason: continue jumps back to the loop header for the next iteration.

5. pass statement is used a) to exit a loop b) as a placeholder that does nothing c) to skip an iteration d) to raise an error

Answer: (b) Reason: pass is a null statement used where syntax requires a statement.

6. How many times does the loop for i in range(5): execute? a)4 b)5 c) 6 d) Infinite

Answer: (b) Reason: range(5) gives 0, 1, 2, 3, 4 – five values.

7. A while loop is best when a) the number of iterations is known b) the number of iterations depends on a condition c) iterating over a string d) never

Answer: (b) Reason: while continues until its condition becomes False, which may happen after any number of steps.

8. What is printed? x = 5; if x > 3: print("A") elif x > 1: print("B") a)A b)B c) A and B d) Nothing

Answer: (a) Reason: Only the first True branch of an if-elif ladder runs.

9. The else block of a for loop executes when a) the loop is broken b) the loop finishes without break c) always d) never

Answer: (b) Reason: Loop-else runs only on normal completion; break skips it.

10. Indentation in Python is used to a) improve looks only b) define blocks of code c) declare variables d) write comments

Answer: (b) Reason: Statements with the same indentation form a block under if, for, while, def.

11. Output of: i = 1; while i < 4: print(i, end=""); i += 1 a) 123 b) 1234 c) 12 d) Infinite loop

Answer: (a) Reason: The loop runs for i = 1, 2, 3 and stops when i becomes 4.

12. 6! equals a) 120 b) 720 c) 36 d) 5040

Answer: (b) Reason: 1 × 2 × 3 × 4 × 5 × 6 = 720.

13. Which condition checks that 5 ≤ w ≤ 50 in Python? a)5<=w<=50 b)5=<w=<50 c) w in 5..50 d) w between 5, 50

Answer: (a) Reason: Python supports chained comparison with <=.

14. A nested if means a) if inside a loop b) if inside another if c) two separate ifs d) if with elif

Answer: (b) Reason: The inner if is evaluated only when the outer condition is True.

15. Which loop cannot become infinite when used with range()? a) while b) for c) do-while d) both

Answer: (b) Reason: A for loop over range() always ends after the last value; Python has no do-while.

3.11 Exercises

1. Write a program to classify a steel by carbon content: < 0.3 % low, 0.3–0.6 % medium, > 0.6 % high carbon.

2. Write a program to print the squares and cubes of numbers 1 to 10 in table form.

3. Using a while loop, find how many years a machine worth ₹5,00,000 takes to depreciate below ₹1,00,000 at 15 % per year.

4. Print all prime numbers between 1 and 100.

5. Write a program that reads temperatures until the user enters −999 and then prints the maximum and average.