首页 > 解决方案 > 一些输入的输出应该是“错误的数字”,但我没有得到那个输入。我究竟做错了什么?

问题描述

我复制并粘贴了下面的问题。我正在 SoloLearn 上学习 python。问题运行了 5 次测试,我得到了 2 次错误,输出应该是“错误数字”的那些。我看不出我哪里出错了。请帮忙。

想象一下出售水果的自动售货机。每个水果都有自己的编号,从 0 开始。

为自动售货机编写一个程序,它将 n 个数字作为客户的输入,并返回具有该索引的水果。

如果 n<0 或 n>7(最后一个水果的索引),程序输出“错误的数字”。

代码:

fruits = ["apple", "cherry", "banana", "kiwi", "lemon", "pear", "peach", "avocado"]
num = int(input())
#your code goes here

print(fruits[num])
if num<0 and num>7:
   print('Wrong number')

标签: pythonlist

解决方案


更正:

  1. 应该or没有and
  2. 如果索引是正确的,则打印水果。如果你不这样做,它会给你list out of index错误。

fruits = ["apple", "cherry", "banana", "kiwi", "lemon", "pear", "peach", "avocado"]
num = int(input())
#your code goes here

if num<0 or num>7: #<--- here
   print('Wrong number')
else:  # <- added this
    print(fruits[num])

推荐阅读