0

I'm trying to search an array within the try accept loop and it won't quite work.

startCodeArray = ['c1', 'c2', 'c3', 'c4', 'c4', 'c5']
startPriceArray = [1.50, 3.00, 4.50, 6.00, 8.00]

print('please enter your first locations code  \n', startCodeArray, '\n', startPriceArray)
s1c = str(input(''))
while True:
    try:
        s1c in startcodearray
        break
    except:
        print('please enter a valid code ')
martineau
  • 119,623
  • 25
  • 170
  • 301
  • 2
    `if s1c in startcodearray: break` i dont think try-except is needed here. – sittsering Sep 26 '21 at 15:56
  • See the answers to this [question](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) for clues on how to do this. – quamrana Sep 26 '21 at 16:01

4 Answers4

2

Here it is the perfect case to use dictionnary:

startCodeArray = ['c1', 'c2', 'c3', 'c4', 'c4', 'c5']
startPriceArray = [1.50, 3.00, 4.50, 6.00, 8.00]

dictio = {startCodeArray[i]: startPriceArray[i] for i in range(len(startPriceArray))}

while True:
    code = input("Enter code: ")
    if code in dictio:
        print(f'price: {dictio[code]} €')
        break
    else:
        print("Not valid code")
Vincent Bénet
  • 1,212
  • 6
  • 20
1

If you want the while loop to re-ask the user for a value when it's wrong, then you'll want to move the input statement into the while loop. Also you messed up syntax on the break logic. Try this:

print('Please enter your first locations code')
print(startCodeArray)
print(startPriceArray)

while True:
    s1c = input('')
    if s1c in startCodeArray:
        break
    else:
        print('Please enter a valid code')
flakes
  • 21,558
  • 8
  • 41
  • 88
0

Do not use try-except, use if-else -

while True:
    s1c = str(input(''))

    if s1c in startcodearray:
        break

    else:
        print('please enter a valid code ')
PCM
  • 2,881
  • 2
  • 8
  • 30
  • I think this answer could use some explanation about why you moved the call to `input` into the while loop. Good edit, btw. Saved me from commenting on how it wouldn't work! – Chris Sep 26 '21 at 16:06
0

Do not use try and except instead use it statment:

Your code must be like this (at least the same idea) to work

startCodeArray = ['c1', 'c2', 'c3', 'c4', 'c4', 'c5']
startPriceArray = [1.50, 3.00, 4.50, 6.00, 8.00]

userinput = input(f'please enter your first locations code  \n {startCodeArray}\n{startPriceArray}\n>>> ')
while True:
    if userinput in startCodeArray:
        print(f'The price of {userinput} is {startPriceArray[startCodeArray.index(userinput)]}')
        break
    else:
        print('Please enter a valid choice!')
        userinput = input(f'please enter your first locations code  \n {startCodeArray}\n{startPriceArray}\n>>> '
s0n0fj0hn
  • 33
  • 5