Python Coding Exercise #23: Slicing and the min() and max() Functions
Part of the series Python Practice Exercise — part 23
Before you start: Know input() and int() · Know what a string and a list are
This post groups two short exercises. The first uses string slicing to pick part of a piece of text, and the second uses the built-in functions min() and max() to find the smallest and largest of several numbers.
Exercise 1: Last three digits of a phone number
The question
Write a program that enters a phone number and prints its last 3 digits.
Enter a phone number: 9876543210
210
My Solution
phone_number = input("Enter a phone number: ")
print(phone_number[-3:])
How it works
1. The phone number stays a string. input() returns text, and there is no int() here. That’s deliberate. A phone number isn’t something you do maths with, and converting it to a number would damage it: int("0123") becomes 123, and the leading zero disappears. A number like +91-98765 or 555-1234 can’t be converted at all. Text is the right type for phone numbers.
2. Square brackets pick characters out of a string. Every character in a string has a position, called an index, counting from 0 at the start. Python also lets you count from the end with negative numbers (as in Exercise #56):
9 8 7 6 5 4 3 2 1 0
0 1 2 3 4 5 6 7 8 9 <- positions from the start
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 <- positions from the end
So phone_number[-1] is the last character, and phone_number[-3] is the third from the end.
3. A slice takes a range. A slice is written [start:stop]. It takes the characters from start up to, but not including, stop. You can leave either side empty:
- If you leave out
stop, the slice runs to the end. - If you leave out
start, it begins at the start.
Here are some examples using "9876543210":
| Slice | Result | Meaning |
|---|---|---|
[-1] | 0 | the last character |
[0] | 9 | the first character |
[-3:] | 210 | from the 3rd-from-last character to the end |
[:3] | 987 | from the start up to (not including) position 3 |
[2:5] | 765 | positions 2, 3 and 4 |
So phone_number[-3:] means “start three characters from the end, and go all the way to the end”. That is exactly the last three digits.
Things to notice
It never crashes on short input. A slice is forgiving. If the text has fewer than 3 characters, you simply get what’s there: "12" gives 12, and an empty string gives an empty line. Picking a single character that doesn’t exist, such as phone_number[5] on a short string, would cause an error, but a slice doesn’t.
Dashes are fine, spaces are not. The slice just counts characters, so 98-765-4321 gives 321. But a stray space at the end counts as a character too. Typing 12345 with a trailing space prints 45 , with the space included. The .strip() method removes spaces from both ends, so input(...).strip() is a handy safeguard. The strip() method is explained in String Methods in Python.
Exercise 2: Largest and smallest of four numbers
The question
Write a program that enters 4 numbers and prints the largest and smallest number. Use built-in functions
maxandmin.
Number 1: 12
Number 2: 7
Number 3: 30
Number 4: 5
Minimum number: 5
Maximum number: 30
My Solution
number1 = int(input("Number 1: "))
number2 = int(input("Number 2: "))
number3 = int(input("Number 3: "))
number4 = int(input("Number 4: "))
number_list = [number1, number2, number3, number4]
print(f"Minimum number: {min(number_list)}")
print(f"Maximum number: {max(number_list)}")
How it works
1. Four numbers, converted with int(). Each answer is converted to an integer, because comparing the text "30" and "5" would give surprising results (as text, "5" sorts after "30"). We want to compare them as numbers.
2. Put the numbers in a list. [number1, number2, number3, number4] creates a list, which holds several values in one variable. (Lists are covered in Core Data Structures in Python.)
3. min() and max() do the work. These are built-in functions, which means they come with Python and need no import. Given a list, min() returns the smallest value and max() returns the largest. They are used inside the f-strings, so the results are printed straight away.
For the numbers 12, 7, 30 and 5, min(...) is 5 and max(...) is 30.
Alternative: no list needed
min() and max() also accept the values directly, separated by commas:
number1 = int(input("Number 1: "))
number2 = int(input("Number 2: "))
number3 = int(input("Number 3: "))
number4 = int(input("Number 4: "))
print(f"Minimum number: {min(number1, number2, number3, number4)}")
print(f"Maximum number: {max(number1, number2, number3, number4)}")
It prints exactly the same output, and it skips the step of building a list. The list version is better when the numbers are already in a list, or when you don’t know in advance how many there will be. The direct version is shorter for a fixed handful of values.
Things to notice
Equal numbers are fine. If all four numbers are 5, both min() and max() give 5.
Negative numbers work too. For -4, 0, 9 and -10, the minimum is -10 and the maximum is 9.
Don’t name a variable min or max. These are the names of the functions, and creating a variable with the same name replaces them. After min = 5, calling min([1, 2]) fails with TypeError: 'int' object is not callable. This is the same trap as naming a variable sum, which came up in Exercise #09. That’s why the list in the solution is called number_list.
Key takeaways
- Keep phone numbers as strings. Converting them to integers would drop leading zeros.
- Negative indexes count from the end:
[-1]is the last character. - A slice
[start:stop]includesstartbut notstop. Leavingstopempty means “to the end”. - Slices don’t raise an error when the text is short.
min()andmax()are built-in functions that find the smallest and largest value in a list, or among values you pass directly.- Convert input to numbers with
int()before comparing, so you compare numbers rather than text. - Don’t use built-in names such as
min,maxorsumfor your own variables.
✦ This is part of my Python Practice Exercise series, where I work through exercises while learning Python and explain each answer in plain language. ✦
Practice Source: These exercises are taken from Ultimate Python Programming: Learn Python with 650+ Programs, 900+ Practice Questions, and 5 Projects by Deepali Srivastava, published by BPB Publications. I’m working through the exercises as part of my Python learning journey and documenting my answers and explanations here.