Guest User

Untitled

a guest
Feb 16th, 2019
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.07 KB | None | 0 0
  1. #note: Python 2.7 users should use `raw_input`, the equivalent of 3.X's `input`
  2. age = int(input("Please enter your age: "))
  3. if age >= 18:
  4. print("You are able to vote in the United States!")
  5. else:
  6. print("You are not able to vote in the United States.")
  7.  
  8. while True:
  9. try:
  10. # Note: Python 2.x users should use raw_input, the equivalent of 3.x's input
  11. age = int(input("Please enter your age: "))
  12. except ValueError:
  13. print("Sorry, I didn't understand that.")
  14. #better try again... Return to the start of the loop
  15. continue
  16. else:
  17. #age was successfully parsed!
  18. #we're ready to exit the loop.
  19. break
  20. if age >= 18:
  21. print("You are able to vote in the United States!")
  22. else:
  23. print("You are not able to vote in the United States.")
  24.  
  25. while True:
  26. data = input("Please enter a loud message (must be all caps): ")
  27. if not data.isupper():
  28. print("Sorry, your response was not loud enough.")
  29. continue
  30. else:
  31. #we're happy with the value given.
  32. #we're ready to exit the loop.
  33. break
  34.  
  35. while True:
  36. data = input("Pick an answer from A to D:")
  37. if data.lower() not in ('a', 'b', 'c', 'd'):
  38. print("Not an appropriate choice.")
  39. else:
  40. break
  41.  
  42. while True:
  43. try:
  44. age = int(input("Please enter your age: "))
  45. except ValueError:
  46. print("Sorry, I didn't understand that.")
  47. continue
  48.  
  49. if age < 0:
  50. print("Sorry, your response must not be negative.")
  51. continue
  52. else:
  53. #age was successfully parsed, and we're happy with its value.
  54. #we're ready to exit the loop.
  55. break
  56. if age >= 18:
  57. print("You are able to vote in the United States!")
  58. else:
  59. print("You are not able to vote in the United States.")
  60.  
  61. def get_non_negative_int(prompt):
  62. while True:
  63. try:
  64. value = int(input(prompt))
  65. except ValueError:
  66. print("Sorry, I didn't understand that.")
  67. continue
  68.  
  69. if value < 0:
  70. print("Sorry, your response must not be negative.")
  71. continue
  72. else:
  73. break
  74. return value
  75.  
  76. age = get_non_negative_int("Please enter your age: ")
  77. kids = get_non_negative_int("Please enter the number of children you have: ")
  78. salary = get_non_negative_int("Please enter your yearly earnings, in dollars: ")
  79.  
  80. def sanitised_input(prompt, type_=None, min_=None, max_=None, range_=None):
  81. if min_ is not None and max_ is not None and max_ < min_:
  82. raise ValueError("min_ must be less than or equal to max_.")
  83. while True:
  84. ui = input(prompt)
  85. if type_ is not None:
  86. try:
  87. ui = type_(ui)
  88. except ValueError:
  89. print("Input type must be {0}.".format(type_.__name__))
  90. continue
  91. if max_ is not None and ui > max_:
  92. print("Input must be less than or equal to {0}.".format(max_))
  93. elif min_ is not None and ui < min_:
  94. print("Input must be greater than or equal to {0}.".format(min_))
  95. elif range_ is not None and ui not in range_:
  96. if isinstance(range_, range):
  97. template = "Input must be between {0.start} and {0.stop}."
  98. print(template.format(range_))
  99. else:
  100. template = "Input must be {0}."
  101. if len(range_) == 1:
  102. print(template.format(*range_))
  103. else:
  104. print(template.format(" or ".join((", ".join(map(str,
  105. range_[:-1])),
  106. str(range_[-1])))))
  107. else:
  108. return ui
  109.  
  110. age = sanitised_input("Enter your age: ", int, 1, 101)
  111. answer = sanitised_input("Enter your answer: ", str.lower, range_=('a', 'b', 'c', 'd'))
  112.  
  113. data = input("Please enter a loud message (must be all caps): ")
  114. while not data.isupper():
  115. print("Sorry, your response was not loud enough.")
  116. data = input("Please enter a loud message (must be all caps): ")
  117.  
  118. def get_non_negative_int(prompt):
  119. try:
  120. value = int(input(prompt))
  121. except ValueError:
  122. print("Sorry, I didn't understand that.")
  123. return get_non_negative_int(prompt)
  124.  
  125. if value < 0:
  126. print("Sorry, your response must not be negative.")
  127. return get_non_negative_int(prompt)
  128. else:
  129. return value
  130.  
  131. age = None
  132. while age is None:
  133. input_value = input("Please enter your age: ")
  134. try:
  135. # try and convert the string input to a number
  136. age = int(input_value)
  137. except ValueError:
  138. # tell the user off
  139. print("{input} is not a number, please enter a number only".format(input=input_value))
  140. if age >= 18:
  141. print("You are able to vote in the United States!")
  142. else:
  143. print("You are not able to vote in the United States.")
  144.  
  145. Please enter your age: *potato*
  146. potato is not a number, please enter a number only
  147. Please enter your age: *5*
  148. You are not able to vote in the United States.
  149.  
  150. f=lambda age: (age.isdigit() and ((int(age)>=18 and "Can vote" ) or "Cannot vote")) or
  151. f(input("invalid input. Try againnPlease enter your age: "))
  152. print(f(input("Please enter your age: ")))
  153.  
  154. def read_single_keypress() -> str:
  155. """Waits for a single keypress on stdin.
  156. -- from :: https://stackoverflow.com/a/6599441/4532996
  157. """
  158.  
  159. import termios, fcntl, sys, os
  160. fd = sys.stdin.fileno()
  161. # save old state
  162. flags_save = fcntl.fcntl(fd, fcntl.F_GETFL)
  163. attrs_save = termios.tcgetattr(fd)
  164. # make raw - the way to do this comes from the termios(3) man page.
  165. attrs = list(attrs_save) # copy the stored version to update
  166. # iflag
  167. attrs[0] &= ~(termios.IGNBRK | termios.BRKINT | termios.PARMRK
  168. | termios.ISTRIP | termios.INLCR | termios. IGNCR
  169. | termios.ICRNL | termios.IXON )
  170. # oflag
  171. attrs[1] &= ~termios.OPOST
  172. # cflag
  173. attrs[2] &= ~(termios.CSIZE | termios. PARENB)
  174. attrs[2] |= termios.CS8
  175. # lflag
  176. attrs[3] &= ~(termios.ECHONL | termios.ECHO | termios.ICANON
  177. | termios.ISIG | termios.IEXTEN)
  178. termios.tcsetattr(fd, termios.TCSANOW, attrs)
  179. # turn off non-blocking
  180. fcntl.fcntl(fd, fcntl.F_SETFL, flags_save & ~os.O_NONBLOCK)
  181. # read a single keystroke
  182. try:
  183. ret = sys.stdin.read(1) # returns a single character
  184. except KeyboardInterrupt:
  185. ret = 0
  186. finally:
  187. # restore old state
  188. termios.tcsetattr(fd, termios.TCSAFLUSH, attrs_save)
  189. fcntl.fcntl(fd, fcntl.F_SETFL, flags_save)
  190. return ret
  191.  
  192. def until_not_multi(chars) -> str:
  193. """read stdin until !(chars)"""
  194. import sys
  195. chars = list(chars)
  196. y = ""
  197. sys.stdout.flush()
  198. while True:
  199. i = read_single_keypress()
  200. _ = sys.stdout.write(i)
  201. sys.stdout.flush()
  202. if i not in chars:
  203. break
  204. y += i
  205. return y
  206.  
  207. def _can_you_vote() -> str:
  208. """a practical example:
  209. test if a user can vote based purely on keypresses"""
  210. print("can you vote? age : ", end="")
  211. x = int("0" + until_not_multi("0123456789"))
  212. if not x:
  213. print("nsorry, age can only consist of digits.")
  214. return
  215. print("your age is", x, "nYou can vote!" if x >= 18 else "Sorry! you can't vote")
  216.  
  217. _can_you_vote()
  218.  
  219. $ ./input_constrain.py
  220. can you vote? age : a
  221. sorry, age can only consist of digits.
  222. $ ./input_constrain.py
  223. can you vote? age : 23<RETURN>
  224. your age is 23
  225. You can vote!
  226. $ _
  227.  
  228. def validate_age(age):
  229. if age >=0 :
  230. return True
  231. return False
  232.  
  233. while True:
  234. try:
  235. age = int(raw_input("Please enter your age:"))
  236. if validate_age(age): break
  237. except ValueError:
  238. print "Error: Invalid age."
  239.  
  240. def takeInput(required):
  241. print 'ooo or OOO to exit'
  242. ans = raw_input('Enter: ')
  243.  
  244. if not ans:
  245. print "You entered nothing...!"
  246. return takeInput(required)
  247.  
  248. ## FOR Exit ##
  249. elif ans in ['ooo', 'OOO']:
  250. print "Closing instance."
  251. exit()
  252.  
  253. else:
  254. if ans.isdigit():
  255. current = 'int'
  256. elif set('[~!@#$%^&*()_+{}":/']+$').intersection(ans):
  257. current = 'other'
  258. elif isinstance(ans,basestring):
  259. current = 'str'
  260. else:
  261. current = 'none'
  262.  
  263. if required == current :
  264. return ans
  265. else:
  266. return takeInput(required)
  267.  
  268. ## pass the value in which type you want [str/int/special character(as other )]
  269. print "input: ", takeInput('str')
  270.  
  271. while True:
  272. try:
  273. age = int(input("Please enter your age: "))
  274. if age >= 18:
  275. print("You are able to vote in the United States!")
  276. break
  277. else:
  278. print("You are not able to vote in the United States.")
  279. break
  280. except ValueError:
  281. print("Please enter a valid response")
  282.  
  283. def getValidInt(iMaxAttemps = None):
  284. iCount = 0
  285. while True:
  286. # exit when maximum attempt limit has expired
  287. if iCount != None and iCount > iMaxAttemps:
  288. return 0 # return as default value
  289.  
  290. i = raw_input("Enter no")
  291. try:
  292. i = int(i)
  293. except ValueError as e:
  294. print "Enter valid int value"
  295. else:
  296. break
  297.  
  298. return i
  299.  
  300. age = getValidInt()
  301. # do whatever you want to do.
  302.  
  303. # If your input value is only a number then use "Value.isdigit() == False".
  304. # If you need an input that is a text, you should remove "Value.isdigit() == False".
  305. def Input(Message):
  306. Value = None
  307. while Value == None or Value.isdigit() == False:
  308. try:
  309. Value = str(input(Message)).strip()
  310. except InputError:
  311. Value = None
  312. return Value
  313.  
  314. # Example:
  315. age = 0
  316. # If we suppose that our age is between 1 and 150 then input value accepted,
  317. # else it's a wrong value.
  318. while age <=0 or age >150:
  319. age = int(Input("Please enter your age: "))
  320. # For terminating program, the user can use 0 key and enter it as an a value.
  321. if age == 0:
  322. print("Terminating ...")
  323. exit(0)
  324.  
  325. if age >= 18 and age <=150:
  326. print("You are able to vote in the United States!")
  327. else:
  328. print("You are not able to vote in the United States.")
  329.  
  330. while True:
  331. age = input("Please enter your age: ")
  332. if age.isdigit():
  333. age = int(age)
  334. break
  335. else:
  336. print("Invalid number '{age}'. Try again.".format(age=age))
  337.  
  338. if age >= 18:
  339. print("You are able to vote in the United States!")
  340. else:
  341. print("You are not able to vote in the United States.")
  342.  
  343. while True:
  344.  
  345. var = True
  346.  
  347. try:
  348. age = int(input("Please enter your age: "))
  349.  
  350. except ValueError:
  351. print("Invalid input.")
  352. var = False
  353.  
  354. if var == True:
  355. if age >= 18:
  356. print("You are able to vote in the United States.")
  357. break
  358. else:
  359. print("You are not able to vote in the United States.")
  360.  
  361. while True:
  362. name = input("Enter Your Namen")
  363. if not name:
  364. print("I did not understood that")
  365. continue
  366. else:
  367. break
  368.  
  369. while True:
  370. try:
  371. salary = float(input("whats ur salaryn"))
  372. except ValueError:
  373. print("I did not understood that")
  374. continue
  375. else:
  376. break
  377.  
  378. while True:
  379. try:
  380. print("whats ur age?")
  381. age = int(float(input()))
  382. except ValueError:
  383. print("I did not understood that")
  384. continue
  385. else:
  386. break
  387.  
  388. print("Hello "+ name + "nYour salary is " + str(salary) + 'nand you will be ' + str(age+1) +' in a Year')
  389.  
  390. #note: Python 2.7 users should use raw_input, the equivalent of 3.X's input
  391. while(1):
  392. try:
  393. age = int(input("Please enter your age: "))
  394. if age >= 18:
  395. print("You are able to vote in the United States!")
  396. break()
  397. else:
  398. print("You are not able to vote in the United States.")
  399. break()
  400. except:
  401. print("Please only enter numbers ")
  402.  
  403. class ValidationError(ValueError):
  404. """Special validation error - its message is supposed to be printed"""
  405. pass
  406.  
  407. def RangeValidator(text,num,r):
  408. """Generic validator - raises 'text' as ValidationError if 'num' not in range 'r'."""
  409. if num in r:
  410. return num
  411. raise ValidationError(text)
  412.  
  413. def ValidCol(c):
  414. """Specialized column validator providing text and range."""
  415. return RangeValidator("Columns must be in the range of 0 to 3 (inclusive)",
  416. c, range(4))
  417.  
  418. def ValidRow(r):
  419. """Specialized row validator providing text and range."""
  420. return RangeValidator("Rows must be in the range of 5 to 15(exclusive)",
  421. r, range(5,15))
  422.  
  423. def GetInt(text, validator=None):
  424. """Aks user for integer input until a valid integer is given. If provided,
  425. a 'validator' function takes the integer and either raises a
  426. ValidationError to be printed or returns the valid number.
  427. Non integers display a simple error message."""
  428. print()
  429. while True:
  430. n = input(text)
  431. try:
  432. n = int(n)
  433.  
  434. return n if validator is None else validator(n)
  435.  
  436. except ValueError as ve:
  437. # prints ValidationErrors directly - else generic message:
  438. if isinstance(ve, ValidationError):
  439. print(ve)
  440. else:
  441. print("Invalid input: ", n)
  442.  
  443.  
  444. column = GetInt("Pleased enter column: ", ValidCol)
  445. row = GetInt("Pleased enter row: ", ValidRow)
  446. print( row, column)
  447.  
  448. Pleased enter column: 22
  449. Columns must be in the range of 0 to 3 (inclusive)
  450. Pleased enter column: -2
  451. Columns must be in the range of 0 to 3 (inclusive)
  452. Pleased enter column: 2
  453. Pleased enter row: a
  454. Invalid input: a
  455. Pleased enter row: 72
  456. Rows must be in the range of 5 to 15(exclusive)
  457. Pleased enter row: 9
  458.  
  459. 9, 2
  460.  
  461. def validate_input(prompt, error_map):
  462. while True:
  463. try:
  464. data = int(input(prompt))
  465. # Insert your non-exception-throwing conditionals here
  466. assert data > 0
  467. return data
  468. # Print whatever text you want the user to see
  469. # depending on how they messed up
  470. except tuple(error_map.keys()) as e:
  471. print(error_map[type(e)])
  472.  
  473. d = {ValueError: 'Integers only', AssertionError: 'Positive numbers only',
  474. KeyboardInterrupt: 'You can never leave'}
  475. user_input = validate_input("Positive number: ", d)
  476.  
  477. # Assuming Python3
  478. import sys
  479.  
  480. class ValidationError(ValueError): # thanks Patrick Artner
  481. pass
  482.  
  483. def validate_input(prompt, cast=str, cond=(lambda x: True), onerror=None):
  484. if onerror==None: onerror = {}
  485. while True:
  486. try:
  487. data = cast(input(prompt))
  488. if not cond(data): raise ValidationError
  489. return data
  490. except tuple(onerror.keys()) as e: # thanks Daniel Q
  491. print(onerror[type(e)], file=sys.stderr)
  492.  
  493. # No validation, equivalent to simple input:
  494. anystr = validate_input("Enter any string: ")
  495.  
  496. # Get a string containing only letters:
  497. letters = validate_input("Enter letters: ",
  498. cond=str.isalpha,
  499. onerror={ValidationError: "Only letters, please!"})
  500.  
  501. # Get a float in [0, 100]:
  502. percentage = validate_input("Percentage? ",
  503. cast=float, cond=lambda x: 0.0<=x<=100.0,
  504. onerror={ValidationError: "Must be between 0 and 100!",
  505. ValueError: "Not a number!"})
  506.  
  507. age = validate_input("Please enter your age: ",
  508. cast=int, cond=lambda a:0<=a<150,
  509. onerror={ValidationError: "Enter a plausible age, please!",
  510. ValueError: "Enter an integer, please!"})
  511. if age >= 18:
  512. print("You are able to vote in the United States!")
  513. else:
  514. print("You are not able to vote in the United States.")
  515.  
  516. from ast import literal_eval
  517.  
  518. ''' This function is used to identify the data type of input data.'''
  519. def input_type(input_data):
  520. try:
  521. return type(literal_eval(input_data))
  522. except (ValueError, SyntaxError):
  523. return str
  524.  
  525. flag = True
  526.  
  527. while(flag):
  528. age = raw_input("Please enter your age: ")
  529.  
  530. if input_type(age)==float or input_type(age)==int:
  531. if eval(age)>=18:
  532. print("You are able to vote in the United States!")
  533. flag = False
  534. elif eval(age)>0 and eval(age)<18:
  535. print("You are not able to vote in the United States.")
  536. flag = False
  537. else: print("Please enter a valid number as your age.")
  538.  
  539. else: print("Sorry, I didn't understand that.")
Add Comment
Please, Sign In to add comment