Home > database >  How to calculate a running total while using a for loop?
How to calculate a running total while using a for loop?

Time:10-06

I'm trying to write a code that generates 100 random numbers and then determines whether or not each number is even or odd. At the end of the code, there should be both the total of even numbers and the total of odd numbers.

Here is the code so far:

import random
even = 0
odd = 0

for count in range(100):
    def main(even, odd):
        number = random.randint(1, 1000)
        return number
    
    def isEven(even, odd):
        number = main(even, odd)
        if number % 2 == 0:
            even  = 1
            print(number, 'is even')
        elif number % 2 != 0:
            odd  = 1
            print(number, 'is odd')
            return odd
            return even
        

    main(even, odd)
    isEven(even, odd)

def totals(even, odd):
    even = isEven(even, odd)
    odd = isEven(even, odd)
    print('the total number of even numbers is', even)
    print('the total number of odd numbers is', odd)

totals(even, odd) 

However, when I run the code the even and odd total end up being a something in a range of None to 2. I've tried making even and odd a local variable in the main(), isEven(), and totals() functions. How can I write it so that the total ends up equaling 100 and it tallies that way I want it to?

CodePudding user response:

I don't understand where the structure of your code came from at all. Why would you define functions inside a for loop? And also the variables odd and even will never be updated since you can't pass variables by reference in python.

A much better approach would be something like:

import random


numbers = [random.randint(1, 1000) for _ in range(100)]

odd_count, even_count = 0, 0

for number in numbers:
    if number % 2 == 0:
        even_count  = 1
    else:
        odd_count  = 1

print(f"The total number of even numbers is {even_count}")
print(f"The total number of odd numbers is {odd_count}")

CodePudding user response:

Maybe try putting the for loop inside the functions. The for loop outside makes no sense to me. Also, what I the purpose of the 2 parameters in the main function.

CodePudding user response:

You can write this functionality in less number of code lines:

import random
numbers = [random.randint(0, 100) for i in range(100)]
even = 0
for num in numbers:
    if num % 2 == 0:
        even  = 1
print("Even numbers count:", even)
print("Odd numbers count:", str(100 - even))

Or even (hehe):

import random
nums = [random.randint(0, 100) for i in range(100)]
even, odd = [n for n in nums if n % 2 == 1], [n for n in nums if n % 2 == 0]
print("Even numbers count:", len(even))
print("Odd numbers count:", len(odd))

If you need to split somehow code into separate functions, then it would be appreciable if you could provide more details on your task/assignment/goal.

  • Related