[Tutor] Output never stops

Vivek Sant vsant at hcs.harvard.edu
Sun Aug 3 04:50:22 CEST 2008


Hi David,

Simple explanation - you should use if instead of while. A while  
statement executes whatever is in that block again and again until  
the condition becomes false. So your code, the way you have it, first  
checks if the user's input is not -1. If you have typed Lary, it goes  
on to print Lary, hits the end of the while block, and starts back at  
the top, since choice still is not -1. If you change while to if, the  
statement will only be executed once.

Here's a scenario you might want to use a while loop (which might be  
what you were trying to do): suppose you want to keep on asking for  
input if the input is not a quit code, or valid input. To do this,  
you could just put the choice = raw_input line inside the while  
block, and perhaps make sure to initialize choice to '' (an empty  
string or something).

Vivek


On Aug 2, 2008, at 10:21 PM, David wrote:

> David wrote:
>> Very new to python and never programed before. Can not figure out  
>> why the output never stops when I run this in a terminal
>>
>>
>> #!/usr/bin/python
>>
>>
>> choice = raw_input("Enter the name Lary or Joan (-1 to quit): ")
>> while choice != '-1':          person = {'Lary': 43,'Joan': 24}
>>   if choice == 'Lary':
>>       print "Lary's age is:", person.get('Lary')
>>
>>   elif choice == 'Joan':
>>       print "Joan's age is:", person.get('Joan')
>>
>>   else:
>>        print 'Bad Code'
>>
> should have been like this;
>
> #!/usr/bin/python
>
>
> choice = raw_input("Enter the name Lary or Joan (-1 to quit): ")
> while choice != '-1':           person = {'Lary': 43,'Joan': 24}
>   if choice == 'Lary':
>       print "Lary's age is:", person.get('Lary')
>
>   elif choice == 'Joan':
>       print "Joan's age is:", person.get('Joan')
>
>   else:
>        print 'Bad Code'
>
>
> -- 
> Powered by Gentoo GNU/LINUX
> http://www.linuxcrazy.com
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor



More information about the Tutor mailing list