Alex
Alex

Reputation: 25

Simple function asking for positive integer and verifying input

I'm simply trying to create a function asking for a positive integer and then verifying that the input is indeed a positive integer:

def int_input(x):
    x = input('Please enter a positive integer:')
    if x != type(int()) and x < 1:
        print("This is not a positive integer, try again:")
    else:
        print(x)

int_input(x)

It's giving me "NameError: name 'x' is not defined".

It's so ridiculously simple I feel like I should have found lots of posts on this so maybe I'm blind...

Thanks!

Upvotes: 1

Views: 6951

Answers (3)

Ankit Vallecha
Ankit Vallecha

Reputation: 728

def int_input():
    x = input('Please enter a positive integer:')
    if x != type(int()) and x < 1:
        print("This is not a positive integer, try again:")
    else:
        print(x)

int_input()

It should be like this, you cannt call a function int_input() without declaring x

Upvotes: 2

Indigo
Indigo

Reputation: 962

I believe you mean to have the code reject float values as well as negative values? In this case you need to say or rather than and in your if statement.

def int_input(x):
    if x != type(int()) or x < 1:
        print("This is not a positive integer, try again:")
    else:
        print(x)

x = input('Please enter a positive integer:')
int_input(x)

Additionally, I'm not sure which version of python you are using. 3.x should work fine but if you are using 2.x you will get a fault if the user enters a string. To protect against this you can add an except like this:

def int_input(x):
    if x != type(int()) or x < 1:
        print("This is not a positive integer, try again:")
    else:
        print(x)

try:
    x = input('Please enter a positive integer:')
    int_input(x)
except:
    print("This is not a positive integer, try again:")

Upvotes: 0

lucasnadalutti
lucasnadalutti

Reputation: 5948

You defined the function, and then call it passing x as parameter, but x is indeed not defined in int_input(x)'s scope (global in this case).

Some more correct version of your code would be:

def int_input(x):
    if x != type(int()) and x < 1:
        print("This is not a positive integer, try again:")
    else:
        print(x)

x = input('Please enter a positive integer:')
int_input(x)

Besides, this comparison:

x != type(int())

will always be False since type(int()) will always be int (a type) while x is a value. Oh and you should pass a value to int() too, otherwise it always returns 0.

Upvotes: 0

Related Questions