-2

Having some difficulty using a While function alongside an IF so that if an INPUT hasn't been met, the same question would be repeatedly asked until the outcome was correct.

county = input(str("County London/Kent/Essex: ")).upper()
while county != ("LONDON") and county != ("KENT") and county != ("ESSEX"):
    if county == ("LONDON"):
        county = ("LONDON")
    elif county == ("KENT"):
        county = ("KENT")
    elif county == ("ESSEX"):
        county = ("ESSEX")
    else:
        county = input(str("Invalid - Please enter an accepted county: ")).upper()

If the user doesn't enter London, Kent or Essex, the input message would be asked until one of these are entered.

JHarris
  • 13
  • 2
  • 1
    As a side suggestion, you can use `while county not in ["LONDON","KENT","ESSEX"]:` – Christian Tapia Mar 03 '17 at 14:00
  • For performance while `county not in ("LONDON","KENT","ESSEX"):` is slightly better ;) – Dmitry Mar 03 '17 at 14:08
  • 1
    what are you asking? I ran your code and it worked as you would think. The loop keeps prompting and exits once one of the three places are input. – Matthias Mar 03 '17 at 14:09
  • `county = ("ESSEX")` evaluates into `county = "ESSEX"` without brackets. Do ypu need to make a tuple? If yes, use `county = ("ESSEX", )` – Dmitry Mar 03 '17 at 14:10
  • @Dmitry Lists and tuples both have O(n) `in` operators. I think you want the set `{"LONDON", "KENT", "ESSEX"}` for O(1) operations. – chepner Mar 03 '17 at 14:14
  • 1
    [Asking the user for input until they give a valid response](http://stackoverflow.com/q/23294658/953482) may be of interest to you. (Not voting to close as duplicate since your question is more "why isn't this specific code working?" than "what's a good way to do this?") – Kevin Mar 03 '17 at 14:27
  • Is this Python 2 or 3? The Python 2 `input` function is rather different to the one in Python 3 and should be avoided. – PM 2Ring Mar 03 '17 at 14:28
  • @chepner i know about complexity issues. But your answer is wrong. In a case of small objects `tuple` is more faster, check it using `timeit`: `python -m timeit 'from random import choice' 'a = choice(["London", "Kent", "Essex"])' 'if a in ("LONDON","KENT","ESSEX"): pass' 1000000 loops, best of 3: 1.11 usec per loop; python -m timeit 'from random import choice' 'a = choice(["London", "Kent", "Essex"])' 'if a in {"LONDON","KENT","ESSEX"}: pass' 1000000 loops, best of 3: 1.22 usec per loop`. In a case of large objects `set` is more appropriate. – Dmitry Mar 03 '17 at 19:18

3 Answers3

0

Let me guess. You are getting an error like

NameError: name 'London' is not defined

The reason for that is the following: input treats what it reads as Python expression, not as string; so when you enter London it tries to interpret it as the variable name named London. Try to enter string instead: "London" -- and it will work.

Example of what input does:

>>> print input("-> ")
-> [1, 2, 3][0] + 4
5

It's 5 because input treats what it reads as Python exrpession. In this case it sees the list of three numbers, takes the first one and adds 4 to it.

You really should not use input(). Do the following:

import sys
...
...
else:
    print "some prompt goes here"
    line = sys.stdin.readline().strip().upper()

Edit: as mentioned in the comment, it's even better to use raw_input() instead of sys.stdin.readline(). Completely forgot about it; did not write programs which read from terminal from quite some time :)

avysk
  • 1,973
  • 12
  • 18
0

Try something like this:

counties = ["London", "Kent", "Essex"] # list of counties
prompt = "County " + "/".join(counties) + ": " # prompt of the input

while True:
    county = raw_input(prompt).title() # using str.title to format the input
    if county in counties: # the input is part of the list
        county = county.upper()
        break
    else: # the input is invalid, try again 
        print "Invalid - Please enter an accepted county."

Note: I used raw_input() instead of input()

Szabolcs
  • 3,990
  • 18
  • 38
0

If you can use Python 3 instead of 2, the code runs smoothly as is.

They changed input() not to evaluate the input as a python expression in 3.4, to work like the old raw_input().

Here's the docs for python 2:

input([prompt])

Equivalent to eval(raw_input(prompt)).

This function does not catch user errors. If the input is not syntactically valid, a SyntaxError will be raised. Other exceptions may be raised if there is an error during evaluation.

If the readline module was loaded, then input() will use it to provide elaborate line editing and history features.

Consider using the raw_input() function for general input from users.

and python 3:

input([prompt])

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised. Example:

>>> s = input('--> ')  
--> Monty Python's Flying Circus
>>> s  
"Monty Python's Flying Circus"

If the readline module was loaded, then input() will use it to provide elaborate line editing and history features.

Matthias
  • 3,160
  • 2
  • 24
  • 38