boolean - Python 3 - Only numeric input -
i have trouble finishing python assignment. i'm using python 3.0 program asks user input set of 20 numbers, store them list, , perform calculation on output largest number, smallest, sum, , average.
right now, working, except 1 thing! in event of non numeric input user, program ask input again. have trouble doing that, thought of boolean variable, i'm not sure.
thanks lot help. here's code :
import time #defining main function def main(): numbers = get_values() get_analysis(numbers) #defining function store values def get_values(): print('welcome number analysis program!') print('please enter series of 20 random numbers') values =[] in range(20): value =(int(input("enter random number " + str(i + 1) + ": "))) values.append(value) #here store data list called "values" return values #defining function output numbers. def get_analysis (numbers): print(".................................") print("the lowest number is:", min(numbers)) time.sleep(1) print("the highest number is:", max(numbers)) time.sleep(1) print("the sum numbers is:", sum(numbers)) time.sleep(1) print("the average numbers is:", sum(numbers)/len(numbers)) print(".................................") main()
vince
a couple of changes:
added
get_int()
function prompts repeatedly until integer enteredused simplify
get_values()
functionadded
how_many
parameter. follows "don't repeat yourself" principle - if want change number of items, can in 1 placemoved "welcome program" message out of
get_values
main
belongsdon't capitalize every word or chuck norris you
i renamed
get_analysis()
show_analysis()
because prints result rather returning it; accurate function names important!i reduced analysis data-driven loop; more matter of taste else, think cleaner , easier understand, number of tests increases, , contributes don't repeat yourself
and final result:
import time def get_int(prompt): while true: try: return int(input(prompt)) except valueerror: # couldn't parse int pass def get_values(how_many): return [get_int("enter #{}: ".format(i)) in range(1, how_many+1)] def average(lst): return sum(lst) / len(lst) def show_analysis(numbers): tests = [ ("the lowest value is", min), ("the highest value is", max), ("the sum is", sum), ("the average is", average) ] print(".................................") label,fn in tests: print("{} {}".format(label, fn(numbers))) time.sleep(.5) print(".................................") def main(): how_many = 20 print("welcome number analysis program!") print("please enter {} integers".format(how_many)) numbers = get_values(how_many) show_analysis(numbers) main()
Comments
Post a Comment