Coding Exercise for Beginners in Python |Exercise 14 | Python Tutorials for Beginners #lec44
How to Calculate Average Height Using Python
Introduction to the Exercise
- The video introduces a coding exercise focused on calculating the average height from a list of heights using a for loop.
- A sample list of heights is provided, illustrating that while the task seems simple, there are specific constraints to follow.
Constraints and Requirements
- Participants cannot use built-in functions like
sumandlen; they must replicate these functionalities using for loops.
- User input must be taken through the
inputfunction, emphasizing understanding its properties and functionality.
- The output should be rounded to the nearest whole number, highlighting three key requirements: no built-in functions, user input handling, and rounding.
Functions to Use
- The
splitfunction is essential for converting user input (a string) into a list of heights by separating values based on spaces.
- The
rangefunction will help generate sequences of numbers; it starts at 0 by default but can be customized with specified start and stop points.
Implementation Steps
- Viewers are encouraged to pause the video and attempt the exercise independently before reviewing the solution.
- The instructor begins coding by taking user input for heights with an explanation of how this data will initially be treated as a string.
Processing Input Data
- After receiving input, the string needs to be split into individual height values using the
splitmethod.
- An example illustrates splitting based on spaces; if commas were used instead, adjustments would need to be made in specifying separators.
- A variable named
height_listis created to store these split values as a list. However, it's noted that these values remain strings until further processing occurs.
How to Convert a List of Strings to Integers
Understanding Type Conversion in Python
- The speaker discusses the need to convert a list of strings into integers, emphasizing that type casting is necessary for this operation.
- An error occurs when attempting to directly convert a list using
int(), as it requires a string, byte-like object, or real number—not a list.
Traversing the List
- To convert each item in the list, one must traverse through it. The speaker introduces the use of a
forloop with an index variable.
- The speaker explains how to access elements in the list using their indices but highlights that using string values as indices will lead to errors.
Using Range Function for Indexing
- A suggestion is made to utilize the
range()function for iterating over indices from 0 up to the length of the list, which should be dynamically determined rather than hardcoded.
- The speaker proposes initializing a counter variable (
count) at zero and incrementing it within another loop that traverses through each element of the height list.
Calculating Length Without len()
- By iterating through each element and incrementing
count, one can determine the length of the list without using Python's built-inlen()function.
- After completing this process, printing
countconfirms its value reflects the actual number of items in the height list.
Finalizing Integer Conversion and Summation
- With an established count, one can now iterate from 0 up to this count and convert each string in
height_listinto an integer.
- The conversion process is reiterated with examples showing how integers are assigned back into their respective positions within
height_list.
Summation Process Introduction
- Finally, after confirming all elements are converted successfully, there’s an introduction to calculating their sum by initializing a sum variable and preparing for traversal through the updated integer list.
Understanding Average Calculation in Python
Looping Through a List to Calculate Sum
- The process begins with a simple loop to traverse through a list of heights, using any variable name (e.g.,
person) for each item in the list.
- The sum is updated by adding each person's height to the total using either
sum = sum + personor shorthandsum += person.
Calculating Average from Total Height
- To find the average height, a new variable
AVGis introduced, calculated astotal / count, wheretotalrepresents the cumulative height.
- It’s important to avoid naming variables after built-in functions like
sum; hence,totalis used instead.
Rounding and Displaying Results
- After calculating the average, it’s rounded to the nearest whole number using Python's built-in round function. For example, an average of 154.6 would be rounded to 155.
- The program outputs both the count of heights entered and the rounded average height.
Practical Application and Understanding Key Functions
- Users are encouraged to practice coding by writing down examples on paper and performing dry runs for better understanding.
- The final output can be formatted for clarity; for instance, displaying "Average height is 155" enhances readability.
Key Concepts Highlighted
- Understanding how to use loops effectively in Python.
- Importance of avoiding conflicts with built-in function names when creating variables.
- Utilizing rounding functions for cleaner output results.