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
while num % 2 == 0:
print ("Even", num)
print ("Odd", num)
There are a couple of problems with your code:
counter, even though you defined it.
whileloop. If the number the user inputs is even, then you're code will continue to run the
elseclause that is available with
whileloops. 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.