- 1

Python Vending Machine

Hi all, I’m having trouble with the Vending Machine problem. I am able to pass all the tests outside of #4. I have tried testing it with inputs 0-30 and it is coming back with what is should. Unless #4 is a negative number in which case it gives the list in reverse (-1 = avocado, -2 = peach, etc). Thanks for looking over this. fruits = [“apple”, “cherry”, “banana”, “kiwi”, “lemon”, pear”, “peach”, “avocado”] num=int (input()) if num==0 or num<=7: print (fruits[num]) else: print (“Wrong number”)

8th Jun 2021, 4:08 PM
Elise Davis
Elise Davis - avatar
4 Respostas
+ 2
Your if-condition reads "if num is equal to 0 OR num is smaller than/equal to 7" If num = -1, then the condition would evaluate to True, as num == 0 or num <= 7 => 0 == -1 or 0 <= 7 => False or True => True Which means the statement in the if-block will be executed and hence, your if-condition is pretty much useless. Hint: the condition should be "if num is *greater than/equal to* 0 and num is smaller than/equal to 7"
8th Jun 2021, 4:26 PM
XXX
XXX - avatar
+ 1
fruits = ["apple", "cherry", "banana", "kiwi", "lemon", "pear", "peach", "avocado"] val = int(input()) if val==0 or val<=7: print(fruits[val]) else: print("Wrong number")
10th Dec 2021, 5:39 PM
Sarafraz Shaikh
Sarafraz Shaikh - avatar
+ 1
Above code passes 4 test conditions
10th Dec 2021, 5:41 PM
Sarafraz Shaikh
Sarafraz Shaikh - avatar
0
You may also do: if num1 <= num <= num2: So 2 compares in one if.
8th Jun 2021, 4:47 PM
Paul
Paul - avatar