Unit 2 | BP101T | Basic of Python Programming for Pharmaceutical sciences

 

CHAPTER 2: CONTROL STRUCTURES AND FUNCTIONS

2.1 Introduction to Control Structures

In the previous chapter, we learned the basic concepts of Python programming, including variables, data types, input and output, operators, strings, libraries, and packages.

In this chapter, we will learn how Python makes decisions, repeats instructions, and organizes code into reusable blocks using functions.

In a Python program, statements are normally executed one after another, from top to bottom. However, real-world programs often require more flexibility. A program may need to make a decision based on a patient's temperature, repeat a calculation for several medicines, or perform the same operation multiple times.

Python provides control structures to manage the flow of program execution.

What are Control Structures?

Control structures are programming statements that determine the order in which instructions are executed in a program.

They allow a program to:

  • Make decisions based on conditions.

  • Repeat instructions using loops.

  • Control execution using statements such as break and continue.

For example, a healthcare application may check a patient's recorded temperature and display a message if the value is above a specified threshold.

Types of Control Structures

1. Conditional statements

These execute instructions based on whether a condition is true or false.

  • if

  • if-else

  • if-elif-else

  • Nested if

2. Looping statements

These repeat a block of code.

  • for loop

  • while loop

3. Loop control statements

These alter the normal execution of a loop.

  • break

  • continue

Functions are another important part of this chapter. They help divide a program into smaller, reusable sections of code.

2.2 Conditional Statements

Conditional statements allow Python to make decisions. They execute specific instructions depending on whether a given condition is satisfied.

A condition is an expression that evaluates to either True or False.

For example:

temperature = 39

print(temperature > 37.5)

Output:

True

The expression temperature > 37.5 is true because the stored value, 39, is greater than 37.5.

2.2.1 The if Statement

The if statement executes a block of code only when the specified condition is true.

Syntax

if condition:
    statement

The condition is evaluated first. If it is true, Python executes the indented statement. If it is false, the statement is skipped.

Example 1: Checking the patient's age

age = 65

if age >= 60:
    print("Senior patient")

Output:

Senior patient

Explanation

  1. The variable age stores the value 65.

  2. Python checks whether age >= 60.

  3. Since 65 is greater than or equal to 60, the condition is true.

  4. Python executes the print() statement.

Example 2: Checking temperature

temperature = 39

if temperature > 37.5:
    print("Temperature is above the threshold")

Output:

Temperature is above the threshold

n this example, the condition is true, so Python displays the message.

Note: The temperature threshold is used here for demonstrating Python syntax. Clinical interpretation depends on measurement method, patient context, and appropriate medical guidance.

Important Points About the if Statement

  • The keyword if must be written in lowercase.

  • A colon (:) is required at the end of the condition.

  • The statements inside the if block must be indented.

  • If the condition is false, the indented block is skipped.

Understanding indentation

Correct:

age = 65

if age >= 60:
    print("Senior patient")

Incorrect:

age = 65

if age >= 60:
print("Senior patient")

The second example produces an IndentationError because the statement inside the if block is not indented.

2.2.2 The if-else Statement

The if-else statement allows a program to choose between two alternatives.

  • If the condition is true, the if block executes.

  • If the condition is false, the else block executes.

Syntax

if condition:
    statement_if_true
else:
    statement_if_false

Example: Checking whether a patient is an adult

age = 17

if age >= 18:
    print("Adult")
else:
    print("Not an adult")

Output:

Not an adult

Explanation

The condition age >= 18 is false because the stored age is 17. Therefore, Python executes the else block.

Pharmacy-related example: Checking medicine stock

stock = 0

if stock > 0:
    print("Medicine available")
else:
    print("Medicine out of stock")

Output:

Medicine out of stock

This example demonstrates how a pharmacy inventory program could display a message depending on the recorded stock quantity.

2.2.3 The if-elif-else Statement

The if-elif-else statement is used when a program must choose among more than two alternatives.

Here, elif means else if.

Python checks the conditions from top to bottom. The block associated with the first true condition is executed, and the remaining conditions are skipped. If none of the conditions is true, the else block executes, if present.

Syntax

if condition1:
    statement1
elif condition2:
    statement2
elif condition3:
    statement3
else:
    default_statement

Example: Classifying stock quantity

stock = 5
if stock == 0: print("Out of stock") elif stock < 10: print("Low stock") elif stock < 50: print("Sufficient stock") else: print("High stock")

Output:

Low stock

Explanation

  1. stock == 0 is false.

  2. stock < 10 is true.

  3. Python displays "Low stock".

  4. The remaining conditions are not checked.

This type of conditional structure is useful for inventory management, laboratory record systems, and other applications that categorize values into different groups.

2.2.4 Nested if Statement

A nested if statement is an if statement placed inside another if statement.

It is useful when a second decision should be made only after an initial condition has been satisfied.

Example: Checking medicine availability

stock = 20
prescription_required = True

if stock > 0:
    print("Medicine is available")

    if prescription_required:
        print("Check prescription requirements")

Output:

Medicine is available
Check prescription requirements

Explanation

The outer if checks whether stock is greater than zero. Since the condition is true, Python executes its block.

Inside this block, the nested if checks whether the medicine requires a prescription. As this condition is also true, the second message is displayed.

If the outer condition were false, the nested if would not be reached.

2.3 Introduction to Loops

A loop is a control structure that repeatedly executes a block of code.

Without loops, we might need to write the same instruction many times. Loops reduce repetition and make programs easier to maintain.

For example, if we need to display the names or quantities of 100 medicines, a loop can process each item without requiring 100 separate print() statements.

Python provides two main types of loops:

  • for loop: Used to iterate over a sequence or other iterable.

  • while loop: Repeats while a condition remains true.

Loop control statements such as break and continue can change how a loop proceeds.

2.4 The for Loop

The for loop is used to iterate over items in a sequence, such as a list or string, or over a sequence of numbers generated by range().

Syntax

for variable in sequence:
    statement

The variable takes each value in the sequence, one at a time, and the indented statements execute for each value.

Example: Displaying numbers

for i in range(1, 6):
    print(i)

Output:

1
2
3
4
5

The function range(1, 6) generates the integers 1, 2, 3, 4, and 5. The ending value, 6, is not included.

Example: Displaying medicine names

medicines = ["Paracetamol", "Cetirizine", "Amoxicillin"]

for medicine in medicines:
    print(medicine)

Output:

Paracetamol
Cetirizine
Amoxicillin

The loop processes each medicine name in the list and displays it.

Understanding range()

The range() function is frequently used with for loops.

Expression

Values generated

range(5)

0, 1, 2, 3, 4

range(1, 6)

1, 2, 3, 4, 5

range(2, 11, 2)

2, 4, 6, 8, 10

The general form is:

range(start, stop, step)
  • start: The starting value; defaults to 0 when omitted.

  • stop: The stopping boundary, which is not included.

  • step: The amount by which the value changes; defaults to 1.

Pharmacy-related example: Recording daily observations

for day in range(1, 8):
    print("Day", day)

Output:

Day 1
Day 2
Day 3
Day 4
Day 5
Day 6
Day 7

This example demonstrates iteration over seven days. It does not prescribe a monitoring schedule; actual clinical monitoring must follow the appropriate protocol.

2.5 The while Loop

The while loop repeatedly executes a block of code as long as its condition is true.

Syntax

while condition:
    statement

Before each iteration, Python checks the condition. If it is true, the loop body executes. If it is false, the loop terminates.

Example: Displaying numbers from 1 to 5

i = 1

while i <= 5:
    print(i)
    i = i + 1

Output:

1
2
3
4
5

Explanation

  1. The variable i starts at 1.

  2. Python checks whether i <= 5.

  3. If true, the current value is displayed.

  4. The statement i = i + 1 increases i by 1.

  5. The condition is checked again.

  6. When i becomes 6, the condition is false and the loop stops.

Warning: Infinite Loops

An infinite loop occurs when a loop continues indefinitely because its termination condition never becomes false.

For example:

i = 1

while i <= 5:
    print(i)

In this program, i is never increased. Therefore, the condition remains true, and the program repeatedly prints 1.

To avoid this problem, ensure that the loop's condition can eventually become false or that an appropriate termination statement is reached.

2.6 The break Statement

The break statement immediately terminates the nearest enclosing loop.

Example

for i in range(1, 6):
    if i == 3:
        break
    print(i)

Output:

1
2

When i becomes 3, the condition is true. The break statement terminates the loop before print(i) executes for that value.

The loop does not continue with 4 or 5.

2.7 The continue Statement

The continue statement skips the remaining statements in the current loop iteration and proceeds to the next iteration.

Example

for i in range(1, 6):
    if i == 3:
        continue
    print(i)

Output:

1
2
4
5

When i is 3, Python executes continue. It skips the print(i) statement for that iteration but continues the loop with the next value.

Difference Between break and continue

break

continue

Terminates the loop.

Skips the current iteration.

No further iterations of that loop occur.

The loop proceeds to the next iteration.

Useful when a stopping condition is met.

Useful when a particular iteration should be skipped.

2.8 Defining, Calling, and Using Functions in Python

A function is a reusable block of code designed to perform a specific task. Functions help reduce code repetition and make programs easier to read, understand, and maintain.

In Python, working with functions involves three basic steps:

  1. Define a function – Write the code that describes what the function should do.

  2. Call a function – Execute the function by using its name.

  3. Use the result – Display or process the returned value, if the function returns one.

2.8.1 Defining a Function

Python uses the def keyword to define a function.

Syntax

def function_name():
    statements

Here:

  • def is the keyword used to define a function.

  • function_name is the name given to the function.

  • Parentheses () follow the function name.

  • A colon : marks the beginning of the function body.

  • Indented statements form the function body.

Example

def welcome():
    print("Welcome to Python programming")

In this example, a function named welcome() is defined. Its task is to display a welcome message.

However, defining the function does not execute its code. The function must be called to run it.

2.8.2 Calling a Function

A function is called by writing its name followed by parentheses.

Example

def welcome():
    print("Welcome to Python programming")

welcome()

Output:

Welcome to Python programming

When Python encounters welcome(), it executes the statements inside the function.

A function can be called multiple times.

def welcome():
    print("Welcome to Python programming")

welcome()
welcome()
welcome()

Output:

Welcome to Python programming
Welcome to Python programming
Welcome to Python programming

The same function is executed three times without rewriting its body.

2.8.3 Parameters and Arguments

Functions often need information to perform a task. Python allows us to pass information to a function using parameters and arguments.

A parameter is a variable specified in the function definition.

An argument is the actual value supplied when the function is called.

Example

def greet(name):
    print("Hello", name)

greet("Anu")
greet("Rahul")

Output:

Hello Anu
Hello Rahul

Explanation

  • name is the parameter.

  • "Anu" and "Rahul" are arguments.

  • When greet("Anu") is called, the parameter name receives the value "Anu".

  • When greet("Rahul") is called, it receives the value "Rahul".

This allows one function to work with different values.

Functions with Multiple Parameters

A function can accept more than one parameter.

Example: Calculating the total cost of medicines

def calculate_total(price, quantity):
    total = price * quantity
    print("Total cost:", total)

calculate_total(20, 5)
calculate_total(15, 4)

Output:

Total cost: 100
Total cost: 60

Explanation

In the function definition, price and quantity are parameters. The function multiplies these values to calculate the total cost.

During the first call, the arguments are 20 and 5. During the second call, they are 15 and 4.

This example demonstrates how functions can be used in pharmacy inventory and billing applications.

2.8.4 Return Values

A function can calculate a result and send it back to the statement that called it. This is done using the return statement.

A return value is the result sent back by a function.

Example

def add(a, b):
    result = a + b
    return result

answer = add(10, 20)

print("Answer:", answer)

Output:

Answer: 30

Explanation

  1. The function add() receives two arguments.

  2. The parameters a and b store the values 10 and 20.

  3. The expression a + b calculates 30.

  4. The return statement sends 30 back to the calling statement.

  5. The returned value is stored in the variable answer.

  6. The print() statement displays the result.

The advantage of using return is that the result can be stored, reused in another calculation, or passed to another function.

Difference Between print() and return

print()

return

Displays information on the screen.

Sends a value back to the caller.

Does not, by itself, provide a result for the caller to store.

Allows the caller to store and reuse the result.

Mainly used to display information.

Used to provide results from a function.

Example

def square_print(number):
    print(number * number)

def square_return(number):
    return number * number

square_print(4)

result = square_return(4)
print(result + 10)

Output:

16
26

The first function displays the square of 4. The second function returns 16, allowing the program to add 10 and display 26.

Important: If a function does not explicitly return a value, Python returns None by default.

2.9 Developing Modular Programs for Pharmaceutical Applications

A modular program is a program divided into smaller, independent functions, each responsible for a particular task.

For example, a pharmaceutical application may contain separate functions for calculating BMI, calculating a medicine's total cost, and converting units.

Modular programming offers several advantages:

  • Reusability: Functions can be used repeatedly.

  • Readability: Each function performs a specific task.

  • Testing: Individual functions can be tested separately.

  • Maintenance: Changes to one function can be made without rewriting the entire program.

2.9.1 Pharmaceutical Application: BMI Calculation

Body Mass Index (BMI) is calculated using body weight in kilograms and height in metres.

Python program

def calculate_bmi(weight, height):
    bmi = weight / (height ** 2)
    return bmi

weight = 60
height = 1.65

result = calculate_bmi(weight, height)

print("Weight:", weight, "kg")
print("Height:", height, "m")
print("BMI:", round(result, 2))

Output:

Weight: 60 kg
Height: 1.65 m
BMI: 22.04

Explanation

  1. The function calculate_bmi() accepts weight and height as parameters.

  2. The arguments 60 and 1.65 are passed to the function.

  3. The function calculates BMI using the formula.

  4. The return statement sends the calculated result back.

  5. The returned value is stored in result and displayed.

The function can be reused for different weight and height values without changing its definition.

Note: This is a programming example. BMI alone is not sufficient to assess an individual's health, and interpretation depends on age and clinical context.

2.9.2 Pharmaceutical Application: Weight-Based Dosage Calculation

In pharmacy, some medication doses are calculated based on the patient's body weight. In such cases, the dose per kilogram (kg) is multiplied by the patient's body weight to calculate the total dose.

Formula

Dosage = Body Weight × Dose per kg

Python program

def calculate_dosage(weight, dose_per_kg):
    dosage = weight * dose_per_kg
    return dosage

# Example values for learning
body_weight = 20  # kg
dose_per_kg = 10  # mg/kg

total_dosage = calculate_dosage(body_weight, dose_per_kg)

print("Body Weight:", body_weight, "kg")
print("Dose per kg:", dose_per_kg, "mg/kg")
print("Calculated Dosage:", total_dosage, "mg")

Output:

Body Weight: 20 kg
Dose per kg: 10 mg/kg
Calculated Dosage: 200 mg

Explanation

  1. calculate_dosage() defines a reusable function.

  2. weight and dose_per_kg are the parameters.

  3. 20 and 10 are the arguments passed to the function.

  4. Python multiplies body weight by the dose per kilogram.

  5. return dosage sends the calculated result back to the calling code.

  6. The returned value is stored in total_dosage and displayed.

Key concepts demonstrated

  • Function: calculate_dosage()

  • Parameters: weight, dose_per_kg

  • Arguments: 20, 10

  • Return value: 200 mg

2.10 Key Takeaways

  • Control structures determine the order in which statements are executed in a Python program.

  • Conditional statements (if, if-else, and if-elif-else) allow programs to make decisions based on specified conditions.

  • Nested if statements allow one condition to be checked inside another condition.

  • Loops are used to execute a block of code repeatedly.

  • The for loop is useful for iterating over a sequence or repeating a task a specified number of times.

  • The range() function generates a sequence of numbers commonly used with for loops.

  • The while loop repeats a block of code as long as a condition remains True. Care must be taken to avoid infinite loops.

  • The break statement immediately terminates the current loop.

  • The continue statement skips the remaining statements in the current iteration and proceeds to the next iteration.

  • Functions are reusable blocks of code designed to perform specific tasks.

  • The def keyword is used to define a function, and the function name followed by parentheses is used to call it.

  • Parameters receive values in a function definition, while arguments are the values passed when calling the function.

  • The return statement sends a result from a function back to the calling code.

  • Functions and control structures can be combined to develop modular Python programs for pharmaceutical applications, such as BMI calculation, medicine cost estimation, and illustrative weight-based dosage calculations.

Chapter 2 – Conclusion

In this chapter, we explored the fundamental concepts of control structures and functions in Python programming. Conditional statements such as if, if-else, and if-elif-else enable programs to make decisions based on specified conditions. The for and while loops allow repetitive tasks to be performed efficiently, while the break and continue statements provide greater control over loop execution.

We also learned how to define and call functions, use parameters and arguments to pass information, and return values for further processing. By combining these concepts, we can develop simple, modular Python programs for pharmaceutical applications, including weight-based dosage calculations, BMI calculations, and medicine cost estimation.

These concepts provide a foundation for developing more organized and reusable programs for pharmacy practice, healthcare data processing, and pharmaceutical calculations. Students should practise writing and testing programs to strengthen their understanding of Python programming and its applications in pharmacy.



Comments

Popular posts from this blog

Unit 1 | BP101T | Basic of Python Programming for Pharmaceutical sciences