0

i want to use input validation so that the user can only input decimal numbers. can someone help

while int_x != : #this is where im having the problem
    print "the number entered must be a decimal number"
    int_x = input("Enter a decimal number:")
8
Contributors
8
Replies
15
Views
6 Years
Discussion Span
Last Post by ultimatebuster
Featured Replies
  • Just a try: [CODE]def dec(): x = float(input('enter number: ')) while x % 1 == 0: print ("the number entered must be a decimal number") x = float(input("Enter a decimal number:")) dec() [/CODE] Read More

1

Just a try:

def dec():  
    x = float(input('enter number:  '))    
    while x % 1 == 0:
        print ("the number entered must be a decimal number")
        x = float(input("Enter a decimal number:"))
dec()

Edited by Mensa180: easier fix

0

didn't you said decimals?
Well that works but works for float too!
If decimal is only you want then change float to int like. And using raw_input is better optin IMHO

x = int(raw_input('enter number:  '))
0

Change the code with and try-except block,so it dont crash when letter is the input.

def dec():
    while True:
        try:
            x = float(raw_input('enter number:  '))
            if x % 1 == 0:
                print ("The number entered must be a decimal number")
            else:
                return x
        except ValueError:
            print 'Numer only'       
dec()
0

One way you can do this (Python2 syntax) ...

while True:
    print "the number entered must be a decimal number"
    int_x = raw_input("Enter a decimal number:")
    if int_x.isdigit():
        int_x = int(int_x)
        break

print int_x
0

He did say decimal, so I'm assuming he wants floats.
If it is a float, use the examples given, but instead of

int()

use

float()

Warning.... Python doesn't handle floats too well, so you might have to check out the decimal module in the standard library.

0

Actually I'd like to recommend using a library for input validation (like pycerberus). You get a lot of infrastructure from these library (better code structure, i18n support and good error messages for example) even if you have to build specific validators yourself. IMHO too many people implement half-baked validation rules (and forget to check for all the corner cases!) instead of doing it only once but 100% right... This is also the cause of many security problems...

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.