Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/powerbi/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 要求用户输入,直到正确为止_Python 3.x - Fatal编程技术网

Python 3.x 要求用户输入,直到正确为止

Python 3.x 要求用户输入,直到正确为止,python-3.x,Python 3.x,反复要求用户输入正确信息的最佳方式是什么 例如,我想继续检查a值是否为int值,当最后显示ok时,您选择了数字 我被困在这里: try: a = int(input()) except: print("incorrect pick a number and try again") #Somewhere here print("Ok thanks you finally picked a number")

反复要求用户输入正确信息的最佳方式是什么

例如,我想继续检查
a
值是否为
int
值,当最后显示ok时,您选择了数字

我被困在这里:

    try:

      a = int(input())

    except:
       print("incorrect pick a number and try again")


#Somewhere here

print("Ok thanks you finally picked a number")
    

您可以这样做:

a = None
while type(a) != int:
    try:
        a = int(input())
    except:
        print("incorrect pick a number and try again")

print("Ok thanks you finally picked a number")
基本上:

  • 使用
    NoneType
    创建一个变量,这样当您第一次运行程序时,它就可以访问while循环,因为条件复杂
  • 循环,直到该变量的类型不是
    int
  • 请求用户输入并尝试转换为整数,如果失败,请打印错误并重试
  • 当输入为整数类型时,它退出循环并打印最终消息

您可以使用
type()
isinstance()
进行检查,但正如@chepner所建议的,避免使用
type
,因为它只返回对象的类型,而如果对象参数是classinfo参数或(直接、间接或虚拟)其子类

为了帮助您理解:

class foo:
    pass

class bar(foo):
    pass

isinstance(foo(), foo)  # returns True
type(foo()) == foo      # returns True
isinstance(bar(), foo)    # returns True
type(bar()) == foo        # returns False,and this probably won't be what you want.
如果要使用
isinstance()
代码,则代码将产生以下结果:

a = None

while not isinstance(a, int):
    try:
        a = int(input())
    except:
        print("incorrect pick a number and try again")

print("Ok thanks you finally picked a number")

正如@l3via所指出的,您还可以:

a = None
while a is None:
    try:
        a = int(input())
    except:
        print("incorrect pick a number and try again")

print("Ok thanks you finally picked a number")

在本例中,您循环直到
a
获得一个值,只有在未引发异常时才会执行该操作。

您要捕获的唯一异常是
int
引发的
ValueError
,如果它无法将其参数转换为整数。
try
语句将位于循环中,您将显式执行该操作如果你没有得到一个例外,就中断

while True:
    try:
        number=int(input("Enter a number: ")) 
    except:
        print("incorrect pick a number and try again")
    else:
        print("ok Thanks you finally picked  a number ")
        break
while True:
    response = input()
    try:
        a = int(response)
    except ValueError:
        print("incorrect pick a number and try again")
    else:
        print("Ok thanks you finally picked a number")
        break

如果您想要/必须保存此代码,我认为唯一的方法是使用循环

while True:
try:
    a = int(input('Insert a number:'))
    print ('Your number is {}'.format(a))
    break

except ValueError:
    print("incorrect pick a number and try again")
因此,如果用户插入一个整数,代码将打印数字并中断循环,否则将重复该请求。
我希望它对你有用!

除了
int
type(None)
之外,
type(a)
怎么可能是别的呢?为什么不做
,而a是None:
在那种情况下呢?你几乎永远不想使用
type(x)==y
;而是使用
isinstance(x,y)
。@chepner请解释一下原因。我知道type()仅返回对象的类型,而isinstance():如果对象参数是classinfo参数或(直接、间接或虚拟)的实例,则返回true它的子类。@carlozanco这就是原因。你几乎从不关心确切的类型,忽略子类型。@chepner在这种情况下,这怎么可能是个问题?
number
根据定义,如果你到达
try
语句后面的语句,那么它就是一个
int
。你不需要
isinstance