Home > Mobile >  (Python) - Seaching an array within a try except
(Python) - Seaching an array within a try except

Time:09-27

I'm fairly new to python and my little brain can't quite comprehend what I'm doing wrong. I'm trying to search an array within the try accept loop and it won't quite work, any input will be much appreciated as i've spent hours trying to figure this out :)

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 ')

CodePudding user response:

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(dictio[code])
    else:
        print("Not valid code")

CodePudding user response:

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

while True:
    if s1c in startcodearray:
        break

    else:
        print('please enter a valid code ')

CodePudding user response:

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')
  • Related