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


1.1 Introduction to Programming

Programming is the process of writing a set of instructions that tells a computer how to perform a particular task. These instructions are written using a programming language.

A computer does not understand ordinary human language directly. Therefore, programming languages are used to communicate instructions to a computer in a structured form.

A program is a collection of instructions written to perform a specific task.

For example, a simple Python program can be used to calculate the dose of a medicine based on the patient's body weight:

weight = 60
dose_per_kg = 1000
dose = weight * dose_per_kg
print("Required dose:", dose, "mg")
In this example, the program calculates the required dose by multiplying the patient's weight by the dose required per kilogram.

Programming is widely used in areas such as healthcare, pharmaceutical research, data analysis, artificial intelligence, and scientific computing.

1.2 Programming Languages

A programming language is a formal language used to write instructions that can be understood and executed by a computer.

Programming languages allow humans to communicate with computers and develop software and applications.

Some commonly used programming languages are:

  • Python

  • C

  • C++

  • Java

  • JavaScript

  • R

Programming languages can be broadly classified into low-level languages and high-level languages.

Low-Level Languages

Low-level languages are closely related to the hardware and provide greater control over the computer's resources. They are generally more difficult for beginners to learn.

Examples include:

  • Machine language

  • Assembly language

High-Level Languages

High-level programming languages are designed to be easier for humans to read, write, and understand. They use instructions and syntax that are relatively closer to human language.

Examples include:

  • Python

  • Java

  • C++

  • R

Python is a high-level programming language.

1.3 Introduction to Python

Python is a high-level, general-purpose programming language known for its simple and readable syntax.

It is widely used in:

  • Data analysis

  • Scientific computing

  • Artificial intelligence

  • Machine learning

  • Automation

  • Web development

  • Software development

Python is also extensively used in education and research because its syntax is relatively simple and easy to understand.

1.4 Brief History of Python

Python was created by Guido van Rossum, a Dutch programmer.

The development of Python began in the late 1980s, and the first public release of Python was made in 1991.

Python was designed with an emphasis on simplicity, readability, and ease of use. The name Python was inspired by the British comedy group Monty Python, rather than the snake.

Over the years, Python has developed into one of the most widely used programming languages.

Major Milestones

Year

Development

1989

Development of Python began

1991

Python was first publicly released

2000

Python 2.0 was released

2008

Python 3.0 was released

Present

Python continues to be widely used in science, education, data analysis, AI, and software development

Python 3 is the modern version of Python and is the version generally used for current programming and educational purposes.

1.5 Features of Python

Python has several features that make it suitable for beginners as well as professional programmers.

1. Simple and Easy to Learn

Python has a relatively simple syntax compared with many other programming languages. This makes it suitable for students who are learning programming for the first time.

2. Readable Syntax

Python code is designed to be easy to read and understand.

For example:

print("Hello, World!")

The purpose of the statement can be understood easily even by a beginner.

3. High-Level Language

Python is a high-level programming language. Programmers do not need to deal directly with many low-level hardware operations.

4. Interpreted Language

Python programs are executed by the Python interpreter. This allows Python code to be run without first compiling the entire program into machine code in the traditional way.

5. General-Purpose Language

Python is not restricted to one particular field. It can be used for:

  • Data analysis

  • Scientific computing

  • Web development

  • Automation

  • Artificial intelligence

  • Machine learning

  • Software development

6. Dynamically Typed

In Python, the programmer does not usually need to specify the data type of a variable when creating it.

For example:

age = 20
name = "Rahul"

Python determines the appropriate type based on the value assigned.

7. Large Standard Library

Python provides a large collection of built-in modules and libraries that can be used for different programming tasks.

8. Large Collection of Third-Party Libraries

Python has a large ecosystem of third-party libraries.

Some important libraries used in scientific and pharmaceutical applications include:

  • NumPy – numerical calculations

  • Pandas – data analysis and data handling

  • Matplotlib – data visualization

  • SciPy – scientific computing

  • Scikit-learn – machine learning

9. Cross-Platform

Python programs can generally be developed and executed on different operating systems, including:

  • Windows

  • macOS

  • Linux

10. Open Source

Python is open-source software and can be downloaded and used without purchasing a commercial license.

11. Supports Multiple Programming Approaches

Python supports different programming approaches, including procedural, object-oriented, and functional programming.

1.6 Limitations of Python

Although Python has many advantages, it also has some limitations.

1. Slower Execution Speed

Python can be slower than some compiled programming languages such as C and C++ for certain computationally intensive tasks.

2. Higher Memory Usage

Python programs may require more memory compared with some lower-level languages.

3. Not Ideal for Some Mobile Applications

Python is not generally the first choice for developing native mobile applications for platforms such as Android and iOS.

4. Runtime Errors

Because Python is dynamically typed and interpreted, some errors may only become apparent when the relevant part of the program is executed.

5. Limitations in Low-Level Programming

Python provides less direct control over hardware compared with low-level languages such as C.

6. Dependency on Libraries and Environment

Some Python applications require external libraries and a properly configured Python environment. Managing different library versions can sometimes be challenging.

These limitations do not prevent Python from being widely used. For applications such as data analysis, scientific computing, machine learning, and pharmaceutical data processing, Python remains a highly useful language.

1.7 Applications of Python in Pharmacy

Programming is becoming increasingly important in pharmaceutical education, research, and industry.

Python can be applied to various pharmaceutical and healthcare-related tasks.

Dose Calculation

Python can be used to perform calculations such as dose based on body weight.

BMI Calculation

Programs can calculate a patient's Body Mass Index using height and weight.

Pharmaceutical Data Analysis

Python can process and analyze experimental, clinical, and pharmaceutical datasets.

Data Visualization

Graphs and charts can be created to represent experimental results and healthcare data.

Pharmacokinetic Calculations

Python can be used to perform mathematical calculations related to pharmacokinetic parameters.

Drug Discovery

Python is increasingly used in computational drug discovery and molecular data analysis.

Artificial Intelligence and Machine Learning

Python is one of the most commonly used languages for developing machine learning and artificial intelligence applications.

These technologies can be applied to areas such as:

  • Drug discovery

  • Disease prediction

  • Medical data analysis

  • Drug response prediction

  • Healthcare decision support

1.8 Installing Python

Before writing and executing Python programs, Python must be installed on the computer.

Python can be downloaded from the official Python website.

During installation, the Python interpreter and other necessary components are installed on the computer.

Python Interpreter

The Python interpreter is the software responsible for executing Python code.

For example, when the following code is written:

print("Hello, World!")

the Python interpreter processes the instruction and produces:

Hello, World!

Therefore, installing Python provides the basic environment required to execute Python programs.

Checking Python Installation

After installation, the Python version can be checked using the command line or terminal.

On many systems, the following command can be used:

python --version

On systems where Python 3 is accessed using

python3 --version

The installed Python version will then be displayed.

1.9 Integrated Development Environment (IDE)

An Integrated Development Environment (IDE) is a software application that provides a collection of tools for writing, running, testing, and debugging programs.

Instead of using separate applications for different programming tasks, an IDE brings several useful tools together in a single environment.

Common environments used for Python programming include:

  • Jupyter Notebook

  • PyCharm

  • Visual Studio Code (VS Code)

Jupyter Notebook

Jupyter Notebook is an interactive environment in which Python code can be written and executed in separate sections called cells.

It is particularly useful for:

  • Learning Python

  • Data analysis

  • Scientific computing

  • Mathematical calculations

  • Data visualization

One of its major advantages for students is that code can be executed step by step, with the output displayed immediately.

For example:

weight = 60
height = 1.70

bmi = weight / (height ** 2)

print(bmi)
The output appears directly below the cell containing the code.

PyCharm

PyCharm is a Python-focused development environment that provides tools for writing and developing Python programs.

It provides features such as:

  • Code completion

  • Error detection

  • Debugging

  • Project management

  • Code navigation

  • Python environment management

PyCharm is particularly useful when working on larger Python projects.

Visual Studio Code (VS Code)

Visual Studio Code, commonly known as VS Code, is a lightweight source-code editor developed by Microsoft.

With suitable extensions, VS Code can provide many features associated with an IDE, including:

  • Python code editing

  • Code completion

  • Debugging

  • Integrated terminal

  • Extensions

  • Project management

1.10 Text Editors

A text editor is software primarily designed for creating and editing text files.

Examples include:

  • Notepad

  • TextEdit

  • Sublime Text

Python code can be written in a text editor and saved with the .py extension. However, a basic text editor may not provide many of the tools required for efficient software development.

1.11 Advantages of IDEs Over Text Editors

IDEs provide several additional features that make programming easier and more efficient.

Feature

                Text Editr

IDE

Writing code

Allows you to type and edit program code.

Allows you to write and edit code along with providing additional programming tools.

Code completion



Usually, the programmer has to type most of the code manually.

Suggests keywords, functions, variables, and other code elements while typing.

Error detection

Basic text editors generally do not identify programming errors.

Can identify many syntax errors and other problems while writing the program.

Running programs



The program usually needs to be run separately using a terminal or another program.

The program can usually be run directly from the development environment.

Debugging



Usually does not provide built-in debugging tools.

Provides debugging tools to help find and correct errors in a program.

Project management



Mainly used for editing individual files.

Helps organize multiple files, folders, and other components of a programming project.

Code navigation



Finding and moving between different parts of a large program may be more difficult.

Provides features that make it easier to find functions, variables, files, and different parts of the program.

Terminal and other tools



Usually requires separate applications or tools for tasks such as running commands.

Often provides a terminal and other useful programming tools within the same application.

Major Advantages

Code Completion:
IDEs can automatically suggest keywords, functions, variables, and other programming elements.

Error Detection:
Many IDEs identify syntax errors and other problems while the programmer is writing code.

Debugging:
Debugging tools help programmers identify and correct errors in their programs.

Integrated Execution:
Programs can often be executed directly from the development environment.

Project Management:
Multiple files and folders belonging to a project can be organized within the same environment.

Code Navigation:
IDEs make it easier to move between different parts of a program and locate functions, variables, and files.

1.12 Python Development Environment

To begin Python programming, the basic setup generally consists of:

Python → Python Interpreter → Development Environment → Python Program

A student can install Python and then use an appropriate development environment such as Jupyter Notebook, PyCharm, or VS Code to write and execute Python programs.

For beginners, Jupyter Notebook is particularly useful for learning Python concepts step by step. VS Code can be used for writing and managing Python programs and projects, while PyCharm provides a more dedicated Python development environment.

1.14 Python Variables

A variable is a name used to store a value in a Python program.

For example:

age = 20

Here, age is the variable and 20 is the value stored in it.

Variables allow us to store information and use that information later in a program.

In pharmacy-related programs, variables can be used to store information such as:

patient_name = "Rahul"
age = 20
weight = 65.5
temperature = 37.2
medicine = "Paracetamol"

Here, different variables store different types of information.

Assigning Values to Variables

The assignment operator = is used to assign a value to a variable.

age = 20
weight = 65.5
medicine = "Paracetamol"

The value on the right side of = is assigned to the variable on the left side.

Variable Naming Rules

The following rules should be followed when naming variables in Python:

  • A variable name can contain letters, numbers, and underscores (_).

  • A variable name must not begin with a number.

  • Spaces are not allowed in variable names.

  • Python variable names are case-sensitive.

  • Python keywords cannot be used as variable names.

Examples of valid variable names:

patient_name = "Rahul"
age = 20
body_weight = 65
medicine1 = "Paracetamol"

Examples of invalid variable names:

2age = 20                #invalid because a variable name cannot start with a number.
patient name = "Rahul" #invalid because spaces are not allowed in variable names.

Case Sensitivity

Python is case-sensitive, which means uppercase and lowercase letters are treated as different.

age = 20
Age = 25

Here, age and Age are two different variables.

1.15 Python Data Types

A data type specifies the type of value stored in a variable.

Python provides several built-in data types. In this chapter, we will focus on four basic data types:

Data Type

Python Keyword

Example

Integer

int

25

Float

float

65.5

String

str

"Paracetamol"

Boolean

bool

True or False

Integer (int)

An integer is a whole number without a decimal point.

Examples:

age = 20
tablets = 10
patients = 50

Here, age, tablets, and patients contain integer values.

Float (float)

A float represents a number containing a decimal point.

Examples:

weight = 65.5
temperature = 37.2
dose = 12.5

Float values are commonly used when greater numerical precision is required.

String (str)

A string is a sequence of characters.

Strings are written inside quotation marks, either single quotes or double quotes.

medicine = "Paracetamol"
patient = 'Rahul'

Both "Paracetamol" and 'Rahul' are strings.

Strings can contain:

  • Letters

  • Numbers

  • Spaces

  • Special characters

For example:

medicine = "Vitamin B12"

Although B12 contains a number, the entire value is a string because it is enclosed in quotation marks.

Boolean (bool)

A Boolean data type represents one of two logical values:

True

False

For example:

is_available = True

Here, is_available indicates whether a medicine is available.

Boolean values are particularly useful when making decisions in a program.

Checking the Data Type

The type() function can be used to determine the data type of a value.

Example 1:

age = 20
print(type(age))

Output:

<class 'int'>

Similarly: Example 2:

medicine = "Paracetamol"
print(type(medicine))

Output:

<class 'str'>

1.16 Type Casting

Type casting is the process of converting a value from one data type to another.

Python provides built-in functions for performing type casting.

Function

Conversion

int()

Converts a value to integer

float()

Converts a value to float

str()

Converts a value to string

bool()

Converts a value to Boolean

Converting Integer to Float

An integer can be converted into a float using the built-in float() function.

age = 20
age_float = float(age)
print(age_float)

Output:

20.0


Explanation:
  • age = 20 stores the integer value 20 in the variable age.
  • float(age) converts the integer 20 into a floating-point number.
  • The converted value is stored in age_float.
  • Therefore, print(age_float) displays 20.0.
  • Notice that .0 is added to the number, indicating that 20.0 is a float, not an integer.

Converting Float to Integer

A float can be converted into an integer using the built-in int() function.

weight = 65.8
weight_int = int(weight)
print(weight_int)

Output:

65

The decimal portion is removed; the value is not rounded.

Explanation:
  • weight = 65.8 stores the floating-point value 65.8 in the variable weight
  • int(weight) converts the float 65.8 into an integer.
  • The converted value is stored in weight_int.
  • When converting a float to an integer using int(), the decimal portion is removed.
  • The value is not rounded. Therefore, 65.8 becomes 65, not 66.

Converting String to Integer

A string containing a numeric value can be converted into an integer using the built-in int() function.

Example 1:

age = "20"
age = int(age)
print(age)
print(type(age))

Output:

20
<class 'int'>

The string "20" is converted into the integer 20.

Explanation:
  • age = "20" stores 20 as a string because it is enclosed in quotation marks.
  • int(age) converts the string "20" into the integer 20
  • The converted value is assigned back to the variable age
  • print(age) displays the value 20.
  • type(age) confirms that the value is now of type int
Example 2:
age = "twenty"
age = int(age)
print(age)
print(type(age))

Output:

ValueError: invalid literal for int() with base 10: 'twenty'

Explanation:

    • age = "twenty" stores the word "twenty" as a string.
    • int(age) attempts to convert the string "twenty" into an integer.
    • However, "twenty" is a word and does not represent an integer in a format Python can convert using int().
    • Therefore, Python raises a ValueError.

    Remember: int() can convert "20" into 20, but it cannot convert "twenty" into 20.

    Converting Number to String

    age = 20
    age_text = str(age)
    print(age_text)
    print(type(age))

    Output:

    20

    The integer 20 is converted into the string "20".

    Explanation:
    • age = 20 stores the value 20 as an integer.
    • str(age) converts the integer 20 into the string "20".
    • The converted value is stored in the variable age_text.
    • print(age_text) displays 20.
    • type(age_text) confirms that the converted value is of type str (string).
    Note: Although both 20 and "20" appear similar when printed, they are different data types.
    20 is an integer, whereas "20" is a string.

    1.17 Input and Output Operations

    Programs often need to receive information from the user and display results to the user.

    Python provides:

    • input() for receiving input from the user

    • print() for displaying output on the screen

    Output Using print()

    The print() function is used to display information on the screen.

    print("Welcome to Python")

    Output:

    Welcome to Python

    Displaying Variables

    Variables can also be displayed using the print() function.

    medicine = "Paracetamol"
    print(medicine)

    Output:

    Paracetamol

    Displaying Multiple Values

    Multiple values can be displayed using a single print() statement. By default, Python separates multiple values
    with a space.

    medicine = "Paracetamol"
    dose = 500
    print(medicine, dose)

    Output:

    Paracetamol 500

    Input Using input()

    The input() function is used to obtain information from the user during program execution.
    name = input("Enter patient name: ")
    print(name)

    When the program runs, it displays:

    Enter patient name: 

    The user can then enter the patient's name. For example:

    Enter patient name: Zara
    Zara

    How Does input() Work?

    The text written inside the parentheses of input() is called a prompt. It tells the user what information they
    should enter.
    In the following example:
    name = input("Enter patient name: ")
    • "Enter patient name: " is the prompt displayed to the user.

    • The value entered by the user is received by input.
    • The entered value is stored in the variable name.

    Important Point: input() Returns a String
    A very important feature of input() is that the value returned by input() is a string by default, regardless of
    whether the user enters text or a number.

    For example:

    age = input("Enter your age: ")
    print(type(age))

    If the user enters:
    20

    The output will be: Although the user entered 20, Python initially treats it as the string "20".

    <class 'str'>

    Although the user entered 20, Python initially treats it as the string "20".


    Why Is Type Conversion Required?

    If we want to perform mathematical calculations using a value obtained through input(), we need to convert it into the appropriate numerical data type.

    For example:

    age = int(input("Enter your age: "))

    Here, the input is first received as a string and then converted into an integer using int().

    The process can be understood as:

    ----

    Similarly, a decimal value can be converted into a float:

    weight = float(input("Enter your weight in kg: "))

    If the user enters 65.5, the value stored in weight will be the float 65.5.

    Example: Taking Patient Details as Input

    A simple pharmaceutical application can be used to demonstrate input and output operations.

    patient_name = input("Enter patient name: ")
    age = int(input("Enter patient age: "))
    weight = float(input("Enter patient weight (kg): "))
    
    print("Patient Name:", patient_name)
    print("Age:", age)
    print("Weight:", weight, "kg")

    Sample Output:

    Enter patient name: Rahul
    Enter patient age: 20
    Enter patient weight (kg): 65.5
    
    Patient Name: Rahul
    Age: 20
    Weight: 65.5 kg

    1.18 Basic Python Operators

    Operators are symbols or keywords used to perform operations on values and variables.

    For example:

    a = 10
    b = 20
    
    result = a + b
    print(result)

    Output:

    30

    Here, + is the operator, while a and b are the operands.

    The basic operators covered in this chapter are:

    1. Arithmetic operators
    2. Comparison operators
    3. Logical operators

    1.18.1 Arithmetic Operators

    Arithmetic operators are used to perform mathematical calculations such as addition, subtraction, multiplication, and division.

    Operator

    Operation

    Example

    Result

    +

    Addition

    10 + 5

    15

    -

    Subtraction

    10 - 5

    5

    *

    Multiplication

    10 * 5

    50

    /

    Division

    10 / 5

    2.0

    %

    Modulus

    10 % 3

    1

    //

    Floor division

    10 // 3

    3

    **

    Exponentiation

    2 ** 3

    8

    Addition

    The +  operator is used to add two values.
    a = 10
    b = 5
    
    result = a + b
    print(result)

    Output:

    15

    Subtraction

    The -  operator is used to subtract one value from another.
    a = 10
    b = 5
    
    result = a - b
    print(result)

    Output:

    5

    Multiplication

    The *  operator is used to multiply two values.

    a = 10
    b = 5
    
    result = a * b
    print(result)

    Output:

    50

    Division

    The /  operator is used to divide one value by another.

    result = 10 / 5
    print(result)

    Output:

    2.0
    Important: In Python, the / operator returns a floating-point result. Therefore, 10 / 5 gives 2.0 rather than 2.

    Modulus

    The % operator is called the modulus operator. It returns the remainder after division.
    result = 10 % 3
    print(result)

    Output:

    1

    Here, 10 divided by 3 leaves a remainder of 1.

    Floor Division

    The //  operator is called the floor division operator. It returns the quotient after floor division.

    result = 10 // 3
    print(result)

    Output:

    3

    Exponentiation

    The ** operator is used to raise a number to a particular power.

    result = 2 ** 3
    print(result)

    Output:

    8

    This means:: 2 × 2 × 2 = 8

    Pharmacy Example: Dose Calculation

    Arithmetic operators can be used to perform simple calculations related to pharmacy.

    Suppose a medicine is prescribed at 10 mg per kg of body weight, and the patient's weight is 60 kg.

    weight = 60
    dose_per_kg = 10
    
    dose = weight * dose_per_kg
    
    print(dose)

    Output:

    600

    Explanation:

    • weight stores the patient's weight as 60 kg.
    • dose_per_kg stores the required dose as 10 mg/kg.
    • The * operator multiplies the patient's weight by the dose per kg.
    • The calculated dose is stored in the variable dose.
    • print() displays the result.

    Therefore:

    60 kg × 10 mg/kg = 600 mg

    Note: This example demonstrates Python arithmetic only. Actual medication dosing must always be based on an appropriate clinical prescription or validated dosing guideline.

    1.18.2 Comparison Operators

    Comparison operators are used to compare two values.

    The result of a comparison is always a Boolean value, either True or False.

    Operator

    Meaning

    Example

    ==

    Equal to

    10 == 10

    !=

    Not equal to

    10 != 5

    >

    Greater than

    10 > 5

    <

    Less than

    5 < 10

    >=

    Greater than or equal to

    10 >= 10

    <=

    Less than or equal to

    5 <= 10

    For example:

    age = 20
    print(age >= 18)

    Output:

    True
    Here, Python checks whether age is greater than or equal to 18. Since 20 satisfies this condition, the
    result is True.

    Important: = and == are Different

    Beginners often confuse = and ==.

    • = is used for assignment.
    • == is used for comparison.

    Consider: 

    age = 20

    Here, 20 is assigned to the variable age.

    But:

    age == 20

    checks whether the value of age is equal to 20.

    For example:

    age = 20
    print(age == 20)

    Output:

    True

    1.18.3 Logical Operators

    Logical operators are used to combine or modify conditions.

    Python provides three logical operators:

    Operator

    Description

    and

    Returns True when both conditions are True

    or

    Returns True when at least one condition is True

    not

    Reverses the logical result

    and Operator

    The and operator returns True only when both conditions are true.

    If even one condition is false, the final result is False.

    Example:

    age = 20 
    weight = 60

    print(age >= 18 and weight >= 50)

    Output:

    True

    Here:

    • age >= 18 → True
    • weight >= 50 → True

    Since both conditions are True, the final result is True.

    Understanding all possible cases

    Consider

    age = 30 
    weight = 50

    Case

    First Condition

    Second Condition

    Output

    Both conditions satisfied

    age >= 18 → True

    weight >= 50 → True

    True

    Only age condition satisfied

    age >= 18 → True

    weight < 50 → False

    False

    Only weight condition satisfied

    age < 18 → False

    weight >= 50 → True

    False

    Neither condition satisfied

    age < 18 → False

    weight < 50 → False

    False

    Therefore, remember:

    and → Both conditions must be True to get True.

    or Operator

    The or operator returns True when at least one condition is true.

    It returns False only when both conditions are false.

    Example:

    age = 20 
    print(age < 18 or age > 60)

    Output:

    False

    Here:

    • age < 18 → False
    • age > 60 → False

    Since both conditions are False, the final result is False.

    Understanding all possible cases

    Consider

    age = 30 
    weight = 50

    Case

    First Condition

    Second Condition

    Output

    Both conditions satisfied

    age >= 18 → True

    weight >= 50 → True

    True

    Only age condition satisfied

    age >= 18 → True

    weight < 50 → False

    True

    Only weight condition satisfied

    age < 18 → False

    weight >= 50 → True

    True

    Neither condition satisfied

    age < 18 → False

    weight < 50 → False

    False

    Therefore, remember:

    or → At least one condition must be True to get True.

    not Operator

    The not operator reverses the Boolean result.

    Understanding all possible cases

    Unlike and & or, the not operator works with one condition at a time.

    Consider

    age = 30 

    Case

    Condition

    Result of Condition

    Output with not

    Condition is true

    age >= 18

    True

    False

    Condition is false

    age < 18

    False

    True

    Therefore, remember:

    not → Reverses the result of a condition: True becomes False, and False becomes True.

    1.18.4 Writing Comments in Python

    Python uses the hash symbol (#) to write ordinary comments. Comments help explain code and are ignored during normal program execution.

    Example:

    # Store the name of a medicine
    medicine = "Paracetamol"
    
    # Display the medicine name
    print(medicine)

    Output:

    Paracetamol

    1.19 Basic String Operations and Manipulation Techniques

    Strings are one of the most commonly used data types in Python. A string is a sequence of characters, including letters, numbers, spaces, and special symbols. Strings are used to store and manipulate textual information in a Python program. In Python, strings are enclosed within single quotation marks (' '), double quotation marks (" "), or triple quotation marks (''' ''' or """ """).

    In pharmacy applications, strings can be used to store:

    • Patient names

    • Medicine names

    • Disease names

    • Blood groups

    • Doctor names

    • Hospital names

    • Prescription details

    For example:

    patient_name = "Anu"

    medicine = "Paracetamol"

    blood_group = "O+"

    Here, patient_name, medicine, and blood_group contain string values.

    Pharmaceutical significance: Strings help represent textual data in pharmacy-related software, such as patient registration systems, medicine inventory management, prescription processing, and pharmacy databases.

    1.19.1 Creating a String

    In Python, strings can be created using single quotes (' ') or double quotes (" ") or Triple quotes                (''' ''' or """ """) .

    1. Single quotes (' ') – commonly used for single-line strings.

    2. Double quotes (" ") – commonly used for single-line strings.

    3. Triple quotes (''' ''' or """ """) – used for multiline strings and docstrings

    For example:

    name = "Anu"

    medicine = 'Paracetamol'


    print(name) print(medicine)

    Output:

    Anu
    Paracetamol

    Explanation:

    • name stores the string "Anu", enclosed in double quotes.

    • medicine stores the string 'Paracetamol', enclosed in single quotes.

    • The print() function displays the stored values.

    Both single quotes and double quotes are valid for creating strings in Python. They produce the same type of data.

    Note: Triple-quoted strings can span multiple lines. They are also used for docstrings, which describe the purpose of functions, classes, and modules. For ordinary comments, Python uses the # symbol.

    For example:

    text = """Python is easy to learn. Python is useful in pharmacy.""" print(text)

    Output:

    Python is easy to learn.
    Python is useful in pharmacy.

    Explanation: Triple quotes (""" """) allow us to write a string across multiple lines.

    1.19.2 String with Numbers

    In Python, numbers written inside quotation marks are treated as strings, not as numerical values.

    Example:

    age = "20"

    Here, 20 is stored as a string because it is enclosed in quotation marks.

    Compare this with:

    age = 20

    Here, 20 is stored as an integer because it is not enclosed in quotation marks.

    Example:

    age1 = 20
    age2 = "20"
    
    print(type(age1))
    print(type(age2))

    Output:

    <class 'int'>
    <class 'str'>

    Explanation:

    • age1 = 20 stores an integer value.

    • age2 = "20" stores a string value.

    • The type() function is used to identify the data type of a variable.

    • int represents an integer, while str represents a string

    Key Point: Quotation marks make a numerical-looking value a string rather than an integer.

    1.19.3 Accessing Characters in a String

    Each character in a string has a position called an index. Python uses index numbers starting from 0.

    Consider the following string:

    medicine = "Tablet"

    Each character in the string has a corresponding index, as shown below.

    Character                  T            a            b            l            e            t   
    Index                          0            1            2           3            4            5

    Example 1: Accessing the First Character
    medicine = "Tablet"
    print(medicine[0])

    Output:

    T

    Explanation: The index 0 accesses the first character, T.

    Example 2: Accessing a Specific Character

    medicine = "Tablet"
    print(medicine[3])

    Output:

    l

    Explanation: The index 3 accesses the fourth character, l.

    Pharmacy Example

    medicine = "Aspirin"
    print(medicine[0])
    print(medicine[2])

    Output:

    A
    p

    Explanation:

    • medicine[0] returns A, the first character.

    • medicine[2] returns p, the third character.

    Important Point

    Python string indexing starts from 0, not 1.

    The first character has index 0, the second has index 1, and so on.

    1.19.4 Negative Indexing

    Python allows us to access characters from the end of a string using negative indexes.

    Consider the following string:

    medicine = "Tablet"

    The characters and their positive and negative indexes are shown below.

    Character                  T            a            b            l            e            t   
           Positive Index                          0            1            2           3            4            5
          Negative Index                        -6           -5          -4          -3           -2           -1

    Example 1: Accessing the Last Character

    medicine = "Tablet"
    print(medicine[-1])

    Output:

    t

    Explanation: The index -1 accesses the last character of the string, which is t.

    Example 2: Accessing Another Character from the End

    medicine = "Tablet"
    print(medicine[-3])

    Output:

    l


    Explanation: The index -3 accesses the third character from the end, which is l.

    Important Points

    • Positive indexing starts from 0 at the beginning of a string.

    • Negative indexing starts from -1 at the end of a string.

    • The last character can be accessed using index -1.

    • Negative indexing is useful when we need to access characters from the end without knowing the string's length.

    1.19.5 String Slicing

    String slicing is used to extract a part of a string by specifying a range of index positions.

    Syntax

    string[start:end]
    • Start index: The position from which slicing begins. This index is included.

    • End index: The position where slicing stops. This index is not included.

    Consider the following string:

    medicine = "Paracetamol"

    Example 1: Extracting the First Four Characters

    medicine = "Paracetamol"
    print(medicine[0:4])

    Output:

    Para

    Explanation:

    • Start index = 0

    • End index = 4
    • Characters at indexes 0, 1, 2, 3 are selected.

    • The character at index 4 is not included.

    Example 2: Extracting a Part of the Medicine Name

    medicine = "Paracetamol"
    print(medicine[4:8])

    Output:

    ceta

    Important Point

    In Python slicing, the start index is included, but the end index is excluded.

    String slicing is useful for extracting specific portions of text, such as parts of medicine names or codes, in pharmacy-related applications.

    1.19.6 Omitting Start or End Index in String Slicing

    In Python, we can omit the start index or end index while slicing a string. Python automatically uses the beginning or end of the string when an index is omitted.

    Consider the following string:

    medicine = "Paracetamol"

    Slicing from the Beginning

    If the start index is omitted, Python starts slicing from the beginning of the string.

    Example:

    medicine = "Paracetamol"
    print(medicine[:4])

    Output:

    Para

    Explanation:

    • The start index is omitted, so slicing begins at index 0.

    • The end index is 4, which is not included.

    • Characters at indexes 0, 1, 2, 3 are selected.

    Slicing Until the End

    If the end index is omitted, Python continues slicing until the end of the string.

    Example:

    medicine = "Paracetamol"
    print(medicine[4:])

    Output:

    etamol

    Explanation:

    • The start index is 4.

    • The end index is omitted, so slicing continues to the end of the string.

    Slicing the Complete String

    If both the start and end indexes are omitted, Python returns the complete string.

    Example:

    medicine = "Paracetamol"
    print(medicine[:])

    Output:

    Paracetamol

    Explanation: The expression medicine[:] selects the entire string from beginning to end.

    Important Points

    • string[:end] extracts characters from the beginning up to, but not including, the end index.

    • string[start:] extracts characters from the start index to the end of the string.

    • string[:] extracts the complete string.

    Pharmacy Example: Slicing can be used to extract a portion of a medicine name or a code stored as a string.

    1.19.7 String Length – len()

    The len() function in Python is used to find the total number of characters in a string.

    It counts letters, numbers, spaces, and special characters present in the string.

    Example 1: Finding the Length of a Medicine Name

    medicine = "Paracetamol"
    print(len(medicine))

    Output:

    11

    Explanation: The word "Paracetamol" contains 11 characters. Therefore, len(medicine) returns 11.

    Example 2: Finding the Length of a Name with a Space

    name = "Anu Kumar"
    print(len(name))

    Output:

    9

    Explanation:

    • Anu contains 3 letters.

    • Kumar contains 5 letters.

    • The space between the two words counts as 1 character.

    Therefore, the total length is (3 + 1 + 5 = 9) characters.

    Important Points

    • The len() function returns the total number of characters in a string.

    • Spaces are counted as characters.

    • Indexing starts from 0, but the length returned by len() gives the total count of characters.

    Remember: len() counts characters; it does not return the last index. For a non-empty string, the last positive index is len(string) - 1.

    1.19.8 String Concatenation – Joining Strings

    String concatenation means joining two or more strings together to form a single string.

    In Python, the + operator is used to concatenate strings.

    Example 1: Joining Two Strings

    first_name = "Anu"
    last_name = "Kumar"
    full_name = first_name + " " + last_name print(full_name)

    Output:

    Anu Kumar

    Explanation:

    • first_name stores the string "Anu".

    • last_name stores the string "Kumar".

    • The + operator joins the strings.

    • " " adds a space between the first name and the last name

    Example 2: Pharmacy Application

    medicine = "Paracetamol"
    strength = "500 mg"
    
    medicine_details = medicine + " " + strength
    
    print(medicine_details)

    Output:

    Paracetamol 500 mg

    Explanation:

    The + operator joins the medicine name, a space, and the strength to create the complete medicine description.

    Important Points

    • The + operator joins strings together.

    • Use quotation marks around a space (" ") when a space is required between strings.

    • The + operator cannot directly concatenate a string and an integer. The integer must first be converted to a string using str().

    medicine = "Paracetamol"
    quantity = 10
    
    print(medicine + " " + str(quantity))

    Output:

    Paracetamol 10

    Here, str(quantity) converts the integer 10 into a string before concatenation.

    1.19.9 Repeating a String

    In Python, the * operator is used to repeat a string a specified number of times.

    The number multiplied by the string determines how many times the string is repeated.

    Example 1: Repeating a String

    print("Rx " * 3)

    Output:

    Rx Rx Rx

    Explanation:

    • "Rx " is the string to be repeated.

    • * 3 repeats the string three times.

    • The space after Rx separates the repeated text.

    Example 2: Pharmacy Example

    print("Take medicine - " * 3)Output:

    Output:

    Take medicine - Take medicine - Take medicine -

    Important Points:

    • The * operator repeats a string according to the specified number.

    • Multiplying a string by 0 produces an empty string.

    • The repetition count must be an integer.

    Remember: The + operator joins strings, whereas the * operator repeats strings.

    1.19.10 Changing the Case of a String

    Python provides several built-in string methods to change the case of letters in a string. These methods are useful for formatting names, medicine names, and other textual information.

    upper() Method

    The upper() method converts all lowercase letters in a string to uppercase.

    Example:

    medicine = "paracetamol"
    
    print(medicine.upper())

    Output:

    PARACETAMOL

    Explanation: The upper() method converts all letters in the string to uppercase.

    lower() Method

    The lower() method converts all uppercase letters in a string to lowercase.

    Example:

    medicine = "paracetamol"
    
    print(medicine.lower())

    Output:

    paracetamol

    Explanation: The lower() method converts all letters in the string to lowercase.

    capitalize() Method

    The capitalize() method converts the first character of a string to uppercase and the remaining characters to lowercase.

    Example:

    name = "ANU"
    
    print(name.capitalize())

    Output:

    Anu

    Explanation: The first letter A remains uppercase, while the remaining letters are converted to lowercase.

    title() Method

    The title() method converts the first letter of each word to uppercase and the remaining letters of each word to lowercase.

    Example:

    patient_name = "anu kumar"
    
    print(patient_name.title())

    Output:

    Anu Kumar

    Explanation: The first letter of both anu and kumar is converted to uppercase.

    1.19.11 Removing Extra Spaces – strip()

    The strip() method removes whitespace characters, such as spaces, from the beginning and end of a string. It does not remove spaces between words.

    Example 1: Removing Extra Spaces

    name = "   Anu   "
    
    print(name.strip())

    Output:

    Anu

    Explanation: The strip() method removes the extra spaces before and after the name "Anu".

    Example 2: Using strip() with User Input

    The strip() method is useful when accepting information from users because they may accidentally enter extra spaces while typing.

    patient_name = input("Enter patient name: ")
    
    patient_name = patient_name.strip()
    
    print(patient_name)

    Sample Input:

        Tom Holland

    Output:

    Tom Holland

    Explanation:

    • The input() function accepts the patient's name from the user.

    • The strip() method removes leading and trailing whitespace.

    • The cleaned name is displayed using print().

    Important Points

    • strip() removes whitespace from both ends of a string.

    • It does not remove spaces between words.

    • It returns a new string and does not modify the original string.

    Pharmacy Application: The strip() method can help clean patient names, medicine names, and other text entered into pharmacy management software.

    1.19.12 Replacing Text – replace()

    The replace() method is used to replace a specified part of a string with another string.

    Syntax

    string.replace(old, new)
    • old – The text to be replaced.

    • new – The replacement text

    Example 1: Replacing a Medicine Name

    medicine = "Paracetamol"
    
    new_medicine = medicine.replace("Paracetamol", "Ibuprofen")
    
    print(new_medicine)

    Output:

    Ibuprofen

    Explanation: The replace() method replaces "Paracetamol" with "Ibuprofen" and returns the modified string.

    Example 2: Replacing the Strength in a Medicine Description

    medicine = "Paracetamol 500 mg"
    
    medicine = medicine.replace("500", "650")
    
    print(medicine)

    Output:

    Paracetamol 650 mg

    Explanation: The text "500" is replaced with "650" in the medicine description.

    Important Points

    • The replace() method returns a new string; it does not modify the original string.

    • If the specified text is not found, the original string is returned unchanged.

    • By default, all occurrences of the specified old text are replaced.

    1.19.13 Finding Text in a String – find()

    The find() method returns the index position of the first occurrence of a specified character or text in a string.

    Syntax

    string.find(substring)

    Example : 

    medicine = "Paracetamol"
    
    print(medicine.find("c"))

    Output:

    4

    Explanation: Python indexing starts from 0. In "Paracetamol", the letter c is at index 4.

    When the Text Is Not Found

    If the specified text is not present, find() returns -1.

    medicine = "Paracetamol"
    
    print(medicine.find("z"))

    Output:

    -1

    Note: The find() method is case-sensitive. For example, "P" and "p" are treated as different characters.

    1.19.14 Checking Whether Text Exists – in

    The in operator checks whether a character or a sequence of characters exists in a string. It returns either True or False.

    Example 1

    medicine = "Paracetamol"
    
    print("Para" in medicine)

    Output:

    True

    Example 2

    medicine = "Paracetamol"
    
    print("Aspirin" in medicine)

    Output:

    False

    Example 3

    medicine = "Paracetamol 500 mg"
    
    print("500" in medicine)

    Output:

    True

    Explanation: The text "500" is present in the medicine description, so Python returns True.

    1.19.15 Checking Whether Text Does Not Exist – not in

    The not in operator checks whether a character or sequence of characters is absent from a string. It returns True if the text is not found and False if it is found.

    Example 1 :

    medicine = "Paracetamol"
    
    print("Aspirin" not in medicine)

    Output:

    True

    Explanation: "Aspirin" does not occur in "Paracetamol", so the expression returns True.

    Example 2 :

    medicine = "Paracetamol"
    
    print("Para" not in medicine)

    Output:

    False

    1.19.16 Counting Characters or Text – count()

    The count() method returns the number of times a specified character or substring occurs in a string.

    Syntax

    string.count(substring)

    Example 1 : 

    medicine = "Paracetamol"
    
    print(medicine.count("a"))

    Output:

    3

    Explanation: The letter "a" occurs three times in "Paracetamol".

    Example 2 :

    medicine = "Tablet, Capsule, tablet"
    
    print(medicine.count("Tablet"))

    Output:

    1

    Explanation: The word "Tablet" appears only once in the string. The second occurrence is "tablet" with a lowercase t. Since Python's count() method is case-sensitive, it treats "Tablet" and "tablet" as different strings.

    Note: The count() method is case-sensitive and counts non-overlapping occurrences.

    1.19.17 Checking the Beginning of a String – startswith()

    The startswith() method checks whether a string begins with a specified character or substring. It returns True or False.

    Syntax

    string.startswith(substring)

    Example 1 : 

    medicine = "Paracetamol"
    
    print(medicine.startswith("Para"))

    Output:

    True

    Example 2 :

    medicine = "Paracetamol"
    
    print(medicine.startswith("Aspi"))

    Output:

    False

    Explanation: "Paracetamol" begins with "Para", not "Aspi".

    1.19.18 Checking the End of a String – endswith()

    The endswith() method checks whether a string ends with a specified character or substring. It returns True or False.

    Syntax

    string.endswith(substring)

    Example 1 : 

    medicine = "Paracetamol"
    
    print(medicine.endswith("mol"))

    Output:

    True

    Explanation: The string "Paracetamol" ends with "mol"

    1.19.19 Splitting a String – split()

    The split() method divides a string into smaller parts and returns them as a list.

    By default, split() separates the string at whitespace, such as spaces.

    Syntax

    string.split(separator)

    The separator is optional. If omitted, Python splits the string using whitespace.

    Example 1 : 

    patient_name = "Anu Kumar"
    
    print(patient_name.split())

    Output:

    ['Anu', 'Kumar']

    Example 2 : Splitting Medicine Names

    medicines = "Paracetamol,Ibuprofen,Aspirin"
    
    print(medicines.split(","))

    Output:

    ['Paracetamol', 'Ibuprofen', 'Aspirin']

    Explanation: The comma , acts as the separator. Python splits the string wherever a comma appears.

    1.19.20 Joining Strings – join()

    The join() method combines multiple strings into a single string using a specified separator.

    Syntax

    separator.join(iterable)

    Here, separator is the text placed between the strings, and iterable is a collection of strings, such as a list or tuple.

    Example 1 : 

    medicines = ["Paracetamol", "Ibuprofen", "Aspirin"]
    
    result = ", ".join(medicines)
    
    print(result)

    Output:

    Paracetamol, Ibuprofen, Aspirin

    Explanation: The separator ", " (comma followed by a space) is placed between each medicine name.

    Example 2 : 

    words = ["Basic", "Python", "Programming"]
    
    print(" ".join(words))

    Output:

    Basic Python Programming

    Explanation: A single space is used to join the words into one string.

    Important Note: The elements being joined must be strings. If a list contains integers or other data types, they must be converted to strings before using join().

    Quick Revision

    Method / Operation

    Purpose

    Example

    len()

    Finds string length

    len("Python")

    upper()

    Converts to uppercase

    "python".upper()

    lower()

    Converts to lowercase

    "PYTHON".lower()

    capitalize()

    Capitalizes first character

    "python".capitalize()

    title()

    Capitalizes each word

    "hello world".title()

    strip()

    Removes spaces from both ends

    " Anu ".strip()

    replace()

    Replaces text

    "Drug".replace("Drug", "Medicine")

    find()

    Finds position of text

    "Python".find("t")

    count()

    Counts occurrences

    "banana".count("a")

    startswith()

    Checks beginning

    "Python".startswith("Py")

    endswith()

    Checks ending

    "Python".endswith("on")

    split()

    Splits string into parts

    "A,B,C".split(",")

    join()

    Joins strings

    ",".join(["A","B","C"])

    in

    Checks whether text exists

    "Py" in "Python"

    not in

    Checks whether text does not exist

    "Java" not in "Python"

    Important Point: Strings Are Immutable

    In Python, strings are immutable. This means that once a string is created, its individual characters cannot be changed directly.

    Example: Trying to Change a Character

    Example : 

    medicine = "Paracetamol"
    
    medicine[0] = "X"

    Output:

    TypeError: 'str' object does not support item assignment

    Explanation: Python does not allow us to replace a character at a specific index in an existing string. Therefore, this code produces a TypeError.

    How to Modify a String

    To make a change, we can create a new string and assign it to the same variable.

    medicine = "Paracetamol"
    
    medicine = "X" + medicine[1:]
    
    print(medicine)

    Output:

    Xaracetamol

    Explanation:

    • "X" represents the new first character.

    • medicine[1:] extracts the remaining characters, starting from index 1.

    • The + operator joins these parts to create a new string.

    • The variable medicine is then assigned this new string.

    Remember

    Strings cannot be modified directly because they are immutable. To make changes, create a new string and assign it to a variable.

    Note: Reassigning a variable does not change the original string object; it makes the variable refer to the newly created string.

    1.20 Third-Party Libraries

    Third-party libraries are collections of pre-written Python code developed and distributed by individuals or organizations outside Python's standard library.

    They provide additional functions and tools that make programming easier and more efficient.

    Examples

    • NumPy – Used for numerical calculations and working with arrays.

    • Pandas – Used for data analysis and handling tabular data.

    • Matplotlib – Used for creating graphs and charts.

    • Scikit-learn – Used for machine learning and predictive modelling.

    Example in Pharmaceutical Sciences

    • NumPy: Performing numerical calculations on experimental data.

    • Pandas: Organizing and analyzing clinical trial data.

    • Matplotlib: Plotting drug concentration versus time graphs.

    • Scikit-learn: Building machine learning models for drug discovery research.

    Key Point

    Third-party libraries extend Python's capabilities and help solve specialized problems without writing all the code from scratch.

    1.20.1 Standard Libraries vs Third-Party Libraries

    Standard Libraries

    Third-Party Libraries

    Included with Python installation.

    Developed by individuals or organizations outside the Python standard library.

    Usually do not require separate installation.

    Usually require separate installation.

    Provide general-purpose functionality.

    Provide specialized functionality for specific tasks.

    Examples: math, random, datetime.

    Examples: NumPy, Pandas, Matplotlib, Scikit-learn.

    Available directly after installing Python.

    Commonly installed using tools such as pip.

    Example : 

    Standard Library

    import math
    
    print(math.sqrt(25))

    Output:

    5.0

    Third-Party Library

    import numpy as np
    
    arr = np.array([10, 20, 30])
    
    print(arr)

    Output:

    [10 20 30]

    Note: NumPy must be installed separately if it is not already available in the Python environment.

    Application in Pharmaceutical Sciences

    • Standard libraries: Calculating values, generating random numbers, and handling dates.

    • Third-party libraries: Analyzing pharmaceutical data, plotting experimental results, and developing machine learning models.

    Key Point

    Standard libraries come with Python, whereas third-party libraries extend Python with additional features and specialized tools.

    1.21 Installing Libraries

    Python provides a standard library with many built-in tools. However, for specialized tasks such as numerical calculations, data analysis, graph plotting, and machine learning, we often need additional libraries.

    These libraries can be installed using a package management tool called pip. It helps Python users easily download, install, upgrade, and uninstall third-party packages.

    pip is Python's package installer. It is used to manage third-party packages in Python.

    Uses of pip

    • Install packages: Add new libraries to Python.

    • Upgrade packages: Update installed packages to newer versions.

    • Uninstall packages: Remove packages that are no longer needed.

    Installing a Package

    Step 1: Open Terminal (macOS/Linux) or Command Prompt (Windows).

    Step 2: Enter the following command:

    python -m pip install numpy

    On systems where Python 3 uses the python3 command, use:

    python3 -m pip install numpy

    If pip Is Not Recognized

    Try running pip through Python:

    python -m pip install numpy

    Or, if your system uses python3:

    python3 -m pip install numpy

    Example: Installing NumPy

    To install NumPy, run the following command in the terminal:

    python3 -m pip install numpy

    Testing the Installation

    After installation, run the following Python code:

    import numpy
    
    print(numpy.__version__)

    Sample Output:

    2.2.0

    Note: The version number may differ depending on the installed NumPy version.

    Important Points

    • Installation commands are entered in the terminal or command prompt, not directly inside a Python script.

    • Python code such as import numpy is executed inside Python.

    • If NumPy is already installed, pip may report that the requirement is already satisfied.

    1.22 Uninstalling a Library

    Packages that are no longer required can be removed using pip.

    Command:

    python3 -m pip uninstall numpy

    Pip asks for confirmation before removing the package. After confirmation, the package is
    uninstalled from the selected environment.

    1.23 Upgrading a Library

    Libraries are updated regularly to fix bugs, improve performance, and introduce new features. The --upgrade option helps install a newer version of an existing package.

    Command:

    python3 -m pip install --upgrade numpy

    Pip checks the available versions and installs a newer compatible version if one is available.

    Chapter 1 – Conclusion

    In this chapter, we learned the fundamentals of Python programming, including variables, data
    types, strings, string operations, and Python libraries. We also explored how to install, upgrade,
    and uninstall third-party libraries using pip.

    These concepts form the foundation for learning Python and applying it to pharmaceutical
    sciences, including pharmaceutical data analysis, statistical calculations, and scientific research.

    In the next chapter, we will continue exploring Python programming concepts and their
    applications in pharmaceutical sciences.

    Comments

    Popular posts from this blog

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