0

I cant find the average

hello, i am trying to create a program that will reads until i put 'done' but it needs to print only int numbers and i started with while true and line = raw_input('tell me a number') and i tried to print only the inte.. numbers with the continue word but it didnt succeed. I also want to find the average of these numbers and i created average=0 outside the loop and i put inside the loop average = average + line but i get TypeError

19th Mar 2017, 9:41 PM
Project:Programgamer
Project:Programgamer - avatar
8 Réponses
+ 6
Ok. I saw your code. Yes. You can use a try/except block to handle the exception when a user enters a float number.
20th Mar 2017, 1:33 AM
Ulisses Cruz
Ulisses Cruz - avatar
+ 6
Another point that I wanted to point out about your code: The way the program works right now it will print the total of the numbers inserted not the average. For it to print the average you should count the how many number the user enters. Example: total = 0 count = 0 while True: line = input('number: ') if line == 'done': break try: line = int(line) count += 1 # this increments the count each time a number is inserted by user total += line except ValueError: print("The value you inserted is invalid.") print(total/count) # this is the average Note that I am using Python 3 that's why I use input instead of raw_input and print with parenteses. In the Code Playground if you what you code to run you should use Python 3 sintax.
20th Mar 2017, 1:43 AM
Ulisses Cruz
Ulisses Cruz - avatar
+ 5
The raw_input function returns a string. If you want to convert that to an int use: while True: line = raw_input('tell me a number') if line == 'done': break line = int(line) average = average + line Trying to add an int and a string is what is causing the TypeError
19th Mar 2017, 10:24 PM
Ulisses Cruz
Ulisses Cruz - avatar
+ 5
One way that we can better help is if you put your code in the Code Playground and tell us its name. Then we can understand better what you are doing.
19th Mar 2017, 10:32 PM
Ulisses Cruz
Ulisses Cruz - avatar
+ 5
Please, post the code in the Code Playground so that we can better help you. That come back and tell us its name.
19th Mar 2017, 11:16 PM
Ulisses Cruz
Ulisses Cruz - avatar
0
thank you very much i finally got the problem you were right about converting it but how can i avoid from being a float number , with try and except loop ? right? or better with the if ?
19th Mar 2017, 11:08 PM
Project:Programgamer
Project:Programgamer - avatar
0
ok i did the name is "How to accept only integer number and show a message when the numbers are float ?"
19th Mar 2017, 11:55 PM
Project:Programgamer
Project:Programgamer - avatar
0
ok thank you very much for your time and your help , i really appreciate !
20th Mar 2017, 1:48 AM
Project:Programgamer
Project:Programgamer - avatar