Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/304.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/string/5.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 |应为INT类型,但如果输入STR?_Python_String_Python 3.x_Input_Integer - Fatal编程技术网

Python |应为INT类型,但如果输入STR?

Python |应为INT类型,但如果输入STR?,python,string,python-3.x,input,integer,Python,String,Python 3.x,Input,Integer,我要求用户输入一个整数类型。但是如果用户不小心输入了字符串类型,我想让它告诉用户他们错误地回答了这个问题。像这样: question1 = int(input("Enter a number: ")) if question1 != int: print("Please enter a number.") else: ... 请注意,我是初学者,因此不理解expect样式编码 谢谢您的时间。将字符串转换为整数仅在字符串看起来像整数时有效 任何其他操作都会引发ValueErro

我要求用户输入一个整数类型。但是如果用户不小心输入了字符串类型,我想让它告诉用户他们错误地回答了这个问题。像这样:

question1 = int(input("Enter a number: "))
if question1 != int:
    print("Please enter a number.")
else:
     ...
请注意,我是初学者,因此不理解expect样式编码


谢谢您的时间。

字符串
转换为
整数
仅在字符串看起来像整数时有效

任何其他操作都会引发
ValueError

我的建议是捕获此
ValueError
,并适当地通知用户

try:
    question1 = int(input("Enter a number: "))
except ValueError:
    print("That's not a number!")
else:
    print("Congratulations - you followed the instructions")

您可以使用
str.isdigit()
方法检查输入是否仅包含数字

question1 = input("Enter a number: ")
if question1.isdigit():
    question1= int(question1)
else:
     print("Not a number")

在您的
if
语句中,您正在比较
question1
,一个整数和
int
,一个类型。他们永远不会平等。