[Tutor] loop questions

Steven D'Aprano steve at pearwood.info
Sun Apr 7 01:49:52 CEST 2013


On 07/04/13 08:00, Soliman, Yasmin wrote:
> I have two questions on these simple programs:
>
> 1st why does this loop keep repeating after I enter 'Quit'?

The code you give below is not valid Python code. Please copy and paste *actual* the code you use, do not retype it from memory. I know that it is not valid code because it uses fancy quotes “ ” which do not work in Python, instead of ordinary quotes (actually inch marks) " "


> import calendar
> m = raw_input(“Enter a year: “)
> while m != “Quit”:
>   if calendar.isleap(int(m)):
>    print “%d is a leap year” % (int(m))
>   else:
>    print “%d is not a leap year” % (int(m))


Fixing the above error, it is *not correct* that the loop repeats after entering "Quit". If you enter Quit, the loop will not run at all, not even once. If you enter something else, *anything* else include "quit" or "QUIT" or "Quit " (notice the space at the end), then it will loop forever.

The problem is that your code only asks for a year *once*. The raw_input is outside of the loop, so it only happens once. To get the opportunity to enter a year, or quit, more than once, it needs to be inside the loop.

Also, you should be more forgiving of user input. Instead of checking whether the user enters exactly CAPITAL Q lower u i t you should accept anything that looks like "quit". Use m.strip() to remove any accidental spaces at the beginning or end of the word, and m.lower() to convert to lowercase, then compare against "quit".

(remember that strings are *immutable*, and re-assign the result of the method calls to m)




> 2nd  How can I make this program not crash when a user enters a non integer?
>
> m = raw_input(“Enter an integer: “)
> while not m.isdigit():
>   m = raw_input(“Enter an integer: “)
>   num = int(m)


There are two ways. You can either catch the exception that happens, or avoid calling int. Here's the first way:


# This will work with negative numbers too.
response = raw_input("Enter an integer: ")
try:
     num = int(response)
except ValueError:
     print "%r is not an integer, please try again" % response


Here's the second way:


# This will not work with negative numbers.
response = raw_input("Enter an integer: ")
response = response.strip()  # get rid of any leading or trailing spaces
if response.isdigit():
     num = int(response)
else:
     print "%r is not an integer, please try again" % response



If you want these to repeat multiple times, you need to put them inside a loop.




-- 
Steven


More information about the Tutor mailing list