Yasmin Paksoy
Yasmin Paksoy

Reputation: 35

checking for decimal points using a while loop

I wrote some code to check if two input variables contained decimal points as so:

while "." in n:
    print()
    print("Please enter only integer numbers")
    n = input("Please enter the numerator:")
    d = input("Please enter the denominator:")

while "." in d:
    print()
    print("Please enter only integer numbers")
    n = input("Please enter the numerator:")
    d = input("Please enter the denominator:")

however, I need a way for these loops to be ignored if the decimal is followed by a 0, e.g. 4.0 or 8.0.

Is there a way to do this, or is there a better way to check if the number entered is a decimal? I don't want to make the input a float from the beginning as it also needs to work if the user enters an integer.

The version of python I'm using is 3.5.4.

Upvotes: 2

Views: 1704

Answers (4)

kallqvist
kallqvist

Reputation: 56

Consider comparing them as the actual value types:

while int(float(d)) != float(d) or int(float(n)) != float(n):

Upvotes: 0

Liam
Liam

Reputation: 6429

this the solution you are looking for

while int(float(d)) != float(d) or int(float(n)) != float(n):

other answers won't work for numbers like 8.05

Upvotes: 3

KuboMD
KuboMD

Reputation: 684

To piggy-back off of @public static void main 's answer, you can also consolidate your loop.

while ("." in n and ".0" not in n) or ("." in d and ".0" not in d):
    n = input("Enter the numerator: ")
    d = input("Enter the denominator: ")

Upvotes: 1

Picachieu
Picachieu

Reputation: 3782

Replace this:

while "." in n:

with this:

while "." in n and ".0" not in n:

This makes the code in the loop execute when "." is found in n, but ".0" is not found in n.

Upvotes: 0

Related Questions