Applied statistics professionals in Kenya require robust programming skills to manage, analyze, and visualize data efficiently. Python has emerged as the leading language for data science due to its simplicity, versatility, and powerful libraries. This chapter equips you with practical Python techniques essential for handling statistical data, focusing on foundational concepts and hands-on coding skills relevant to real-world data problems in the Kenyan context.
Python is a high-level programming language widely used in statistics for its readability and extensive library support. Mastery of Python basics enables statisticians to automate data cleaning, perform calculations, and develop reliable scripts for data management tasks.
Python literals are fixed values assigned directly in code. Common types include integers, floats, strings, and booleans. Running Python literals is the starting point for performing calculations and manipulating data.
Example 1: Print an integer, a float, and a string literal in Python.
Given: Integer \(10\), Float \(3.14\), String "Kenya"
Python code:
print(10)
print(3.14)
print("Kenya")
Answer:
10
3.14
Kenya
Example 2: Assign a boolean literal and display it.
Given: Boolean value \(True\)
Python code:
is_data_valid = True
print(is_data_valid)
Answer:
True
Example 3: Add two numeric literals and print the sum.
Given: Literals \(25\) and \(60\)
Python code:
print(25 + 60)
Step-by-step:
Answer:
85
Example 4: Concatenate two string literals representing two counties.
Given: "Nairobi" and "Mombasa"
Python code:
print("Nairobi" + " and " + "Mombasa")
Answer:
Nairobi and Mombasa
Example 5: Multiply two float literals representing rainfall in mm.
Given: \(12.5\) mm and \(3.2\) mm
Python code:
print(12.5 * 3.2)
Step-by-step:
Answer:
40.0
Comments are statements in Python code ignored by the interpreter. They are essential for explaining code, making it easier to understand and maintain statistical scripts.
Example 1: Write a single-line comment in Python explaining code purpose.
Given: Code to add two numbers
Python code:
# This code adds two numbers
print(7 + 5)
Answer:
12
Example 2: Use a comment to label a data input section.
Given: Inputting the age of a respondent
Python code:
# Input respondent's age
age = 24
print(age)
Answer:
24
Example 3: Comment out a line of code to prevent execution.
Given: Only print the value of x
Python code:
x = 15
# print(x + 5)
print(x)
Answer:
15
Example 4: Write a multi-line comment describing a script.
Given: Script calculates average age
Python code:
"""
This script calculates
the average age of respondents
"""
ages = [20, 22, 24]
print(sum(ages) / len(ages))
Step-by-step:
Answer:
22.0
Example 5: Place a comment beside a line of code.
Given: Indicate units of measurement
Python code:
rainfall = 120 # mm
print(rainfall)
Answer:
120
Python has several basic data types used in statistics, such as integers, floats, strings, lists, and booleans. Knowing the correct data type ensures accurate computations and data handling.
Example 1: Identify the data type of a value.
Given: \(x = 45\)
Python code:
x = 45
print(type(x))
Answer:
Example 2: Assign a float and display its type.
Given: \(y = 12.75\)
Python code:
y = 12.75
print(type(y))
Answer:
Example 3: Store a name and check its data type.
Given: \(name = "Mary"\)
Python code:
name = "Mary"
print(type(name))
Answer:
Example 4: Create a list of values representing survey scores and check its type.
Given: \(scores = [60, 75, 80]\)
Python code:
scores = [60, 75, 80]
print(type(scores))
Answer:
Example 5: Assign a boolean value to indicate data validity.
Given: \(is_valid = False\)
Python code:
is_valid = False
print(type(is_valid))
Answer:
Variables are names that store data values. In statistics, variables hold data such as sample sizes, means, and frequencies which are manipulated during analysis.
Example 1: Assign the number of respondents to a variable.
Given: 150 respondents
Python code:
respondents = 150
print(respondents)
Answer:
150
Example 2: Store the average rainfall in mm in a variable.
Given: Average rainfall is 85.2 mm
Python code:
avg_rainfall = 85.2
print(avg_rainfall)
Answer:
85.2
Example 3: Assign a string variable for county name.
Given: "Kisumu"
Python code:
county = "Kisumu"
print(county)
Answer:
Kisumu
Example 4: Update a variable value and print new value.
Given: Initial sample size \(n = 100\), then increase by 20
Python code:
n = 100
n = n + 20
print(n)
Step-by-step:
Answer:
120
Example 5: Assign a list of percentages to a variable and print.
Given: [45, 30, 25]
Python code:
percentages = [45, 30, 25]
print(percentages)
Answer:
[45, 30, 25]
A Python module is a file containing Python code, such as functions and variables, that can be imported and reused. Modules help organize statistical scripts and functions for large data projects.
Example 1: Create a module with a function to calculate mean.
Given: Filename is stats_module.py
Python code in stats_module.py:
def calculate_mean(data):
return sum(data) / len(data)
Usage:
import stats_module
print(stats_module.calculate_mean([10, 20, 30]))
Step-by-step:
Answer:
20.0
Example 2: Write a module with a function to compute median.
Given: Filename is median_module.py
Python code in median_module.py:
def median(data):
data = sorted(data)
n = len(data)
mid = n // 2
if n % 2 == 0:
return (data[mid - 1] + data[mid]) / 2
else:
return data[mid]
Usage:
import median_module
print(median_module.median([12, 15, 10, 20]))
Step-by-step:
Answer:
13.5
Example 3: Save a function for variance calculation in a module.
Given: Filename is variance_module.py
Python code in variance_module.py:
def variance(data):
mean = sum(data) / len(data)
return sum((x, mean) ** 2 for x in data) / len(data)
Usage:
import variance_module
print(variance_module.variance([5, 7, 9]))
Step-by-step:
Answer:
2.67
Example 4: Create a module with a string variable.
Given: Filename is info_module.py
Python code in info_module.py:
stat_project = "Kenya Census 2019"
Usage:
import info_module
print(info_module.stat_project)
Answer:
Kenya Census 2019
Example 5: Write a module with a function to sum values.
Given: Filename is sum_module.py
Python code in sum_module.py:
def total(data):
return sum(data)
Usage:
import sum_module
print(sum_module.total([7, 14, 21]))
Step-by-step:
Answer:
42
The print() function outputs data to the screen. It is used to display results, debug code, and communicate findings in statistical scripts.
Example 1: Print a simple message.
Given: "Data collection complete"
Python code:
print("Data collection complete")
Answer:
Data collection complete
Example 2: Print the result of a calculation.
Given: \(100 + 250\)
Python code:
print(100 + 250)
Step-by-step:
Answer:
350
Example 3: Print multiple values in one statement.
Given: "Sample size:", 75
Python code:
print("Sample size:", 75)
Answer:
Sample size: 75
Example 4: Print formatted text using variables.
Given: Variable county = "Embu", respondents = 120
Python code:
county = "Embu"
respondents = 120
print("County:", county, "- Respondents:", respondents)
Answer:
County: Embu - Respondents: 120
Example 5: Print list of values.
Given: [10, 20, 30]
Python code:
values = [10, 20, 30]
print(values)
Answer:
[10, 20, 30]
Named arguments allow you to specify parameter names in function calls for clarity. They are useful in statistics for formatting output and customizing function behavior.
Example 1: Use named argument 'sep' in print().
Given: Print "Nairobi" and "Mombasa" separated by " - "
Python code:
print("Nairobi", "Mombasa", sep=" - ")
Answer:
Nairobi - Mombasa
Example 2: Use named argument 'end' in print().
Given: Print "Data Entry" and then "Complete" on the same line.
Python code:
print("Data Entry", end=" ")
print("Complete")
Answer:
Data Entry Complete
Example 3: Format number of items with named arguments.
Given: Items = 3, item_type = "Surveys"
Python code:
print("Number of", item_type, ":", items, sep="")
Given variables:
items = 3
item_type = "Surveys"
Answer:
Number ofSurveys:3
Example 4: Print percentages with custom separator.
Given: Values 40 and 60, separator = "% | "
Python code:
print(40, 60, sep="% | ")
Answer:
40% | 60
Example 5: Use both sep and end in print().
Given: Print "Start" and "End" with sep=" --> " and end as "!"
Python code:
print("Start", "End", sep=" --> ", end="!")
Answer:
Start --> End!
The input() function allows users to enter data at runtime. It is frequently used in statistical scripts to collect sample sizes, values, or labels interactively.
Example 1: Collect a respondent's name.
Python code:
name = input("Enter respondent's name: ")
print("Name:", name)
Suppose user enters: Mary
Answer:
Name: Mary
Example 2: Enter age and display it.
Python code:
age = input("Enter age: ")
print("Age:", age)
Suppose user enters: 28
Answer:
Age: 28
Example 3: Input a number and perform a calculation.
Python code:
num = input("Enter a number: ")
num = int(num)
print(num * 5)
Suppose user enters: 7
Step-by-step:
Answer:
35
Example 4: Input two numbers and print their sum.
Python code:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print("Sum:", a + b)
Suppose user enters: 10 and 15
Step-by-step:
Answer:
Sum: 25
Example 5: Input a list of marks separated by spaces and print the average.
Python code:
marks = input("Enter marks separated by space: ")
marks = [int(x) for x in marks.split()]
print(sum(marks) / len(marks))
Suppose user enters: 40 50 60
Step-by-step:
Answer:
50.0
Python provides built-in ways to access documentation and help about functions and objects. This is crucial for statisticians exploring new libraries or functions.
Example 1: Use help() to get information about print().
Python code:
help(print)
Answer:
Displays documentation for the print() function.
Example 2: View help for the int type.
Python code:
help(int)
Answer:
Displays documentation for the int class.
Example 3: Get help for a list.
Python code:
help(list)
Answer:
Displays documentation for the list class.
Example 4: Access help for a user-defined function.
Given:
def add(a, b):
"""Returns the sum of two numbers."""
return a + b
help(add)
Answer:
Displays: Returns the sum of two numbers.
Example 5: Use dir() to list attributes of an object.
Python code:
dir(str)
Answer:
Displays all methods and attributes of the string class.
Create a free account to open more of this chapter.
Free: practical guides, quick cards, workplace scenarios and more.
Create a free accountThis chapter introduced the fundamentals of managing statistical data using Python, starting with essential concepts such as running Python code, understanding comments, data types, variables, creating modules, and utilizing the print function. It then explored the structure and use of functions, including scope, parameters, returning values, and importing modules to organize code efficiently. The chapter covered mathematical operations, including arithmetic, modulus, assignment operators, built-in math functions, and the use of the math and random modules, along with techniques for managing randomness through seeding. Learners examined strings, quotation marks, special characters, and advanced data structures like sequences, dictionaries, sets, and the use of *args and **kwargs. The flow control section detailed conditional statements, identity operators, ternary operations, looping mechanisms, enumeration, generators, and list comprehensions for powerful data manipulation. File processing was addressed through techniques for opening files and working with the os and os.path modules. Exception handling was thoroughly discussed, including wildcard exceptions, retrieving exception information, the else and finally clauses, and leveraging exceptions for flow control, along with the exception hierarchy. The chapter concluded by working with dates and times using the time and datetime modules, and demonstrated how to run Python scripts from the command line using the sys module and command-line arguments.
[14, 22, 18, 25, 16, 20, 19], calculate the total rainfall for the week using Python arithmetic operators. (2 marks)Step 1: Write the Python code to sum the list:
rainfall = [14, 22, 18, 25, 16, 20, 19]
total = sum(rainfall)
print(total)
Step 2: Calculate step by step:$$ 14 + 22 = 36 $$$$ 36 + 18 = 54 $$$$ 54 + 25 = 79 $$$$ 79 + 16 = 95 $$$$ 95 + 20 = 115 $$$$ 115 + 19 = 134 $$
Final Answer:
Total rainfall = 134 mm
23, 28, 19, 34, and 27, calculate the average age. (2 marks)Step 1: Write the formula:$$ \text{Average Age} = \frac{\text{Sum of Ages}}{\text{Number of Ages}} $$
Step 2: Substitute values:$$ \text{Sum of Ages} = 23 + 28 + 19 + 34 + 27 = 131 $$$$ \text{Number of Ages} = 5 $$
Step 3: Calculate average:$$ \text{Average Age} = \frac{131}{5} = 26.2 $$
Final Answer:
Average age = 26.2 years
A statistics officer at the Kenya National Bureau of Statistics (KNBS) needs to collect monthly rainfall data from county offices and process the data using Python. List the steps they should follow to open a CSV file, read its contents, and handle any errors that may occur during file opening. (4 marks)
Write a Python statement that prints the mean and standard deviation of the following list of daily customer counts at a Nairobi supermarket: [120, 135, 150, 110, 145]. (4 marks)