dner
dner

Reputation: 57

Validating whether raw input is an integer and greater than zero simultaneously in Python

I'm trying to complete a program that will determine whether a number is prime our not. I am trying to add a piece of code that will validate whether user input is both an integer and if so, whether it's a positive integer. I want it to check both of these at the same time, as previously I had it check whether it was an integer first, then check if the number was positive, but if someone entered a string on their second try it caused an error. My code is below:

import math

def is_prime(integer):
    if integer < 2:
        return False
    elif integer == 2:
        return True
    elif not integer & 1:
        return False
    for x in range(3, int(integer**0.5) + 1, 2):
        if integer % x == 0:
            return False
    return True

while True:
    value = input("Please enter a positive integer: ")
    try:
        integer = int(value)
        if integer >= 0:
            break
        else:
            print("The integer must be positive, try again.")
    except ValueError:
        print("This is not an integer, try again.")

if is_prime(integer) == False:
    print "%d is not a prime number." % integer
if is_prime(integer) == True:
    print "%d is a prime number!" % integer

I'm trying to use a while loop to tell the user that their input is invalid, and then ask for input again. Any ideas? Thanks!

EDIT: If I enter a string, I get the following:

>>> python ex19.1.py
Please enter a positive integer: abcd
Traceback (most recent call last):
  File "ex19.1.py", line 16, in <module>
    value = input("Please enter a positive integer: ")
  File "<string>", line 1, in <module>
NameError: name 'abcd' is not defined

Upvotes: 0

Views: 907

Answers (4)

sandeep nagendra
sandeep nagendra

Reputation: 522

Using raw_input()

no  = raw_input("Enter a positive integer number")
if no.isdigit() and int(no) >= 0:
    print "positive no"

Using input()

no = input("Enter a positive integer number")
if str(no).isdigit() and no >= 0:
    print "positive no"

Upvotes: 1

furas
furas

Reputation: 142734

Your have to use raw_input() instead of input() because input() in Python 2 tries to execute inputed text as Python code. When you input abcd it tries to find variable abcd in your code and you get error.

Upvotes: 2

TheClonerx
TheClonerx

Reputation: 343

if not value.isdigit():
    print("This is not an integer, try again.")
elif int(value) < 0:
    print("The integer must be positive, try again.")
else:
    break

Upvotes: 1

Fomalhaut
Fomalhaut

Reputation: 9785

You may use the function isdigit in order to check the string. The function returns True is it consists of digits only:

>>> '123'.isdigit()
True
>>> '123qwe'.isdigit()
False

Upvotes: 0

Related Questions