I am having a dilemma with my code, first of there was an exercise i had to write that will achieve the following
Exercise
Create a file in order to complete this exercise. Write a program that generates 100 random numbers (in the range of 1-1000) and keeps a count of how many of those random numbers are even and how many are odd. Display the results to the screen as seen in the sample output below. Hint: Use a while loop to loop 100 times.
My result:
import random
num = 0
odd = 0
even = 0
while num < 100:
random.randint(1,1000)
num = num + 1
#print(num)
if random.randint(1,1000)%2==0:
even = even + 1
else:
odd = odd + 1
print ("Out of 100 Random Numbers,",even,"were even and",odd,"were Odd")
Output:
Out of 100 Random Numbers, 50 were even and 50 were Odd
All Gravy !!
Next activity:
Add another while loop which repeats part a 10 times. Display the results to the screen as seen in the sample output below.
With an output like this:
Out of 100 random numbers, 56 were odd, and 44 were even.
Out of 100 random numbers, 60 were odd, and 40 were even.
Out of 100 random numbers, 47 were odd, and 53 were even.
Out of 100 random numbers, 54 were odd, and 46 were even.
Out of 100 random numbers, 48 were odd, and 52 were even.
Out of 100 random numbers, 53 were odd, and 47 were even.
Out of 100 random numbers, 46 were odd, and 54 were even.
Out of 100 random numbers, 52 were odd, and 48 were even.
Out of 100 random numbers, 53 were odd, and 47 were even.
So I have written:
import random
num = 0
odd = 0
even = 0
loop = 0
while loop < 10:
loop = loop +1
while num < 100:
num = num + 1
rand = random.randint(1,1000)
#print(num)
if rand%2==0:
even = even + 1
else:
odd = odd + 1
result = print ("Out of 100 Random Numbers,",even,"were even and",odd,"were Odd")
resulting in Output:
Out of 100 Random Numbers, 50 were even and 50 were Odd
Out of 100 Random Numbers, 50 were even and 50 were Odd
Out of 100 Random Numbers, 50 were even and 50 were Odd
Out of 100 Random Numbers, 50 were even and 50 were Odd
Out of 100 Random Numbers, 50 were even and 50 were Odd
Out of 100 Random Numbers, 50 were even and 50 were Odd
Out of 100 Random Numbers, 50 were even and 50 were Odd
Out of 100 Random Numbers, 50 were even and 50 were Odd
Out of 100 Random Numbers, 50 were even and 50 were Odd
Out of 100 Random Numbers, 50 were even and 50 were Odd
Can one of you fine programmers explain to me why I am getting that result and/or modify the code the get the expect result for the exercise.
An explanation of why its not working and how to fix it would be preferable because you know what they say, give a man a fish he will eat for a day teach him to fish he will eat for a lifetime.
Thanks for your time.