Python如何检查输入是字母还是字符

Python如何检查输入是字母还是字符,python,input,integer,character,sequence,Python,Input,Integer,Character,Sequence,如何在Python中检查输入是字母还是字符 输入应该是用户想要检查的数字量。 然后程序应该检查用户提供的输入是否属于Tribonaci序列(任务中给出了0,1,2),若用户输入的不是整数,程序应该继续运行 n = int(input("How many numbers do you want to check:")) x = 0 def tribonnaci(n): sequence = (0, 1, 2, 3) a, b, c, d = sequence while

如何在Python中检查输入是字母还是字符

输入应该是用户想要检查的数字量。 然后程序应该检查用户提供的输入是否属于Tribonaci序列(任务中给出了0,1,2),若用户输入的不是整数,程序应该继续运行

n = int(input("How many numbers do you want to check:"))
x = 0

def tribonnaci(n):
    sequence = (0, 1, 2, 3)
    a, b, c, d = sequence
    while n > d:
        d = a + b + c
        a = b
        b = c
        c = d
    return d

while x < n:
    num = input("Number to check:")
    if num == "":
        print("FAIL. Give number:")
    elif int(num) <= -1:
        print(num+"\tFAIL. Number is minus")
    elif int(num) == 0:
        print(num+"\tYES")
    elif int(num) == 1:
        print(num+"\tYES")
    elif int(num) == 2:
        print(num+"\tYES")
    else:
        if tribonnaci(int(num)) == int(num):
            print(num+"\tYES")
        else:
            print(num+"\tNO")
    x = x + 1
n=int(输入(“要检查多少个数字:”)
x=0
def tribonnaci(n):
序列=(0,1,2,3)
a、 b,c,d=序列
当n>d时:
d=a+b+c
a=b
b=c
c=d
返回d
而xelif int(num)您可以通过以下方式检查输入的类型:

num = eval(input("Number to check:"))
if isinstance(num, int):
    if num < 0:
        print(num+"\tFAIL. Number is minus")
    elif tribonnaci(num) == num: # it would be clean if this function also checks for the initial correct answers. 
        print(num + '\tYES')
    else:
        print(num + '\NO')
else:
    print('FAIL, give number')
num=eval(输入(“要检查的编号:”)
如果isinstance(num,int):
如果num<0:
打印(num+“\t邮件号为负”)
elif tribonnaci(num)=num:#如果此函数还检查初始正确答案,则该函数将是干净的。
打印(num+'\tYES')
其他:
打印(num+'\NO')
其他:
打印('失败,给出编号')

如果没有给出int,那么它是错误的,所以你可以声明输入是错误的。您可以对初始的n=int(输入(“您想检查多少个数字:”)调用执行相同的操作,如果它无法成功计算为int并使程序崩溃,则此操作将失败

您可以使用num.isnumeric()函数,该函数将在输入为数字时返回“True”,在输入为非数字时返回“False”

>>> x = raw_input()
12345
>>> x.isdigit()
True
您还可以使用try/catch:

try:
   val = int(num)
except ValueError:
   print("Not an int!")

您可以使用
.isdigit()
方法

对于给定的字符串,例如输入,可以调用
string.isdigit()
,如果字符串仅由数字组成,则该函数将返回
True
;如果字符串由其他内容组成或为空,则返回
False

要验证,可以使用
if
语句检查输入是否为数字

n = input("Enter a number")
if n.isdigit():
    # rest of program
else:
    # ask for input again
我建议在用户输入要检查的数字时进行此验证。由于空字符串
导致
.isdigit()
返回
False
,因此不需要对其进行单独的验证


如果您想了解更多关于字符串方法的信息,可以查看提供了每个方法的信息并给出了每个方法的示例。

这个问题总是以这样或那样的形式出现。这里有一个更广泛的回应

## Code to check if user input is letter, integer, float or string. 

#Prompting user for input.
userInput = input("Please enter a number, character or string: ") 
while not userInput:
    userInput = input("Input cannot be empty. Please enter a number, character or string: ")

#Creating function to check user's input
inputType = '' #See: https://stackoverflow.com/questions/53584768/python-change-how-do-i-make-local-variable-global
def inputType():
    global inputType
    
def typeCheck():
    global inputType
    try:
        float(userInput) #First check for numeric. If this trips, program will move to except.
        if float(userInput).is_integer() == True: #Checking if integer
            inputType = 'an integer' 
        else:
            inputType = 'a float' #Note: n.0 is considered an integer, not float
    except:
        if len(userInput) == 1: #Strictly speaking, this is not really required. 
            if userInput.isalpha() == True:
                inputType = 'a letter'
            else:
                inputType = 'a special character'
        else:
            inputLength = len(userInput)
            if userInput.isalpha() == True:
                inputType = 'a character string of length ' + str(inputLength)
            elif userInput.isalnum() == True:
                inputType = 'an alphanumeric string of length ' + str(inputLength)
            else:
                inputType = 'a string of length ' + str(inputLength) + ' with at least one special character'

#Calling function         
typeCheck()
print(f"Your input, '{userInput}', is {inputType}.")

使用
in
if
语句,如
if variable in numers
她从输入中获取num,这将始终提供字符串,需要尝试转换它们,这取决于您使用的python版本。否,是吗?此外,您正在评估elif tribonnaci(num)
,这看起来不正确