Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #note: Python 2.7 users should use `raw_input`, the equivalent of 3.X's `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.")
- while True:
- try:
- # Note: Python 2.x users should use raw_input, the equivalent of 3.x's 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.")
- 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
- 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.")
- 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: ")
- 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
- age = sanitised_input("Enter your age: ", int, 1, 101)
- answer = sanitised_input("Enter your answer: ", str.lower, range_=('a', 'b', 'c', 'd'))
- 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): ")
- 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
- 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.")
- 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.
- f=lambda age: (age.isdigit() and ((int(age)>=18 and "Can vote" ) or "Cannot vote")) or
- f(input("invalid input. Try againnPlease enter your age: "))
- print(f(input("Please enter your age: ")))
- def read_single_keypress() -> str:
- """Waits for a single keypress on stdin.
- -- from :: https://stackoverflow.com/a/6599441/4532996
- """
- 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()
- $ ./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!
- $ _
- 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."
- 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')
- 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")
- 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.
- # 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's 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.")
- 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.")
- 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.")
- while True:
- name = input("Enter Your Namen")
- if not name:
- print("I did not understood that")
- continue
- else:
- break
- while True:
- try:
- salary = float(input("whats ur salaryn"))
- 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')
- #note: Python 2.7 users should use raw_input, the equivalent of 3.X's 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 ")
- 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))
- 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)
- 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
- 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)])
- d = {ValueError: 'Integers only', AssertionError: 'Positive numbers only',
- KeyboardInterrupt: 'You can never leave'}
- user_input = validate_input("Positive number: ", d)
- # 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)
- # 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!"})
- 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.")
- 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.")
Add Comment
Please, Sign In to add comment