如何将随机数加在一起

时间:2019-06-29 00:49:37

标签: python random

number_checker = 0  

for random_variables in range(1,11):  
    import random  
    random = random.randint(1,25)  
    print(random)  
    if random % 2 == 0:  
        print("This number is even")  
        even_numbers = number_checker + random  
    else:  
        print("This number is odd")  
        odd_numbers = number_checker + random    

print("")  
print("This is the sum of even numbers.")  
print(even_numbers)  
print("")  
print("This is the sum of odd numbers.")  
print(odd_numbers)  

1 个答案:

答案 0 :(得分:2)

您应该将随机数添加到even_numbersodd_numbers,而不是number_checker。由于number_checker永不改变,因此您只需将even_numbersodd_numbers设置为循环中产生的最后一个偶数和奇数。

import random

even_numbers = 0
odd_numbers = 0
for _ in range(1,11):
    r = random.randint(1,25)
    print(r)
    if r % 2 == 0:
        print("This number is even")
        even_numbers += r
    else:
        print("This number is odd")
        odd_numbers += r

print("")
print("This is the sum of even numbers.")
print(even_numbers)
print("")
print("This is the sum of odd numbers.")
print(odd_numbers)