| New Reply |
Beginner Python - simple function |
Share Thread |
| Jun3-11, 08:31 AM | #1 |
|
|
Beginner Python - simple function
1. The problem statement, all variables and given/known data
Write the definition of a function typing_speed , that receives two parameters. The first is the number of words that a person has typed (an int greater than or equal to zero) in a particular time interval. The second is the length of the time interval in seconds (an int greater than zero). The function returns the typing speed of that person in words per minute (a float ). 2. Relevant equations 3. The attempt at a solution def typing_speed(a, b): return float((a/b)*60) Is that right? |
| Jun3-11, 10:17 AM | #2 |
|
Mentor
|
When you include code in a post, use [ code] and [ /code] tags (without the extra space). Doing so preserves your indentation, which is especially important in python.
First off - your variable names don't give any clue as to what they are to be used for. It's usually a good idea to use names that help you and other readers understand how the variable will be used. Code:
def typing_speed(wordCount, time): return float((wordCount/time)*60) The other type of division is floating point division, which behaves as you would expect. Let's suppose that someone types 170 words in 2 minutes (120 seconds). Your function will evaluate 170/120 * 60. It first evaluates 170/120 as 1, with no fractional part. It then multiplies 1 by 60 to get 60, and then casts that result to a float value, 60.0. This is not the right answer, since the correct result is actually 85.0 words per minute. To fix your code you need to cast one or both operands of the division as a float or double. You are using a cast to convert a/b * 60 to a float, but you are doing it too late. The cast operation needs to happen before the division takes place, not after. |
| New Reply |
Similar discussions for: Beginner Python - simple function
|
||||
| Thread | Forum | Replies | ||
| Beginner Python - better way to write this? | Engineering, Comp Sci, & Technology Homework | 26 | ||
| Beginner Python question | Engineering, Comp Sci, & Technology Homework | 10 | ||
| Python Beginner | Engineering, Comp Sci, & Technology Homework | 3 | ||
| Python beginner help | Engineering, Comp Sci, & Technology Homework | 3 | ||
| Python Beginner | Programming & Comp Sci | 4 | ||