San Jose State University Department of Applied Data Science
**DATA 200 Computational Programming for Data Analytics**
Spring 2024 Instructor: Ron Mak
"
]
},
{
"cell_type": "markdown",
"id": "fc24ba86-b964-4cbe-8d85-1dfde2623068",
"metadata": {},
"source": [
"# Sentinel-Controlled Iteration\n",
"\n",
"#### If we are given a fixed list of scores, we can easily calculate their average."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9519fcf7-7b3a-40ab-9b51-44bcf64e6946",
"metadata": {},
"outputs": [],
"source": [
"scores = [92, 85, 6, 90, 75, 83]\n",
"total = 0\n",
"count = len(scores)\n",
"\n",
"print(f'The {count} scores are:', end='')\n",
"\n",
"for score in scores:\n",
" print(f'{score:3d}', end='')\n",
" total += score\n",
" \n",
"print()\n",
"print(f'and their average is {total/count:.2f}')"
]
},
{
"cell_type": "markdown",
"id": "6fdf47de-75cf-492e-afae-527c332550a3",
"metadata": {},
"source": [
"#### But what if we have to prompt the user for each score, and therefore we don't know ahead of time (i.e., when we're writing the code) what the scores are, or even how many there are? Then we can use a **sentinel** to mark the end of the scores. For example, the sentinel can be -1, since no score should be negative."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "646ca193-181c-4991-8871-6885c1df58a5",
"metadata": {},
"outputs": [],
"source": [
"total = 0\n",
"count = 0\n",
"\n",
"# Get the first score.\n",
"score = int(input('Enter a score, -1 to end: '))"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "dbf244bc-d179-46cd-a964-c07b8e4a893c",
"metadata": {},
"outputs": [],
"source": [
"# Get the remaining scores.\n",
"while score >= 0:\n",
" total += score\n",
" count += 1\n",
" \n",
" score = int(input('Enter a score, -1 to end: '))"
]
},
{
"cell_type": "markdown",
"id": "05db9817-8126-4397-ba03-a525d0ac95f9",
"metadata": {},
"source": [
"#### The sentinel value (-1) is neither counted nor added to the toal."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "05ec1bae-2750-450c-9d78-29ee03cb1a42",
"metadata": {},
"outputs": [],
"source": [
"print()\n",
"print(f'You entered {count} scores.')\n",
"print(f'Their average is {total/count:.3f}')"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "bd592fd7-aa58-4c8d-9240-e1ae7dd8d46d",
"metadata": {},
"outputs": [],
"source": [
"# (C) Copyright 2023 by Ronald Mak"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "410a1dfb-6e72-428b-8b2d-a504944316b1",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.5"
}
},
"nbformat": 4,
"nbformat_minor": 5
}