[Tutor] Issue w/ while loops

Peter Otten __peter__ at web.de
Thu Nov 21 12:31:56 CET 2013


Rafael Knuth wrote:

> Hej there,
> 
> I want to use a while loop in a program (version used: Python 3.3.0),
> and I expect it to loop unless the user enters an integer or a
> floating-point number instead of a string.
> 
> print("TIME TRACKING")
> 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!  ")
> 
> print("you worked " + str(hours_worked) + " hours today.")
> 
> When I run the program, it keeps looping even if the condition is met.
> How do I need to modify the program on the 3rd line so that it stops
> looping when the user enters a floating-point number or an integer?

Let's have a look at what input() gives:

>>> input("How many hours did you work today? ")
How many hours did you work today? 1234
'1234'

A human being would understand that I was either very busy or that I lied, 
but from Python's point of view this is just a str containing some digits, 
not an actual number.

Now let's see str() actually is:

>>> str()
''

An empty string. Now int():

>>> int()
0

The integer 0.

So your loop is

while "1234" != "" or 0:
    ...

and following Python's precedence rules it is evaluated as

while ("1234" != "") or 0:
    ...

With that information, can you work out with what input your script would 
terminate (or not enter) the while loop?

Now how can we find out if the string can be converted to a valid (non-
negative) float? You have to check the characters and verify that there are 
at most one ".", at least one digit and no other non-digits.

While it would be a good exercise for you to try and implement the above 
check there is a simpler approach: just try the conversion and catch the 
potential error:

valid = True # we are optimists
try:
    hours_worked = float(hours_worked)
except ValueError:
    valid = False # only executed when the string is not a valid float

Try to integrate this into your script and come back here if you run into 
problems.



More information about the Tutor mailing list