User request for input until he gives a valid answer

I am writing a program that should receive input from a user.

#note: Python 2.7 users should use `raw_input`, the equivalent of 3.X `input` age = int(input("Please enter your age: ")) if age >= 18: print("You are able to vote in the United States!") else: print("You are not able to vote in the United States.") 

This works as expected if the user enters reasonable data.

 C:\Python\Projects> canyouvote.py Please enter your age: 23 You are able to vote in the United States! 

But if they are mistaken, then he falls:

 C:\Python\Projects> canyouvote.py Please enter your age: dickety six Traceback (most recent call last): File "canyouvote.py", line 1, in <module> age = int(input("Please enter your age: ")) ValueError: invalid literal for int() with base 10: 'dickety six' 

Instead of failing, I would like him to try again to get input. Like this:

 C:\Python\Projects> canyouvote.py Please enter your age: dickety six Sorry, I didn't understand that. Please enter your age: 26 You are able to vote in the United States! 

How can i do this? What if I also wanted to reject values โ€‹โ€‹such as -1 , which is a valid int , but pointless in this context?

+515
python loops validation user-input
source share
21 answers

The easiest way to do this is to put the input method in a while loop. Use continue when you get the wrong input, and break outside the loop when you are satisfied.

When your input may throw an exception

Use try and except to determine when the user enters data that cannot be parsed.

 while True: try: # Note: Python 2.x users should use raw_input, the equivalent of 3.x input age = int(input("Please enter your age: ")) except ValueError: print("Sorry, I didn't understand that.") #better try again... Return to the start of the loop continue else: #age was successfully parsed! #we're ready to exit the loop. break if age >= 18: print("You are able to vote in the United States!") else: print("You are not able to vote in the United States.") 

Implement custom validation rules

If you want to reject values โ€‹โ€‹that Python can successfully parse, you can add your own validation logic.

 while True: data = input("Please enter a loud message (must be all caps): ") if not data.isupper(): print("Sorry, your response was not loud enough.") continue else: #we're happy with the value given. #we're ready to exit the loop. break while True: data = input("Pick an answer from A to D:") if data.lower() not in ('a', 'b', 'c', 'd'): print("Not an appropriate choice.") else: break 

Combining Exception Handling and Custom Validation

Both of the above methods can be combined in one cycle.

 while True: try: age = int(input("Please enter your age: ")) except ValueError: print("Sorry, I didn't understand that.") continue if age < 0: print("Sorry, your response must not be negative.") continue else: #age was successfully parsed, and we're happy with its value. #we're ready to exit the loop. break if age >= 18: print("You are able to vote in the United States!") else: print("You are not able to vote in the United States.") 

Encapsulating it all in function

If you need to ask the user about a lot of different values, it might be useful to put this code in a function so that you don't have to repeat it every time.

 def get_non_negative_int(prompt): while True: try: value = int(input(prompt)) except ValueError: print("Sorry, I didn't understand that.") continue if value < 0: print("Sorry, your response must not be negative.") continue else: break return value age = get_non_negative_int("Please enter your age: ") kids = get_non_negative_int("Please enter the number of children you have: ") salary = get_non_negative_int("Please enter your yearly earnings, in dollars: ") 

Putting it all together

You can extend this idea to make a very general input function:

 def sanitised_input(prompt, type_=None, min_=None, max_=None, range_=None): if min_ is not None and max_ is not None and max_ < min_: raise ValueError("min_ must be less than or equal to max_.") while True: ui = input(prompt) if type_ is not None: try: ui = type_(ui) except ValueError: print("Input type must be {0}.".format(type_.__name__)) continue if max_ is not None and ui > max_: print("Input must be less than or equal to {0}.".format(max_)) elif min_ is not None and ui < min_: print("Input must be greater than or equal to {0}.".format(min_)) elif range_ is not None and ui not in range_: if isinstance(range_, range): template = "Input must be between {0.start} and {0.stop}." print(template.format(range_)) else: template = "Input must be {0}." if len(range_) == 1: print(template.format(*range_)) else: print(template.format(" or ".join((", ".join(map(str, range_[:-1])), str(range_[-1]))))) else: return ui 

Using such as:

 age = sanitised_input("Enter your age: ", int, 1, 101) answer = sanitised_input("Enter your answer: ", str.lower, range_=('a', 'b', 'c', 'd')) 

Common traps and why they should be avoided

Excessive use of redundant input statements

This method works, but is usually considered bad style:

 data = input("Please enter a loud message (must be all caps): ") while not data.isupper(): print("Sorry, your response was not loud enough.") data = input("Please enter a loud message (must be all caps): ") 

It may initially look attractive because it is shorter than the while True method, but it violates the Do Not Repeat Software Development principle. This increases the likelihood of errors in your system. What if you want to do a backport in 2.7 by changing the input to raw_input , but accidentally change only the first input above? This SyntaxError just waiting for this to happen.

Recursion will blow your stack

If you just learned about recursion, you might want to use it in get_non_negative_int so that you can get rid of the while loop.

 def get_non_negative_int(prompt): try: value = int(input(prompt)) except ValueError: print("Sorry, I didn't understand that.") return get_non_negative_int(prompt) if value < 0: print("Sorry, your response must not be negative.") return get_non_negative_int(prompt) else: return value 

In most cases, this works fine, but if the user enters incorrect data many times, the script exits with RuntimeError: maximum recursion depth exceeded . You might think that โ€œnot a single fool will make 1000 mistakes in a row,โ€ but you underestimate the ingenuity of fools!

+628
source share

Why do you need to do while True and then exit this loop, while you can just put your requirements in a while statement, since all you need to do is stop if you have age?

 age = None while age is None: input_value = input("Please enter your age: ") try: # try and convert the string input to a number age = int(input_value) except ValueError: # tell the user off print("{input} is not a number, please enter a number only".format(input=input_value)) if age >= 18: print("You are able to vote in the United States!") else: print("You are not able to vote in the United States.") 

This will result in the following:

 Please enter your age: *potato* potato is not a number, please enter a number only Please enter your age: *5* You are not able to vote in the United States. 

this will work because age will never make a difference that doesn't make sense, and the code follows the logic of your "business process"

+33
source share

Although the accepted answer is amazing. I would also like to share a quick hack for this problem. (It also solves the problem of negative age.)

 f=lambda age: (age.isdigit() and ((int(age)>=18 and "Can vote" ) or "Cannot vote")) or \ f(input("invalid input. Try again\nPlease enter your age: ")) print(f(input("Please enter your age: "))) 

PS This code is for Python 3.x.

+21
source share

So, I recently messed around with something similar to this, and I came up with the following solution, which uses an input method that rejects unwanted information before it can be verified in any logical way.

read_single_keypress() courtesy of https://stackoverflow.com/a/168295/

 def read_single_keypress() -> str: """Waits for a single keypress on stdin. -- from :: /questions/21608/how-do-i-make-python-to-wait-for-a-pressed-key/160320#160320 """ import termios, fcntl, sys, os fd = sys.stdin.fileno() # save old state flags_save = fcntl.fcntl(fd, fcntl.F_GETFL) attrs_save = termios.tcgetattr(fd) # make raw - the way to do this comes from the termios(3) man page. attrs = list(attrs_save) # copy the stored version to update # iflag attrs[0] &= ~(termios.IGNBRK | termios.BRKINT | termios.PARMRK | termios.ISTRIP | termios.INLCR | termios. IGNCR | termios.ICRNL | termios.IXON ) # oflag attrs[1] &= ~termios.OPOST # cflag attrs[2] &= ~(termios.CSIZE | termios. PARENB) attrs[2] |= termios.CS8 # lflag attrs[3] &= ~(termios.ECHONL | termios.ECHO | termios.ICANON | termios.ISIG | termios.IEXTEN) termios.tcsetattr(fd, termios.TCSANOW, attrs) # turn off non-blocking fcntl.fcntl(fd, fcntl.F_SETFL, flags_save & ~os.O_NONBLOCK) # read a single keystroke try: ret = sys.stdin.read(1) # returns a single character except KeyboardInterrupt: ret = 0 finally: # restore old state termios.tcsetattr(fd, termios.TCSAFLUSH, attrs_save) fcntl.fcntl(fd, fcntl.F_SETFL, flags_save) return ret def until_not_multi(chars) -> str: """read stdin until !(chars)""" import sys chars = list(chars) y = "" sys.stdout.flush() while True: i = read_single_keypress() _ = sys.stdout.write(i) sys.stdout.flush() if i not in chars: break y += i return y def _can_you_vote() -> str: """a practical example: test if a user can vote based purely on keypresses""" print("can you vote? age : ", end="") x = int("0" + until_not_multi("0123456789")) if not x: print("\nsorry, age can only consist of digits.") return print("your age is", x, "\nYou can vote!" if x >= 18 else "Sorry! you can't vote") _can_you_vote() 

You can find the full module here .

Example:

 $ ./input_constrain.py can you vote? age : a sorry, age can only consist of digits. $ ./input_constrain.py can you vote? age : 23<RETURN> your age is 23 You can vote! $ _ 

Note that the nature of this implementation is that it closes standard input as soon as something that is not a number is read. I did not press enter after a , but I needed after numbers.

You can combine this with thismany() in the same module to allow, say, only three digits.

+11
source share

Functional approach or โ€œlook, mom without loops!โ€:

 from itertools import chain, repeat prompts = chain(["Enter a number: "], repeat("Not a number! Try again: ")) replies = map(input, prompts) valid_response = next(filter(str.isdigit, replies)) print(valid_response) 
 Enter a number: a Not a number! Try again: b Not a number! Try again: 1 1 

or if you want the "incorrect input" message to be separated from the input request, as in other answers:

 prompt_msg = "Enter a number: " bad_input_msg = "Sorry, I didn't understand that." prompts = chain([prompt_msg], repeat('\n'.join([bad_input_msg, prompt_msg]))) replies = map(input, prompts) valid_response = next(filter(str.isdigit, replies)) print(valid_response) 
 Enter a number: a Sorry, I didn't understand that. Enter a number: b Sorry, I didn't understand that. Enter a number: 1 1 

How it works?

  1.  prompts = chain(["Enter a number: "], repeat("Not a number! Try again: ")) 
    This combination of itertools.chain and itertools.repeat will create an iterator that itertools.repeat lines "Enter a number: " once, and "Not a number! Try again: " infinite number of times:
     for prompt in prompts: print(prompt) 
     Enter a number: Not a number! Try again: Not a number! Try again: Not a number! Try again: # ... and so on 
  2. replies = map(input, prompts) - here map will apply all prompts lines from the previous step to the input function. For example.:
     for reply in replies: print(reply) 
     Enter a number: a a Not a number! Try again: 1 1 Not a number! Try again: it does not care now it does not care now # and so on... 
  3. We use filter and str.isdigit to filter out strings containing only numbers:
     only_digits = filter(str.isdigit, replies) for reply in only_digits: print(reply) 
     Enter a number: a Not a number! Try again: 1 1 Not a number! Try again: 2 2 Not a number! Try again: b Not a number! Try again: # and so on... 
    And to get only the first line, consisting only of numbers, we use next .

Other validation rules:

  1. String methods: Of course, you can use other string methods such as str.isalpha to get only alphabetic strings, or str.isupper to get only uppercase letters. See the docs for a complete list.

  2. Membership Testing:
    There are several different ways to do this. One of them is using the __contains__ method:

     from itertools import chain, repeat fruits = {'apple', 'orange', 'peach'} prompts = chain(["Enter a fruit: "], repeat("I don't know this one! Try again: ")) replies = map(input, prompts) valid_response = next(filter(fruits.__contains__, replies)) print(valid_response) 
     Enter a fruit: 1 I don't know this one! Try again: foo I don't know this one! Try again: apple apple 
  3. Comparison of numbers:
    There are useful comparison methods that we can use here. For example, for __lt__ ( < ):

     from itertools import chain, repeat prompts = chain(["Enter a positive number:"], repeat("I need a positive number! Try again:")) replies = map(input, prompts) numeric_strings = filter(str.isnumeric, replies) numbers = map(float, numeric_strings) is_positive = (0.).__lt__ valid_response = next(filter(is_positive, numbers)) print(valid_response) 
     Enter a positive number: a I need a positive number! Try again: -5 I need a positive number! Try again: 0 I need a positive number! Try again: 5 5.0 

    Or, if you don't like the use of more complex methods (dunder = double underscore), you can always define your own functions or use functions from the operator module.

  4. Way of Existence:
    Here you can use the pathlib library and its Path.exists method:

     from itertools import chain, repeat from pathlib import Path prompts = chain(["Enter a path: "], repeat("This path does not exist! Try again: ")) replies = map(input, prompts) paths = map(Path, replies) valid_response = next(filter(Path.exists, paths)) print(valid_response) 
     Enter a path: abc This path does not exist! Try again: 1 This path does not exist! Try again: existing_file.txt existing_file.txt 

Attempt limit:

If you do not want to torture the user by asking him something an infinite number of times, you can specify a restriction in calling itertools.repeat . This can be combined with providing a default value for the next function:

 from itertools import chain, repeat prompts = chain(["Enter a number:"], repeat("Not a number! Try again:", 2)) replies = map(input, prompts) valid_response = next(filter(str.isdigit, replies), None) print("You've failed miserably!" if valid_response is None else 'Well done!') 
 Enter a number: a Not a number! Try again: b Not a number! Try again: c You've failed miserably! 

Input preprocessing:

Sometimes we donโ€™t want to reject input if the user accidentally provided it with IN CAPS or with a space at the beginning or end of the line. To take these simple errors into account, we can pre-process the input using the str.lower and str.strip . For example, in the case of membership testing, the code would look like this:

 from itertools import chain, repeat fruits = {'apple', 'orange', 'peach'} prompts = chain(["Enter a fruit: "], repeat("I don't know this one! Try again: ")) replies = map(input, prompts) lowercased_replies = map(str.lower, replies) stripped_replies = map(str.strip, lowercased_replies) valid_response = next(filter(fruits.__contains__, stripped_replies)) print(valid_response) 
 Enter a fruit: duck I don't know this one! Try again: Orange orange 

In the case where you have many functions that you can use for preprocessing, it may be easier to use a function that composes the functions . For example, using here :

 from itertools import chain, repeat from lz.functional import compose fruits = {'apple', 'orange', 'peach'} prompts = chain(["Enter a fruit: "], repeat("I don't know this one! Try again: ")) replies = map(input, prompts) process = compose(str.strip, str.lower) # you can add more functions here processed_replies = map(process, replies) valid_response = next(filter(fruits.__contains__, processed_replies)) print(valid_response) 
 Enter a fruit: potato I don't know this one! Try again: PEACH peach 

Combining validation rules:

For example, for the simple case when the program asks for an age from 1 to 120 years, you can simply add another filter :

 from itertools import chain, repeat prompt_msg = "Enter your age (1-120): " bad_input_msg = "Wrong input." prompts = chain([prompt_msg], repeat('\n'.join([bad_input_msg, prompt_msg]))) replies = map(input, prompts) numeric_replies = filter(str.isdigit, replies) ages = map(int, numeric_replies) positive_ages = filter((0).__lt__, ages) not_too_big_ages = filter((120).__ge__, positive_ages) valid_response = next(not_too_big_ages) print(valid_response) 

But in the case where there are many rules, it is better to implement a function that performs a logical connection . In the following example, I will use the finished one from here :

 from functools import partial from itertools import chain, repeat from lz.logical import conjoin def is_one_letter(string: str) -> bool: return len(string) == 1 rules = [str.isalpha, str.isupper, is_one_letter, 'C'.__le__, 'P'.__ge__] prompt_msg = "Enter a letter (CP): " bad_input_msg = "Wrong input." prompts = chain([prompt_msg], repeat('\n'.join([bad_input_msg, prompt_msg]))) replies = map(input, prompts) valid_response = next(filter(conjoin(*rules), replies)) print(valid_response) 
 Enter a letter (CP): 5 Wrong input. Enter a letter (CP): f Wrong input. Enter a letter (CP): CDE Wrong input. Enter a letter (CP): Q Wrong input. Enter a letter (CP): N N 

Unfortunately, if someone needs a custom message for each unsuccessful case, then, I'm afraid there is no sufficiently functional way. Or at least I could not find.

+5
source share
 def validate_age(age): if age >=0 : return True return False while True: try: age = int(raw_input("Please enter your age:")) if validate_age(age): break except ValueError: print "Error: Invalid age." 
+3
source share

To edit the code and fix the error:

 while True: try: age = int(input("Please enter your age: ")) if age >= 18: print("You are able to vote in the United States!") break else: print("You are not able to vote in the United States.") break except ValueError: print("Please enter a valid response") 
+3
source share

Use Click :

Click is a command line interface library that provides functionality for requesting the right response from the user.

A simple example:

 import click number = click.prompt('Please enter a number', type=float) print(number) 
 Please enter a number: a Error: a is not a valid floating point value Please enter a number: 10 10.0 

Notice how it automatically converted the string value to a floating-point number.

Check if the value is within the range:

There are different user types . To get a number in a specific range, we can use IntRange :

 age = click.prompt("What your age?", type=click.IntRange(1, 120)) print(age) 
 What your age?: a Error: a is not a valid integer What your age?: 0 Error: 0 is not in the valid range of 1 to 120. What your age?: 5 5 

We can also specify only one of the restrictions, min or max :

 age = click.prompt("What your age?", type=click.IntRange(min=14)) print(age) 
 What your age?: 0 Error: 0 is smaller than the minimum valid value 14. What your age?: 18 18 

Membership Testing:

Using the type click.Choice . By default, this check is case sensitive.

 choices = {'apple', 'orange', 'peach'} choice = click.prompt('Provide a fruit', type=click.Choice(choices, case_sensitive=False)) print(choice) 
 Provide a fruit (apple, peach, orange): banana Error: invalid choice: banana. (choose from apple, peach, orange) Provide a fruit (apple, peach, orange): OrAnGe orange 

Work with paths and files:

Using the type click.Path , we can check the existing paths and also allow them:

 path = click.prompt('Provide path', type=click.Path(exists=True, resolve_path=True)) print(path) 
 Provide path: nonexistent Error: Path "nonexistent" does not exist. Provide path: existing_folder '/path/to/existing_folder 

Reading and writing files can be done by click.File :

 file = click.prompt('In which file to write data?', type=click.File('w')) with file.open(): file.write('Hello!') # More info about 'lazy=True' at: # https://click.palletsprojects.com/en/7.x/arguments/#file-opening-safety file = click.prompt('Which file you wanna read?', type=click.File(lazy=True)) with file.open(): print(file.read()) 
 In which file to write data?: # <-- provided an empty string, which is an illegal name for a file In which file to write data?: some_file.txt Which file you wanna read?: nonexistent.txt Error: Could not open file: nonexistent.txt: No such file or directory Which file you wanna read?: some_file.txt Hello! 

Other examples:

Password confirmation:

 password = click.prompt('Enter password', hide_input=True, confirmation_prompt=True) print(password) 
 Enter password: ยทยทยทยทยทยท Repeat for confirmation: ยท Error: the two entered values do not match Enter password: ยทยทยทยทยทยท Repeat for confirmation: ยทยทยทยทยทยท qwerty 

Default Values:

In this case, just pressing Enter (or any other key that you use) without entering a value will give you the default value:

 number = click.prompt('Please enter a number', type=int, default=42) print(number) 
 Please enter a number [42]: a Error: a is not a valid integer Please enter a number [42]: 42 
+3
source share

Based on the remarkable suggestions of Daniel Q and Patrick Artner, an even more generalized solution is presented here.

 # Assuming Python3 import sys class ValidationError(ValueError): # thanks Patrick Artner pass def validate_input(prompt, cast=str, cond=(lambda x: True), onerror=None): if onerror==None: onerror = {} while True: try: data = cast(input(prompt)) if not cond(data): raise ValidationError return data except tuple(onerror.keys()) as e: # thanks Daniel Q print(onerror[type(e)], file=sys.stderr) 

I chose explicit if and raise instead of assert because assertion checking can be turned off while checking should always be done to ensure reliability.

This can be used to get different types of input with different verification conditions. For example:

 # No validation, equivalent to simple input: anystr = validate_input("Enter any string: ") # Get a string containing only letters: letters = validate_input("Enter letters: ", cond=str.isalpha, onerror={ValidationError: "Only letters, please!"}) # Get a float in [0, 100]: percentage = validate_input("Percentage? ", cast=float, cond=lambda x: 0.0<=x<=100.0, onerror={ValidationError: "Must be between 0 and 100!", ValueError: "Not a number!"}) 

Or, to answer the original question:

 age = validate_input("Please enter your age: ", cast=int, cond=lambda a:0<=a<150, onerror={ValidationError: "Enter a plausible age, please!", ValueError: "Enter an integer, please!"}) if age >= 18: print("You are able to vote in the United States!") else: print("You are not able to vote in the United States.") 
+2
source share

Try the following: -

 def takeInput(required): print 'ooo or OOO to exit' ans = raw_input('Enter: ') if not ans: print "You entered nothing...!" return takeInput(required) ## FOR Exit ## elif ans in ['ooo', 'OOO']: print "Closing instance." exit() else: if ans.isdigit(): current = 'int' elif set('[ ~!@ #$%^&*()_+{}":/\']+$').intersection(ans): current = 'other' elif isinstance(ans,basestring): current = 'str' else: current = 'none' if required == current : return ans else: return takeInput(required) ## pass the value in which type you want [str/int/special character(as other )] print "input: ", takeInput('str') 
+1
source share

While the try / except block will work, a much faster and cleaner way to accomplish this task would be to use str.isdigit() .

 while True: age = input("Please enter your age: ") if age.isdigit(): age = int(age) break else: print("Invalid number '{age}'. Try again.".format(age=age)) if age >= 18: print("You are able to vote in the United States!") else: print("You are not able to vote in the United States.") 
0
source share

Use try catch with an infinite loop. To check for an empty string, use the IF statement to check if the string is empty.

 while True: name = input("Enter Your Name\n") if not name: print("I did not understood that") continue else: break while True: try: salary = float(input("whats ur salary\n")) except ValueError: print("I did not understood that") continue else: break while True: try: print("whats ur age?") age = int(float(input())) except ValueError: print("I did not understood that") continue else: break print("Hello "+ name + "\nYour salary is " + str(salary) + '\nand you will be ' + str(age+1) +' in a Year') 
0
source share

This will continue by asking the user to enter a number until the correct number is entered:

 #note: Python 2.7 users should use raw_input, the equivalent of 3.X input while(1): try: age = int(input("Please enter your age: ")) if age >= 18: print("You are able to vote in the United States!") break() else: print("You are not able to vote in the United States.") break() except: print("Please only enter numbers ") 
0
source share

Another solution for using input validation using a custom ValidationError and (optional) range for integer inputs:

 class ValidationError(ValueError): """Special validation error - its message is supposed to be printed""" pass def RangeValidator(text,num,r): """Generic validator - raises 'text' as ValidationError if 'num' not in range 'r'.""" if num in r: return num raise ValidationError(text) def ValidCol(c): """Specialized column validator providing text and range.""" return RangeValidator("Columns must be in the range of 0 to 3 (inclusive)", c, range(4)) def ValidRow(r): """Specialized row validator providing text and range.""" return RangeValidator("Rows must be in the range of 5 to 15(exclusive)", r, range(5,15)) 

Using:

 def GetInt(text, validator=None): """Aks user for integer input until a valid integer is given. If provided, a 'validator' function takes the integer and either raises a ValidationError to be printed or returns the valid number. Non integers display a simple error message.""" print() while True: n = input(text) try: n = int(n) return n if validator is None else validator(n) except ValueError as ve: # prints ValidationErrors directly - else generic message: if isinstance(ve, ValidationError): print(ve) else: print("Invalid input: ", n) column = GetInt("Pleased enter column: ", ValidCol) row = GetInt("Pleased enter row: ", ValidRow) print( row, column) 

Exit:

 Pleased enter column: 22 Columns must be in the range of 0 to 3 (inclusive) Pleased enter column: -2 Columns must be in the range of 0 to 3 (inclusive) Pleased enter column: 2 Pleased enter row: a Invalid input: a Pleased enter row: 72 Rows must be in the range of 5 to 15(exclusive) Pleased enter row: 9 9, 2 
0
source share

Good question! .

ast.literal_eval(), ( age ). :

  1. age .

    1.1. age float int :

    • , age>=18 . age>=18 , .

    • , 0<age<18 . 0<age<18 , .

    • age<=0 , (.. 1.)

    1.2. age float int , (.. 1.)

Here is the code

 from ast import literal_eval ''' This function is used to identify the data type of input data.''' def input_type(input_data): try: return type(literal_eval(input_data)) except (ValueError, SyntaxError): return str flag = True while(flag): age = raw_input("Please enter your age: ") if input_type(age)==float or input_type(age)==int: if eval(age)>=18: print("You are able to vote in the United States!") flag = False elif eval(age)>0 and eval(age)<18: print("You are not able to vote in the United States.") flag = False else: print("Please enter a valid number as your age.") else: print("Sorry, I didn't understand that.") 
0
source share

:

 def askName(): return input("Write your name: ").strip() or askName() name = askName() 

 def askAge(): try: return int(input("Enter your age: ")) except ValueError: return askAge() age = askAge() 

, , :

 def askAge(): try: return int(input("Enter your age: ")) except ValueError: return askAge() age = askAge() responseAge = [ "You are able to vote in the United States!", "You are not able to vote in the United States.", ][int(age < 18)] print(responseAge) 
0
source share

if-else if for .

 while True: age = int(input("Please enter your age: ")) if (age >= 18) : print("You are able to vote in the United States!") if (age < 18) & (age > 0): print("You are not able to vote in the United States.") else: print("Wrong characters, the input must be numeric") continue 

, .

0
source share

, , .

 def getValidInt(iMaxAttemps = None): iCount = 0 while True: # exit when maximum attempt limit has expired if iCount != None and iCount > iMaxAttemps: return 0 # return as default value i = raw_input("Enter no") try: i = int(i) except ValueError as e: print "Enter valid int value" else: break return i age = getValidInt() # do whatever you want to do. 
-one
source share

"while", , null, . . , 1 150, , . 0 .

: .

 # If your input value is only a number then use "Value.isdigit() == False". # If you need an input that is a text, you should remove "Value.isdigit() == False". def Input(Message): Value = None while Value == None or Value.isdigit() == False: try: Value = str(input(Message)).strip() except InputError: Value = None return Value # Example: age = 0 # If we suppose that our age is between 1 and 150 then input value accepted, # else it a wrong value. while age <=0 or age >150: age = int(Input("Please enter your age: ")) # For terminating program, the user can use 0 key and enter it as an a value. if age == 0: print("Terminating ...") exit(0) if age >= 18 and age <=150: print("You are able to vote in the United States!") else: print("You are not able to vote in the United States.") 
-one
source share

while True loop, , , . try except blocks .

 while True: var = True try: age = int(input("Please enter your age: ")) except ValueError: print("Invalid input.") var = False if var == True: if age >= 18: print("You are able to vote in the United States.") break else: print("You are not able to vote in the United States.") 

The var variable is such that if the user enters a string instead of an integer, the program will not return "You cannot vote in the United States."

-one
source share

Here's a cleaner, more generalized solution that avoids repeating if / else blocks: write a function that accepts pairs (error, error) in the dictionary and performs all your value checks using statements.

 def validate_input(prompt, error_map): while True: try: data = int(input(prompt)) # Insert your non-exception-throwing conditionals here assert data > 0 return data # Print whatever text you want the user to see # depending on how they messed up except tuple(error_map.keys()) as e: print(error_map[type(e)]) 

Using:

 d = {ValueError: 'Integers only', AssertionError: 'Positive numbers only', KeyboardInterrupt: 'You can never leave'} user_input = validate_input("Positive number: ", d) 
-one
source share

All Articles