【问题标题】:Python While loop that accepts only integerPython While循环只接受整数
【发布时间】:2021-11-28 03:33:40
【问题描述】:

我有这个循环,我很难让它接受在线整数。没有字符串。

def addItem(menu, order):
    # get item no from user
    itemNo = int(input('your choice : '))
    # validate item no
    if itemNo == -1:
        return itemNo
    while itemNo not in range(1, len(menu) + 1):
        itemNo = int(input('Invalid input, try again: '))
        if itemNo == -1:
            return itemNo

【问题讨论】:

  • 什么是在线整数?你能发布完整的代码吗?
  • 这里是不是要强制输入:itemNo = int(input('Invalid input, try again: '))取整数仅类型?
  • 您是否尝试过将itemNo = int(input('Invalid input, try again: ')) 放入try .. except 块中,以捕获输入有效整数以外的任何内容时出现的异常?
  • 那是一个错字...我的意思是说只有整数

标签: python loops if-statement while-loop


【解决方案1】:

您可以在执行此操作的函数中放入 try/catch


def get_input():
    not_valid = True
    while not_valid:
        itemNo = input("your choice: ")
        try:
           itemNo = int(itemNo) #Try convert the input to an integer
           return itemNo
        except TypeError: #That fails - start over
            print("Enter only integers!")

并使用它

def addItem(menu, order):
    # get item no from user
    itemNo = get_input()
    # validate item no
    if itemNo == -1:
        return itemNo
    while itemNo not in range(1, len(menu) + 1):
        itemNo = int(input('Invalid input, try again: '))
        if itemNo == -1:
            return itemNo

【讨论】:

    猜你喜欢
    • 2013-01-06
    • 2021-11-24
    • 2012-08-29
    • 1970-01-01
    • 2020-04-29
    • 2015-12-04
    • 2015-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多