+ 2
How can I make this code more elegant?
Hi everyone! This is my code for a “ Vending machine” exercise. As you may notice it is a bit long. It works fine, taking a number as an input and returning a name of the fruits as an output. The question is how can I get the same result using less rows of a code? Any options of loops or something like iteration through a list? Thank you in advance for your comments! Cheers https://code.sololearn.com/cEU3roIdsax2/?ref=app
5 ответов
+ 4
fruits = ["apple", "cherry", "banana", "kiwi", "lemon", "pear", "peach", "avocado"]
num = int(input())
#your code goes here
if 0 <= num <= 7:
print(fruits[num])
else:
print("Wrong number")
+ 4
fruits = ["apple", "cherry", "banana", "kiwi", "lemon", "pear", "peach", "avocado"]
num = int(input())
try:
print(fruits[num])
except:
print("Wrong number")
+ 1
fruits = ["apple", "cherry", "banana", "kiwi", "lemon", "pear", "peach", "avocado"]
num = int(input())
print fruits[num] if num < len(fruits) else "Wrong number"
0
fruits = ["apple", "cherry", "banana", "kiwi", "lemon", "pear", "peach", "avocado"]
try:
print(fruits[int(input('Enter Choice: '))])
except:
print("Wrong number")