0
chemlist = np.array(["carbon dioxide", "co2",
                     "carbon monoxide", "co",
                     "ethane", "c2h6",
                     "methane", "ch4",
                     "nitrogen", "n2",
                     "oxygen", "o2",
                     "water", "h2o (liquid)",
                     "water vapour", "h2o (gas)"])

print(chemlist)
chemical = input("Enter name or the chemical formula of your compound:\n")
chemical = chemical.lower()
print(chemical)

for i in range(len(chemlist)):
    if chemical == chemlist[i]:
        break
    else:
        print("Invalid chemical name. Please input one from the list below:\n")
        print(chemlist)
        chemical = input("Enter name or the chemical formula of your compound again:\n")

temperature = 0
temperature = float(input("Enter your temperature in degrees Kelvin:\n"))

if temperature <= 273.15 or temperature >= 673.15:
    temperature = float(input('Temperature is not in range. Enter your temperature in degrees Kelvin again:\n'))
else:
    break

Hello,

I have been trying to use this code as a test to find whether the user inputs a valid chemical species. However, when i run the code, it returns invalid for whatever i input even if it is the correct element from the array. What is wrong?

I have changed the way i defined the array from surrounding with single quotation marks to double but that also did not work.

Selcuk
  • 57,004
  • 12
  • 102
  • 110
  • When I run the code, the interpreter returns "SyntaxError: 'break' outside loop". It means that you cannot "break" in if-else block. – Lizhi Liu Mar 10 '23 at 02:50
  • After removing else+break at the end of your code, the code is still beyond expectation. In the for-loop, you compare the input string with each entry in the list. However, if you input a chemical name that is not the first chemical of the list (i.e. carbon dioxide), it will enter else branch, and let you enter again. It is incorrect. – Lizhi Liu Mar 10 '23 at 02:56
  • Welcome to Stack Overflow. The problem is that this loop does not make sense as a way to find out whether the string is contained in the list. The overall code should have a `while` loop (because there is not any limit to how many times the user could type an invalid name), and it should not loop over the list (because the list can directly tell you whether it contains something). Please see the linked duplicates. – Karl Knechtel Mar 10 '23 at 03:23

1 Answers1

1

You ask the user for another entry again as soon as you find a non-match, therefore it only works for the first element of your array ("carbon dioxide"). Try this:

while True:
    chemical = input("Enter name or the chemical formula of your compound:\n")
    chemical = chemical.lower()
    print(chemical)
    
    if chemical in chemlist:
        break
    else:
        print("Invalid chemical name. Please input one from the list below:\n")
        print(chemlist)
Selcuk
  • 57,004
  • 12
  • 102
  • 110