python - 一些输入的输出应该是“错误的数字”,但我没有得到那个输入。我究竟做错了什么?
问题描述
我复制并粘贴了下面的问题。我正在 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')
解决方案
更正:
- 应该
or
没有and
- 如果索引是正确的,则打印水果。如果你不这样做,它会给你
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])
推荐阅读
- python - 使用 Dolfin 创建一维网格
- c# - BTCPay 服务器 AspNetCore Antiforgery Token 无法解密
- reactjs - 如何扩展列并添加水平滚动 Material UI DataGrid
- python-3.x - 使用 7000 聚类绘制大数据
- java - 如何在java中计算2 n次的近似自然对数?
- azure - 使用 Azure Active Directory 或 ADFS 或 AD 的 SSO
- ios - DocC 文档无法在 CentOS 7 上使用 Apache 呈现
- c - 在c中使用链表通过引用传递问题
- google-apps-script - 当前活动单元格输入的 Google Sheet 脚本不得低于先前的输入
- excel - Excel VBA中的数组重置