beginner question (True False help)

Larry Hudson orgnut at yahoo.com
Wed Aug 7 22:49:55 EDT 2013


On 08/07/2013 01:17 AM, eschneider92 at comcast.net wrote:
> I'm trying to create an option for the program to repeat if the user types 'y' or 'yes', using true and false values, or otherwise end the program. If anyone could explain to me how to get this code working, I'd appreciate it.
>
> letters='abcdefghijklmn'
> batman=True
> def thingy():
>      print('type letter from a to n')
>      typedletter=input()
>      if typedletter in letters:
>          print('yes')
>      else:
>          print('no')
> def repeat():
>      print('go again?')
>      goagain=input()
>      if goagain in ('y', 'yes'):
>          print('ok')
>      else:
>          print('goodbye')
>          batman=False
> while batman==True:
>      thingy()
>      repeat()
>      print('this is the end')
>
You've already received answers to this, primarily pointing out that batman needs to be declared 
as global in your repeat() function.  Global variables can be read from inside a function 
without declaring them as such, but if you need to change them, they MUST be declared as 
globals, otherwise it will merely create an independant local variable with the same name.

A second possibility is to do away with batman in the repeat() function, and instead return True 
in the 'yes' clause and False in the else clause.  Then in your while loop, change the repeat() 
line to:
     batman = repeat()

A third version (which I would prefer) is to do away with batman altogether (maybe the Penguin 
got 'im??)   ;-)   Use the True/False version of repeat() and change the while loop to:

while True:
     thingy()
     if not repeat():
         break

And finally unindent your final print() line.  The way you have it will print 'The end' every 
time in your loop.  Not what you want, I'm sure.

      -=- Larry -=-




More information about the Python-list mailing list