[Tutor] Issue w/ while loops
Amit Saha
amitsaha.in at gmail.com
Thu Nov 21 12:44:06 CET 2013
On Thu, Nov 21, 2013 at 9:00 PM, Rafael Knuth <rafael.knuth at gmail.com> 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?
There are two fundamental mistakes in your program:
1. The input() function always returns a string. So, there is no way
to check directly whether the user has entered a number or a string.
2. hours_worked != str() or int() does not do what you want to do. In
Python, str() creates a new string object and similarly int() creates
an integer object, 0.
So, to check whether the input is an integer or float, here is an idea:
>>> def check_input(user_input):
... try:
... user_input = float(user_input)
... except ValueError:
... return 'Invalid input'
... else:
... return user_input
...
>>> check_input('a')
'Invalid input'
>>> check_input('1.5')
1.5
>>> check_input('1')
1.0
The idea above is basically, you convert the input (a string) to a
float. If the input is a number, 1.5 or 1, the check_input() function
will return the numeric equivalent. However, if the number is a
string, it returns invalid input. You could make use of this in your
program above.
Hope that helps.
Best,
Amit.
--
http://echorand.me
More information about the Tutor
mailing list