Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Homework help
#1
Here's my assignment:
Odd/Even Counter
In this chapter you saw an example of how to design an algorithm that determines whether a number is even or odd (see Returning Boolean Values in Section 6.2). Design a program that generates 100 random numbers, and keeps a count of how many of those random numbers are even and how many are odd.

Here's my code:
HERE'S my question. So my program has random numbers 0-1000, how can I pick 100 random numbers from this group of 1001 numbers using the code I have? We aren't to lists and things like this, we've basically covered, loops and functions. Thanks for any ideas you have.
import random
 
numbers=random.randint(0,1000)
countEven = 0
countOdd = 0
 
for x in range(100):
    if not x % 2
        countEven += 1
    else:
        countOdd += 1
   
print('Number of even numbers :',countEven)
print('Number of odd numbers: ', countOdd)
Reply
#2
You need to pick a new random number each time the loop happens and check its value is odd or even.
Reply
#3
Pls use python code tags so we can see the proper indentation.
You have to generate 100 random numbers, not 1000 says your assignment.

Now you are generating a continuous series of numbers in your loop.
You need to move the random.randint() inside the loop.

Paul
Reply
#4
Read about what randint does.  You do not have 1001 or even 100 random numbers.  You have 1.  You can use randint to generate numbers one at a time or use one of the other functions in the random library that generate a sequence (multiple numbers).

Don't you find it odd that you never use "numbers" after you supposedly fill it with random numbers?

Why are you counting even and odd numbers?  If you are testing 100 numbers and 62 of them are odd, how many even numbers are there?

You can (should) solve this problem without using an if statement.  Think about what x % 2 does and try to think of different ways this could be used to count how many numbers are odd.

This program can be written in four lines (including import random) and still be easy to read and understand.  See how close you can get to that.
Reply
#5
Sorry about the formatting, I edited the post so many times I'm sure I messed that up. Yes, you're working with an old dog whose trying to learn new tricks here.

So, I've been reading through our text and looking up about randint it looks like randrange may be more what I'm wanting.

I also added a line to my OP code that printed the number, yes the same number every time. Thanks for that. Once you pointed that out, and I added the line it was a bit clearer.

Thanks yall for the suggestions. I'm going to keep working on it!
Reply
#6
randint and randrange are nearly identical.  I would look at some of the other random functions that return more than 1 value.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020