首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何为输入重复输入

如何为输入重复输入
EN

Stack Overflow用户
提问于 2019-06-06 06:58:52
回答 4查看 190关注 0票数 -1

我一直在尝试让我的代码对列表进行重复,如果将其留空则可以工作,但如果输入在中断中大于4,我仍在尝试掌握python的诀窍

我试着为这个问题找到一个解决方案,但不知道该怎么做

代码语言:javascript
复制
#Create a list for when they select the computer they want
ComputerList = ["(1)Home Basic $900", "(2)Office $1200", "(3)Gamer $1500", "(4)Studio $2200"]
#Ask them what they want and repeat if left blank
while True:
    ComputerChoice = input("What computer would you like to buy?(Use the number beside it 1-4): ")
    print("")
    try:
        ComputerChoice_int = int(ComputerChoice)
    except ValueError:
        print("You can not leave this blank '%s', try again" % (ComputerChoice,))
        print("")
    else:
        break

我希望它会重复,但它想出了

代码语言:javascript
复制
Traceback (most recent call last):
  File "\\hnhs-fs01\StudentUsers$\17031\Documents\11 DTG\1.7\Assement\Assessment computer.py", line 69, in <module>
    Computer = ComputerList[ComputerChoice_int -1]
IndexError: list index out of range
EN

回答 4

Stack Overflow用户

发布于 2019-06-06 07:23:24

问题出在哪里?这段代码运行得很好。

代码语言:javascript
复制
#Create a list for when they select the computer they want
ComputerList = ["(1)Home Basic $900", "(2)Office $1200", "(3)Gamer $1500", "(4)Studio $2200", "test (5)"]
#Ask them what they want and repeat if left blank
while True:
    print(ComputerList)
    ComputerChoice = input("What computer would you like to buy?(Use the number beside it 1-%s): " % len(ComputerList))
    try:
        ComputerChoice_int = int(ComputerChoice) - 1
        if not -1 < ComputerChoice_int < len(ComputerList):
            raise ValueError
        print("ok")
        break
    except ValueError:
        print("Something went bad :/\n")
票数 0
EN

Stack Overflow用户

发布于 2019-06-06 07:24:40

你可以这样做,使用int(input())会让一切变得更好+你不需要排除错误。

代码语言:javascript
复制
ComputerList = ["(1)Home Basic $900", "(2)Office $1200", "(3)Gamer $1500", "(4)Studio $2200"]

while True:
    ComputerChoice = int(input("What computer would you like to buy?(Use the number beside it 1-4): "))

    if ComputerChoice not in range(1,5):
        print("invalid input")
    else:
        print("You selected {}".format(ComputerList[ComputerChoice-1]))
        # Do whatever here
票数 0
EN

Stack Overflow用户

发布于 2019-06-06 07:28:52

它崩溃是因为你没有捕获大于4的输入的子句。它只会在字段不能转换为整数的情况下引发错误。现在您可以硬编码4 in,但更可靠的方法是使用列表的长度。如果您添加或删除计算机,这将使您的代码更容易更新。

这就是我要做的:

代码语言:javascript
复制
ComputerList = ["(1)Home Basic $900", "(2)Office $1200", "(3)Gamer $1500", "(4)Studio $2200"]

max_integer = len(ComputerList)
status = False 
while status == False:
   try:
      Choice = int(input("enter your choice"))
      if 0 < Choice <= max_integer:
         status = True
   except ValueError:
      print('input is invalid')
      pass

这是可以缩短的,但我把它画了一点,这样你就能明白发生了什么。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56469068

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档