[Tutor] NEWBIE- how to make a program continue
Andy W
toodles@yifan.net
Wed, 20 Feb 2002 23:30:10 +0800
> I am very NEW to programing. Here is my question. I have written a small
program( with the help of teaching python in 24 hours) I added the year =
input line it works well except i want it to countue doing what it does
utill i tell it to stop. How do I do this?
>
> below is the script i am using
>
> def julian_leap (y) :
> if (y%4) == 0:
> return 1
> return 0
> year = input ( " Type in a year:" )
> if julian_leap (year):
> print year, "is leap"
> else:
> print year, "is not a leap year"
>
>
> Tahnks for ant help offered,
> Robert
Hi Robert,
Seeing as you're new, I'll try to be a little more clear and thorough than I
usually am. No promises though!
To repeat the instructions, you require a loop statement. Using a "while"
statement would be most appropriate I think.
The basics go as follows:
while <test clause>:
statement 1
...
statement n
as long as the <test clause> evaluates to true, the loop will continue. Each
time it will go through to the end, unless told otherwise. To "tell it
otherwise", and make it exit the loop at a certain time, we use the "break"
statement. So
while 1:
break
will exit the loop straight away. To return to the top of the loop, we can
use another statement called "continue".
while 1:
continue
break
That one will continue forever. Don't try it out, because it'll make your
interpreter hang ;)
So there's a few ways we can approach your problem. I'll just look at the
part that needs to be in the loop.
BTW, this isn't tested. I've made one error already tonight, I hope I don't
get myself crucified.
The two most obvious options to me are
1) Use an "always true" loop (ie. while 1:) , and use "break" to get out of
it.
2) Use a variable as the test clause, and set it to exit the loop.
1st way:
while 1:
year = input ( " Type in a year:" )
if julian_leap (year):
print year, "is leap"
else:
print year, "is not a leap year"
keep_going=raw_input("Do you want to keep going, yes or no?")
if keep_going=="no":
break
2nd way:
done=0
while not done:
year = input ( " Type in a year:" )
if julian_leap (year):
print year, "is leap"
else:
print year, "is not a leap year"
keep_going=raw_input("Do you want to keep going, yes or no?")
if keep_going=="no":
done=1
HTH
Andy
>
>
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>