Jump to content

How can we ensure that the user enters only positive integers in a Python program?


SubhanUllah

Recommended Posts

 

I would use a function But you can just put the code anywhere

def get_pos_int(prompt='Please enter a positive Integer:'): 
    while True: 
        inp = input(prompt) 
        try: 
            num = int(inp) 
        except ValueError: 
            print(f"{inp} was not an Integer") 
            continue 
        else: 
            if num < 0: 
                print(f"{num} is not a positive Integer") 
                continue 
            else: 
                break 
    return num 
 
a = 1 + get_pos_int("Please enter a number to add to one:")  
 
print(f"result was {a}") 
 
b = get_pos_int() 
print (f"got {b} back") 
Output

python get_positive.py  
Please enter a number to add to one:-12 
-12 is not a positive Integer 
Please enter a number to add to one:A 
A was not an integer 
Please enter a number to add to one:4 
result was 5 
Please enter a positive Integer:10 
got 10 back 

 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...