How can I make this code more elegant? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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

27th Oct 2021, 8:14 PM
Petr Ekimov
Petr Ekimov - avatar
5 Answers
+ 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")
27th Oct 2021, 8:22 PM
Per Bratthammar
Per Bratthammar - avatar
+ 4
fruits = ["apple", "cherry", "banana", "kiwi", "lemon", "pear", "peach", "avocado"] num = int(input()) try: print(fruits[num]) except: print("Wrong number")
27th Oct 2021, 8:22 PM
Oma Falk
Oma Falk - avatar
+ 1
fruits = ["apple", "cherry", "banana", "kiwi", "lemon", "pear", "peach", "avocado"] num = int(input()) print fruits[num] if num < len(fruits) else "Wrong number"
27th Oct 2021, 8:41 PM
Devnull
Devnull - avatar
0
Mladen Just don’t forget parentheses when you call functions in Python 3: print(fruits[num] if num < len(fruits) else "Wrong number")
27th Oct 2021, 9:04 PM
Per Bratthammar
Per Bratthammar - avatar
0
fruits = ["apple", "cherry", "banana", "kiwi", "lemon", "pear", "peach", "avocado"] try: print(fruits[int(input('Enter Choice: '))]) except: print("Wrong number")
28th Oct 2021, 1:16 PM
Krishnam Raju M
Krishnam Raju M - avatar