Lecture Note: Python Commands and
Their Meanings
Department of Statistics
Lagos State University of Science and Technology
1. Introduction
Python is a high-level, general-purpose programming language widely used in data anal-
ysis, machine learning, automation, scientific computing, and statistical programming.
This lecture note introduces common Python commands, their meanings, and examples
for beginners.
Python is recommended for Statistics students because of its simplicity, readability,
and availability of powerful libraries such as NumPy, Pandas, SciPy, and Matplotlib.
([Link]
Contents
1 Introduction to Python 7
1.1 Why Learn Python? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2 Basic Python Syntax 7
2.1 Printing Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.2 Comments in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.3 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.4 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.5 Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3 Operators 8
3.1 Arithmetic Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.2 Comparison Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.3 Comparison Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3.4 Comparison Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1
3.5 Comparison Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3.6 Comparison Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3.7 Comparison Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3.8 Comparison Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
3.9 Comparison Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
3.10 Comparison Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
4 Control Flow 10
4.1 The if Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
4.2 if-else Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
4.3 if-elif-else Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
5 Loops 11
5.1 The for Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
5.2 The while Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
6 Functions 11
6.1 Functions with Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . 11
7 Lists 12
8 Dictionaries 12
9 File Handling 12
9.1 Reading a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
9.2 Writing to a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
10 Exercises with Solutions 13
2
2. Basic Python Commands
Command Meaning / Use
print() Displays output on the screen.
input() Accepts input from the user.
type() Returns the data type of a value or variable.
len() Returns length of lists, strings, tuples, etc.
help() Shows documentation for functions or modules.
dir() Displays all attributes of an object or module.
3. Data Type Conversion Commands
Command Meaning
int() Converts a value to an integer.
float() Converts a value to a float.
str() Converts a value to a string.
bool() Converts to a Boolean.
list() Converts to a list.
tuple() Converts to a tuple.
dict() Converts to a dictionary.
4. Operators in Python
4.1 Arithmetic Operators
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
// Floor division
% Modulus (remainder)
** Exponentiation
3
4.2 Comparison Operators
Operator Meaning
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater or equal
<= Less or equal
4.3 Logical Operators
Operator Meaning
and True if both conditions are true
or True if at least one condition is true
not Reverses a Boolean value
4.4 Assignment Operators
Operator Meaning
= Assigns a value
+= Add and assign
-= Subtract and assign
*= Multiply and assign
/= Divide and assign
5. Python Keywords
5.1 Control Flow Keywords
Keyword Meaning
if Executes block if condition is true.
elif Additional condition check.
else Executes when prior conditions fail.
for Loop over a sequence.
while Loop while a condition is true.
4
break Terminates a loop.
continue Skips current loop iteration.
pass Placeholder that does nothing.
5.2 Function and Class Keywords
Keyword Meaning
def Defines a function.
return Returns a value from a function.
class Defines a class.
lambda Anonymous (short) function.
5.3 Exception Handling Keywords
Keyword Meaning
try Starts error-checking block.
except Handles exception.
finally Runs regardless of error.
raise Raises an error manually.
5.4 Other Important Keywords
Keyword Meaning
import Imports a module.
from Imports specific part of module.
as Renames a module.
in Membership operator.
is Identity comparison.
global Declares global variable in function.
nonlocal Variable from outer function.
with Context manager (safe file handling).
yield Generates values lazily in a function.
6. File Handling Commands
5
Command Meaning
open() Opens a file.
read() Reads file content.
write() Writes into file.
close() Closes file.
7. List, Tuple, and Dictionary Commands
7.1 List Commands
Command Meaning
append() Add item to end of list.
insert() Insert item at index.
remove() Remove first occurrence.
pop() Remove and return last item.
sort() Sort list.
reverse() Reverse list.
7.2 Dictionary Commands
Command Meaning
keys() Returns keys.
values() Returns values.
items() Returns key-value pairs.
get() Retrieves value safely.
6
1 Introduction to Python
Python is known for its simplicity and readability. It uses a clean syntax that resembles
English.
1.1 Why Learn Python?
• Easy to read and write
• Vast libraries for data science (NumPy, Pandas, Matplotlib)
• Supports multiple paradigms (procedural, object-oriented)
• Widely used in academics and industry
2 Basic Python Syntax
2.1 Printing Output
The first command most beginners learn is the print() function.
print (" Welcome to Python ")
2.2 Comments in Python
Comments help explain your code. Python uses the hash symbol #.
# This is a comment
print (" Hello World ")
2.3 Variables
Variables store data.
import numpy as np
arr = np . array ([1 , 2 , 3])
print ( arr )
2.4 Variables
Variables store data.
7
import pandas as pd
data = pd . DataFrame ({" Age ": [20 , 21 , 19]})
print ( data )
2.5 Data Types
Common Python data types include:
• Integers: 5, -7, 100
• Floats: 2.7, 3.14
• Strings: "Hello"
• Booleans: True, False
3 Operators
3.1 Arithmetic Operators
a = 10
b = 3
print ( a + b ) # Addition
print ( a - b ) # Subtraction
print ( a * b ) # Multiplication
print ( a / b ) # Division
print ( a // b ) # Floor division
print ( a % b ) # Modulus
print ( a ** b ) # Exponentiation
3.2 Comparison Operators
print (5 > 3) # True
print (5 == 5) # True
print (5 != 4) # True
8
3.3 Comparison Operators
age = 18
if age >= 18:
print (" You are an adult ")
else :
print (" You are not an adult ")
3.4 Comparison Operators
score = 75
if score >= 70:
print (" A ")
elif score >= 60:
print (" B ")
else :
print (" C ")
3.5 Comparison Operators
for i in range (1 , 6) :
print (" Number :" , i )
3.6 Comparison Operators
count = 1
while count <= 5:
print ( count )
count += 1
3.7 Comparison Operators
count = 1
while count <= 5:
print ( count )
9
count += 1
3.8 Comparison Operators
fruits = [" apple " , " banana " , " orange "]
print ( fruits [0]) # First item
3.9 Comparison Operators
student = {
" name ": " Alice " ,
" age ": 20 ,
" department ": " Statistics "
}
print ( student [" name "])
3.10 Comparison Operators
point = (5 , 10)
print ( point [0])
4 Control Flow
4.1 The if Statement
fruits . append (" mango ")
fruits . remove (" banana ")
print ( fruits )
4.2 if-else Statement
age = 16
if age >= 18:
print (" Adult ")
else :
print (" Minor ")
10
4.3 if-elif-else Statement
score = 75
if score >= 70:
print (" A ")
elif score >= 50:
print (" C ")
else :
print (" F ")
5 Loops
5.1 The for Loop
Used for iterating over a sequence.
for i in range (5) :
print ( i )
5.2 The while Loop
count = 1
while count <= 5:
print ( count )
count += 1
6 Functions
Functions allow code reuse.
def greet () :
print (" Hello !")
greet ()
6.1 Functions with Parameters
def add (a , b ) :
return a + b
11
print ( add (3 , 4) )
7 Lists
Lists store multiple items.
fruits = [" apple " , " banana " , " orange "]
print ( fruits [0])
fruits . append (" mango ")
8 Dictionaries
Key-value pairs.
student = {
" name ": " John " ,
" age ": 21 ,
" department ": " Statistics "
}
print ( student [" name "])
9 File Handling
9.1 Reading a File
def add (a , b ) :
return a + b
print ( add (5 , 3) )
9.2 Writing to a File
import matplotlib . pyplot as plt
plt . plot ([1 , 2 , 3] , [2 , 4 , 6])
plt . show ()
12
10 Exercises with Solutions
Exercise 6
Write a Python program that sums all numbers from 1 to 50.
Solution:
total = 0
for i in range (1 , 51) :
total += i
print ( total )
Exercise 7
Write a function that checks if a string is a palindrome.
Solution:
def is_palindrome ( word ) :
word = word . lower ()
return word == word [:: -1]
print ( is_palindrome (" Level ") )
Exercise 8
Given a list of numbers, find the largest number.
Solution:
numbers = [3 , 9 , 2 , 11 , 7]
print ( max ( numbers ) )
Exercise 9
Write a program that prints the multiplication table of any number entered by the user.
Solution:
n = int ( input (" Enter a number : ") )
for i in range (1 , 13) :
print (n , " x " , i , "=" , n * i )
13
Exercise 10
Create a dictionary of five items and print all keys and values using a loop.
Solution:
items = {
" pen ": 50 ,
" book ": 150 ,
" pencil ": 20 ,
" eraser ": 30 ,
" ruler ": 40
}
for key , value in items . items () :
print ( key , "=" , value )
Creating Arrays Using NumPy
Loading the NumPy Library
import numpy as np
Creating a One-Dimensional Array (Vector)
# Create a vector as a row
vector_row = [Link]([1, 2, 3])
print(vector_row)
Creating a Column Vector
A column vector must be written using a list of lists:
# Create a vector as a column
vector_column = [Link]([[1],
[2],
[3]])
print(vector_column)
14
Creating a Two-Dimensional Array (Matrix)
import numpy as np
# Create a 2x2 matrix
matrix = [Link]([[5, 2],
[3, 6]])
print(matrix)
Array Properties
a = [Link]([[1, 2, 3],
[4, 5, 6]])
print([Link]) # (2, 3)
print([Link]) # 6 elements
print([Link]) # 2 dimensions
Matrix Operations
a = [Link]([1, 2, 3])
b = [Link]([4, 5, 6])
print(a + b)
print(2 * a)
A = [Link]([[1, 2],
[3, 4]])
B = [Link]([[5, 6],
[7, 8]])
C = A @ B # or [Link](A, B)
print(C)
#Transpose
print(A.T)
det = [Link](A)
#Determinant
print(det)
#Inverse
15
inv = [Link](A)
print(inv)
Statistics
data = [Link]([10, 20, 30, 40, 50])
[Link](data)
data = [Link]([10, 20, 30, 40, 50])
[Link](data)
data = [Link]([10, 20, 30, 40, 50])
[Link](data)
data = [Link]([10, 20, 30, 40, 50])
[Link](data)
Creating Tables
from tabulate import tabulate
data = [
["John", 20, 85],
["Mary", 22, 90],
["Paul", 19, 78]
]
print(tabulate(data, headers=["Name", "Age", "Score"], tablefmt="grid"))
import pandas as pd
data = {
"Name": ["Joel", "Ahmid", "Christo", "Sola", "Felix"],
"Sex": ["M", "M", "M", "F", "M"],
"Age": [25, 30, 22, 25, 26],
"Height": [1.56, 1.29, 1.82, 1.74, 1.65],
"Score": [72, 62, 66, 75, 42]
16
}
df = [Link](data)
# Convert dictionary to table
print(df)
Histogram
import numpy as np
import [Link] as plt
# Generate 100 random numbers
x = [Link](100)
[Link](x, bins=10, edgecolor="black")
[Link]("Histogram of Normally Distributed Data")
[Link]("Values")
[Link]("Frequency")
[Link]()
Plot a Simple Histogram
import [Link] as plt
# Example data
data = [12, 15, 13, 17, 18, 19, 22, 25, 21, 23, 24, 25, 19, 17, 16]
# Plot histogram
[Link](data)
# Add labels
[Link]("Histogram of Sample Data")
[Link]("Values")
[Link]("Frequency")
# Display the plot
[Link]()
17
Plot a Simple Histogram 2
[Link](data, bins=5)
[Link]("Histogram with 5 Bins")
[Link]()
Simple Boxplot
import [Link] as plt
data = [12, 15, 13, 97, 18, 19, 22, 25, 21, 23, 24, 25, 19, 17, 16]
[Link](data)
[Link]("Boxplot of Sample Data")
[Link]("Values")
[Link]()
Boxplot For Multiple Groups
group1 = [12, 13, 14, 15, 16]
group2 = [18, 19, 21, 22, 23]
group3 = [25, 26, 24, 27, 28]
[Link]([group1, group2, group3])
[Link]("Boxplot of Three Groups")
[Link]("Groups")
[Link]("Values")
[Link]()
Boxplot For Multiple Groups With Labels
[Link]([group1, group2, group3], labels=["Group A", "Group B", "Group C"])
[Link]("Boxplot with Labels")
[Link]("Values")
[Link]()
18
Exercise 1
Write a Python program that prints your name, department, and level.
Exercise 2
Create a program that checks whether a number is even or odd.
Exercise 3
Write a function that returns the square of a number.
Exercise 4
Create a list of 5 biological terms and print each term using a loop.
Exercise 5
Create a dictionary to store student information (name, age, course) and print each value.
6. Exercises
1. Write a Python program that asks for a user’s name and age and prints:
“Hello ¡name¿, you are ¡age¿ years old.”
2. Write a Python program that computes the area of a circle using:
A = πr2
3. Create a list of five numbers and print:
• the largest number,
• the smallest number,
• the sum of the numbers.
4. Write a function that returns the square of a number.
5. Write a program that prints numbers from 1 to 50, but:
• multiples of 3 print “Fizz”,
• multiples of 5 print “Buzz”,
• multiples of both print “FizzBuzz”.
19
9. Further Reading
1. Downey, A. (2015). Think Python. O’Reilly Media.
2. Matthes, E. (2023). Python Crash Course. No Starch Press.
3. Sweigart, A. (2019). Automate the Boring Stuff with Python. No Starch Press.
4. Mark Lutz (2013). Learning Python. O’Reilly Media.
5. Charles Severance (2016). Python for Everybody. Python Institute.
6. Eric Matthes (2019). Python Crash Course. No Starch Press.
20