I have defined a variable in the program but it is not working. The user will input the number to view animals and enter "exit" to end the program. The program will run in a loop.
animals = [camel, lion, deer, goose, bat, rabbit]
x = input("Please enter the number of the habitat you would like to view: ")
while True:
if x != ("exit"):
print(animals[(int(x))])
else: x == ("exit")
print("See you later!")
exit
This will work. Your list elements should be in string format " "
animals = ["camel","lion","deer", "goose", "bat", "rabbit"]
x = int(input("Please enter the number of the habitat you would like to view: "))
while True:
if x != ("exit"):
print(animals[x])
break
elif (x == ("exit")):
print("See you later!")
animals = ["camel", "lion", "deer", "goose", "bat", "rabbit"]
In python , every string value should be written inside double or single quotes
In your code , your list elements were not in quotes.
But yes , its possible to have a list like yours. But then the python recognizes these as variables
From the code you have given , it is understandable that these variables are not assigned a value before
Thus you got the variable error
You have to take input inside the while loop otherwise it will continue printing, and you cannot able to input next time
animals = ["camel", "lion", "deer", "goose", "bat", "rabbit"]
while True:
x = input("Please enter the number of the habitat you would like to view: ")
if x != ("exit"):
print(animals[(int(x))])
else:
x == ("exit")
print("See you later!")
break
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.