beginner question (True False help)

wxjmfauth at gmail.com wxjmfauth at gmail.com
Thu Aug 8 02:20:09 EDT 2013


Le mercredi 7 août 2013 10:17:21 UTC+2, eschne... at comcast.net a écrit :
> 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')

-----------

Your loop is not very well organized. It should be
at the same time the "loop" and the "condition tester".
Compare your code with this and note the missing and
unnecessary "batman":


>>> def z():
...     letters = 'abc'
...     c = input('letter: ')
...     while c in letters:
...         print('do stuff')
...         c = input('letter: ')
...     print('end, fin, Schluss')
...     
>>> z()
letter: a
do stuff
letter: b
do stuff
letter: b
do stuff
letter: c
do stuff
letter: n
end, fin, Schluss
>>> 
>>> z()
letter: q
end, fin, Schluss


Variant
It is common to use a infinite loop and to break it
in order to end the job.


>>> def z2():
...     letters = 'abc'
...     while True:
...         c = input('letter: ')
...         if c not in letters:
...             print('end, fin, Schluss')
...             break
...         else:
...             print('do stuff')
...             
>>> z2()
letter: a
do stuff
letter: b
do stuff
letter: a
do stuff
letter: q
end, fin, Schluss


jmf



More information about the Python-list mailing list