Python is a versatile, beginner-friendly programming language used for a wide range of applications from web development and data analysis to machine learning. Its simple syntax, rich standard library, and extensive third-party modules allow developers to quickly write programs to accomplish tasks. This guide will demonstrate how to write Python scripts to perform basic mathematical calculations and text manipulations—essential skills for automating workflows, processing data, and building more complex applications. You can run the following code snippets in a Python interpreter or by saving them in a .py
file and running it.
Table of Contents
Open Table of Contents
Overview of Python Calculations and String Manipulation
Python includes many built-in functions and operators to carry out numeric computations and evaluate mathematical expressions. Developers can perform common operations like addition, subtraction, multiplication, division, exponentiation, modulo division, and more using concise syntax. Python also provides extensive string manipulation capabilities. Strings can be indexed, sliced, formatted, searched, and transformed using Python’s string methods and formatting mini-language.
This guide will cover the following topics using hands-on examples:
- Basic math operators for arithmetic
- Variable assignments and expressions
- Built-in math functions
- Type conversions and rounding
- F-strings for string formatting
- Common string methods
- Regular expressions for pattern matching
Understanding these core concepts will provide a solid foundation for writing Python scripts that can crunch numbers, parse text data, and manipulate string outputs.
Performing Basic Arithmetic Calculations
Python supports the standard arithmetic operators for mathematical calculations:
- Addition:
+
- Subtraction:
-
- Multiplication:
*
- Division:
/
- Exponentiation:
**
- Modulo (remainder):
%
Let’s walk through some examples:
# Addition
print(5 + 2) # Outputs 7
# Subtraction
print(10 - 3) # Outputs 7
# Multiplication
print(4 * 5) # Outputs 20
# Division
print(16 / 4) # Outputs 4.0
# Exponentiation
print(3 ** 4) # Outputs 81
# Modulo
print(10 % 3) # Outputs 1
Python supports both integer and floating-point arithmetic. The /
divider always returns a float value, even when dividing integers. The //
operator can be used for integer division, truncating any fractional part.
print(10 / 3) # 3.3333333333333335
print(10 // 3) # 3
Calculations can be performed on variables by assigning values and expressing operations:
width = 15
height = 12
area = width * height
print(area) # 180
Following the standard order of operations, expressions in parentheses are evaluated first:
print(2 * (3 + 4)) # 14
print(2 * 3 + 4) # 10
In summary, Python provides concise syntax and operators for all basic math calculations needed in scripts.
Using Built-in Math Functions
Beyond the basic operators, Python includes numerous math functions in the math
module of the standard library. Some common examples include:
math.sqrt()
- Square rootmath.ceil()
- Round up to the nearest integermath.floor()
- Round down to the nearest integermath.fabs()
- Absolute valuemath.pow()
- Raise to power (returns a float)math.log()
- Logarithm for given basemath.sin()
- Sine functionmath.cos()
- Cosine function
To use the math
functions, import the module:
import math
print(math.floor(12.5)) # 12
print(math.ceil(12.5)) # 13
print(math.sqrt(25)) # 5.0
print(math.pow(2, 3)) # 8.0
print(math.log(8, 2)) # 3.0
These provide additional mathematical capabilities without needing to write long expressions yourself. Python’s math module includes many more advanced functions as well like hyperbolic trigonometry, factorials, GCDs, etc.
Type Conversions and Rounding
When performing calculations in Python, sometimes variables may need to be converted between data types or results rounded to a specific precision.
The int()
, float()
and round()
functions are useful for this:
x = 1.345
print(int(x)) # 1
y = 5
print(float(y)) # 5.0
z = 1.678
print(round(z, 1)) # 1.7 Rounded to 1 decimal
print(round(z)) # 2 Rounded to nearest integer
Type conversions allow seamlessly moving between integer and float representations during math operations and data processing.
The second argument of round()
specifies the number of decimals to round to. Omitting it rounds to the nearest whole number.
Formatted String Output with f-strings
Python f-strings provide a concise way to embed expressions and variable values directly inside string literals for formatting:
name = "John"
age = 25
print(f"Hello, my name is {name}. I am {age} years old.")
# Prints: Hello, my name is John. I am 25 years old.
This f''
syntax replaces the placeholders {name}
and {age}
with their variable values. Expressions can also be included inside the braces:
print(f"In 5 years, I will be {age + 5} years old")
# Prints: In 5 years, I will be 30 years old
f-strings provide an easy way to interpolate Python variables and generate dynamic string outputs without concatenation.
They support all the formatting options of the str.format()
method like padding, numerical precision, date formatting, etc:
price = 24.583
print(f"The price is {price:.2f}") # The price is 24.58
In summary, f-strings are quite useful when building scripts that produce formatted output for reporting or integration.
Common String Methods in Python
Python has over 50 built-in string methods that can be called on string objects to manipulate and transform text data. Here are some commonly used ones:
1. Changing case:
s = "Hello World"
print(s.upper()) # "HELLO WORLD"
print(s.lower()) # "hello world"
print(s.title()) # "Hello World"
2. Searching and replacing:
s = "apples and oranges"
print(s.count("and")) # 1
print(s.replace("and", "or")) # "apples or oranges"
3. Checking content:
s = "Python strings"
print("Python" in s) # True
print("python" in s) # False
print(s.startswith("Python")) # True
print(s.endswith("strings")) # True
4. Splitting and joining:
s = "Python,JavaScript,C++"
print(s.split(",")) # ["Python", "JavaScript", "C++"]
langs = ["Python","C++","Java"]
print("-".join(langs)) # "Python-C++-Java"
These are just a few examples of the many options available for manipulating string data in Python scripts.
Using Regular Expressions
Regular expressions provide powerful pattern matching capabilities in Python. They can be used to search, extract, replace, and validate string content.
Here are some introductory examples of common regex tasks:
1. Finding pattern matches:
import re
pattern = r"grocery"
s = "Visit the grocery store"
matches = re.findall(pattern, s)
print(matches) # ['grocery']
2. Extracting matches:
s = "Apples - $1.49 per lb"
price_regex = r"\$([\d.]+)"
matches = re.search(price_regex, s)
print(float(matches.group(1))) # 1.49
3. Replacing matches:
s = "The dog is playing fetch"
s = re.sub(r"dog", "cat", s)
print(s) # The cat is playing fetch
4. Validating strings (Example):
regex = r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$" # A basic email pattern
print(re.search(regex, "[email protected]")) # Matches
print(re.search(regex, "testing")) # None
This provides a brief overview of how powerful regular expressions are for advanced string processing and validation. Remember that crafting precise regular expressions can be complex, and the example above is a basic one.
Practical Examples and Use Cases
Now that we’ve covered the building blocks, let’s walk through some practical examples of how these concepts come together in real Python scripts:
1. Distance Conversion Script
This script demonstrates unit conversion from kilometers to miles:
# Units conversion
KM_TO_MILES = 0.62137
def km_to_miles(km):
miles = km * KM_TO_MILES
return miles
km = 10.5
print(f"{km} km is equal to {km_to_miles(km):.2f} miles")
# Output:
# 10.5 km is equal to 6.52 miles
It defines a constant ratio, a conversion function, performs the calculation on a sample input, and prints a formatted string output.
2. Monthly Sales Report
This script generates a simple text report summarizing product sales for a month:
sales = {
"apples": 65,
"oranges": 35,
"pears": 48
}
total = sum(sales.values())
print(f"Monthly Sales Report \n")
for product, qty in sales.items():
print(f"{product.title()}: {qty} units")
print(f"\nTotal Sales: {total} units")
# Output:
# Monthly Sales Report
# Apples: 65 units
# Oranges: 35 units
# Pears: 48 units
# Total Sales: 148 units
It uses a dictionary to store the data, calculates the summary statistics, and generates a formatted multi-line output report.
3. Password Strength Checker
This script checks if a password meets basic strength criteria using regular expressions:
import re
password = input("Enter a new password: ")
regex = r"^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%]).{8,24}$"
if re.search(regex, password):
print("Strong password")
else:
print("Weak password. Must be 8-24 characters with at least one uppercase, lowercase, number and special symbol.")
# Example usage:
# Enter a new password: hello@123
# Weak password. Must be 8-24 characters with at least one uppercase, lowercase, number and special symbol.
This shows how calculators, reports, validators, and other tools can be built rapidly with Python.
Summary
This guide covered several fundamental techniques for performing calculations, formatting strings, and manipulating text in Python:
- Arithmetic operators, math functions, type conversions, and rounding allow flexible numeric computing.
- F-strings provide readable formatted string output using embedded expressions.
- String methods like
split()
,join()
,replace()
enable efficient text processing. - Regular expressions add powerful pattern matching and validation capabilities.
With these core skills, developers can automate everyday tasks, process data, generate reports, and build more complex scripts and applications in Python. The standard libraries provide many additional modules for mathematical, statistical, text processing, I/O, web scraping, and other tasks.
Python strikes a unique balance between concise, readable code and extensive functionality. By mastering basic math and string manipulation, programmers can take advantage of Python’s strengths to write scripts that are productive, maintainable, and easily extensible. This guide provided examples and use cases to demonstrate applied concepts, but there are countless more possibilities.