- 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”)
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"
+ 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")
+ 1
Above code passes 4 test conditions
0
You may also do:
if num1 <= num <= num2:
So 2 compares in one if.