【问题标题】:Request re-input from user if input is not integer [duplicate]如果输入不是整数,则请求用户重新输入[重复]
【发布时间】:2019-10-17 20:18:14
【问题描述】:
While True:
    n=turtle.textinput(“”,”write your grade”)
    grade = int(n)

    while int(n) != grade :
        n=turtle.textinput(“”,”use only number”)
        grade = int(n)

    If grade <=100 and grade>=95 :
        print(“A+“)
    else :
        print(“F”)

我收到值错误。

我想了解情况

【问题讨论】:

  • int(n)!=? 不等于什么?试试这个,n.isalpha() 检查n 是否包含字母!
  • 如果你想要比较 int(n),因为此时你将它与“无”进行比较
  • 我认为你的意思是像try: int(n) except ValueError: doSomething
  • 内部循环会以任何方式执行吗?您在循环之前将它们设置为相等,并且下一行检查相反的情况。

标签: python valueerror


【解决方案1】:

我想你是想试试这个

def enforce_int(x):
    try:
        _ = int(x)
        return True
    except ValueError as _:
        return False

While True: # why is this here though?
    n=turtle.textinput(“”,”write your grade”)

    while not enforce_int(n):
        n=turtle.textinput(“”,”use only number”)

    grade = int(n)
    If grade <=100 and grade>=95 :
        print(“A+“)
    else :
        print(“F”)

【讨论】:

    【解决方案2】:

    下次请用 ASCII 格式化您的代码。

    while True:
        n = input("write your grade: ")
        while True:
            try:
                grade = int(n)
                break
            except:
                n=input("use only number: ")
    
        if grade <=100 and grade>=95 :
            print("A+")
        else :
            print("F")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-28
      • 1970-01-01
      相关资源
      最近更新 更多