JBarela JBarela - 3 years ago 59
Python Question

creating a python program which ask the user for a number - even odd

I am new to python and I am taking a summer online class to learn python.

Unfortunately, our professor doesn't really do much. We had an assignment that wanted us to make a program (python) which asks the user for a number and it determines whether that number is even or odd. The program needs to keep asking the user for the input until the user hit zero. Well, I actually turned in a code that doesn't work and I got a 100% on my assignment. Needless to say our professor is lazy and really doesn't help much. For my own knowledge I want to know the correct way to do this!!! Here is what I have/had. I am so embarrassed because I know if probably very easy!

counter = 1
num = 1
while num != 0:
counter = counter + 1
num=int(input("Enter number:"))
while num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)

Answer Source

There are a couple of problems with your code:

  • You never use counter, even though you defined it.
  • You have an unnecessary nested while loop. If the number the user inputs is even, then you're code will continue to run the while loop forever.
  • You are incorrectly using the else clause that is available with while loops. See this post for more details.

Here is the corrected code:

while True:
    # Get a number from the user.
    number = int(input('enter a number: '))

    # If the number is zero, then break from the while loop
    # so the program can end.
    if number == 0:
        break

    # Test if the number given is even. If so, let the
    # user know the number was even.
    if number % 2 == 0:
        print('The number', number, 'is even')
    # Otherwise, we know the number is odd. Let the user know this.
    else:
        print('The number', number, 'is odd')

Note that I opted above to use an infinite loop, test if the user input is zero inside of the loop, and then break, rather than testing for this condition in the loop head. In my opinion this is cleaner, but both are functionally equivalent.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download