Problem Solving - Interactive code!
So here I got this problem to solve:
Write an INTERACTIVE python program that will print the average value of the elements of a list.
Writing these programs is easy. Just make logic and code it out. Debugging is also a whole lot easier. But interactive programs are really a pain! For that case we will have to:
- Take input from the user,
- Use a function to run the code
- Define when to stop,
- Make the program suitable for input mistakes. (it's the toughest thing to do
First I have to define a function for calculating the average.
def average(li):x = sum(li) / len(li)print(x)
Then I have to make an input system to start and stop counting. My logic is simple. If the input is given as an integer, it'll append that number to the list. And if some string or other values than integer comes, the program will take the list to the function to calculate the average. I used simple try-expect commands.
list1 = []try:while True:list1.append(int(input("Enter the numbers:")))except:print(list1)
Lastly, I have to put list1 in the average() function.
But if someone presses enter at the very beginning of the code he will have a ZeroDivisionError.
So, I have to put another try-expect command.
try:while True:average(list1)breakexcept:print("you should add some numbers, then other characters in order to get an average of those numbers")
Now it all came together. Let's have a look to the full code.
Image by Johnson Martin from Pixabay
No comments: