Home > Back-end >  how to display a list that has numbers when the number is inputted
how to display a list that has numbers when the number is inputted

Time:10-07

options = ["1. Hyundai", "2. Benz", "3. BMW", "4. Honda", "5. Toyota", "6. GMC", "7. Cadillac", "0.Exit"]

for i in options:
    print(i)
answer = int(input("choose a number from the list above "))
for index in range(len(options)):
    if answer == options[0]:
        print(f"{options} is a nice car")


if  answer == 0:
    print("Goodbye")

i would like to know how to get the output "(their option) is a nice car" after they put the number of the car they like.

CodePudding user response:

options = ["1. Hyundai", "2. Benz", "3. BMW", "4. Honda", "5. Toyota", "6. GMC", "7. Cadillac", "0.Exit"]

for i in options:
    print(i)
answer = int(input("choose a number from the list above "))
if  answer == 0:
    print("Goodbye")
else:
    print(f"{options[answer-1]} is a nice car")

CodePudding user response:

We have to print "their car", so we don't need answer==options[index], we just need to print options[0] if answer is 1, options[1] if answer is 2, options[2] if answer is 3, and so on, so your edited code would be:

options = ["1. Hyundai", "2. Benz", "3. BMW", "4. Honda", "5. Toyota", 
"6. GMC", "7. Cadillac", "0.Exit"]

for i in options:
    print(i)
answer = int(input("choose a number from the list above "))
if answer in range(1,8):
    print(f"{options[answer-1]} is a nice car")


elif  answer == 0:
    print("Goodbye")
else:
    print("wrong option chosen")

Check for indentation errors because I've edited it myself while writing answer

CodePudding user response:

For your easiness, I started the list from 0.Exit. So, your code needs to be like this

options = [ "0.Exit", "1. Hyundai", "2. Benz", "3. BMW", "4. Honda", "5. Toyota", "6. GMC", "7. Cadillac", ]

for i in options:
    print(i)
answer = int(input("choose a number from the list above "))
for index in range(len(options)):
    if 0 < answer < len(options):
        print(f"{options[answer]} is a nice car")
        break

if  answer == 0:
    print("Goodbye")
  • Related