In: Computer Science
A few weeks ago you crated a program which randomly
generated a wind-speed, and the output told us what category of
cyclone it was. Your solution may have looked like this:
import random
def main():
wind_speed = random.randint(0, 255)
if wind_speed in range(0, 118):
message =
str(wind_speed) + "\n It is not yet a cyclone"
elif wind_speed in range(119, 153):
message =
str(wind_speed) + "\n It is a Category 1 cyclone"
elif wind_speed in range(154, 177):
message =
str(wind_speed) + "\n It is a Category 2 cyclone"
elif wind_speed in range(178, 208):
message =
str(wind_speed) + "\n It is a Category 3 cyclone"
elif wind_speed in range(209, 251):
message =
str(wind_speed) + "\n It is a Category 4 cyclone"
else:
message =
str(wind_speed) + "\n It is a Category 5 cyclone"
print(message)
main()
Now we need to refactor this code. Extract the decision into a
function called det_category, which takes a number (the wind speed)
as an input. This function needs to return the message.
main() should still generate the number, and display the message.
It will need to call the det_category function in between those two
things.
# Python code
import random """ det_category, which takes a number (the wind speed) as an input. This function needs to return the message. """ def det_category(wind_speed): if wind_speed in range(0, 118): message = str(wind_speed) + "\n It is not yet a cyclone" elif wind_speed in range(119, 153): message = str(wind_speed) + "\n It is a Category 1 cyclone" elif wind_speed in range(154, 177): message = str(wind_speed) + "\n It is a Category 2 cyclone" elif wind_speed in range(178, 208): message = str(wind_speed) + "\n It is a Category 3 cyclone" elif wind_speed in range(209, 251): message = str(wind_speed) + "\n It is a Category 4 cyclone" else: message = str(wind_speed) + "\n It is a Category 5 cyclone" return message # main() function def main(): # generate the number, and display the message. wind_speed = random.randint(0, 255) # call the function message = det_category(wind_speed) print(message) # call function main()
# screenshot for indentation help
#output
// if you need any help regarding this solution ................ please leave a comment .......... thanks