[Tutor] Issue w/ while loops

Dave Angel davea at davea.name
Thu Nov 21 12:44:40 CET 2013


On Thu, 21 Nov 2013 12:00:31 +0100, Rafael Knuth 
<rafael.knuth at gmail.com> wrote:
> hours_worked = input("How many hours did you work today? ")
> while hours_worked != str() or int():
>     hours_worked = input("Can't understand you. Please enter a 
number!  ")

There are two problems with your conditional expression.  First is 
your use of "or"

Suppose you were trying to loop until the user entered "7" or "X".  
You couldn't use
     while  value == "7" or "X":

You would need
      while value == "7" or  value == "X":

The "or" operator is used to combine two boolean expressions, and 
since "X" is truthie, the entire expression would be true.


The second problem is that str() and int() are used to convert 
values, not somehow analyze them.  WIthout arguments to convert, they 
produce default values.  Int() will produce a zero integer, and I 
assume str() will produce the empty string.  Neither is what you want 
to compare.

What you need instead is a technique that'll analyze a string to see 
whether it'll convert to an int or float.  Best way to do that is to 
try to convert it, and see if an exception is thrown.

while True:
try:
    hw = float(hours_worked)
except xxxxxxx as ex:
    hours_worked = input("try again....")

-- 
DaveA



More information about the Tutor mailing list