Computing the average of non-negative numbers from a text file
<p>I am trying to read in a text file of integers, make it a list, compute the average of all integers, compute the average of all non-negative integers, print max and min. I was able to compute the average of all integers but am having difficulty getting the average of all non-negative integers and the max and min. </p>

<p>Here is what I have so far:</p>

<pre><code>file = open("numberlist.txt", "r")

sum = 0

list = []
for num in file:
    list.append(num)

poslist = []
for number in file:
    x = int(number)
    if x &gt; 0:
        poslist.append(x)
        sum += number
posavg = sum / len(poslist)
print("The number of non-negative integers is ", len(poslist))
print("The average of the non-negtive integers is ", posavg)
</code></pre>

<p>If the numbers are separated by spaces<br>
(or, as I understand from your code, by new lines)<br>
this is a very short and <em>"Pythonic"</em> task!</p>

<p>First, let's read the entire file into numbers<br>
and also have the file close automatically:</p>

<pre><code>with open('numberlist.txt') as f:
    nums = [int(x) for x in f.read().split() if int(x) &gt;= 0]
</code></pre>

<p>After the previous 2 line you have all the non-negative<br>
numbers in a list called <code>nums</code>!</p>

<p>Now, the average would be:</p>

<pre><code>avg = sum(nums) / len(nums)
</code></pre>

<p>And the min/max would be:</p>

<pre><code>minNum, maxNum = min(nums), max(nums)
</code></pre>

<p>And that's all!</p>

<p>Now, I pushed as much Python as I think is possible<br>
into this task, so by understanding this code you make <br>
a leap in Python!</p>

python python-3.x if-statement for-loop accumulator