Jump to content

Recommended Posts

Posted

 

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 

 

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...