首页 > 解决方案 > If 语句接受输入并接受整数

问题描述

我需要编写一个 if 语句来接受用户输入并接受整数。

这是代码,但它只采用指定的整数。

next = raw_input("> ")
if "0" in next or "1" in next:
    how_much = int(next)

标签: python

解决方案


有几种方法可以解决这个问题,因为我不确定您到底在寻找什么。他们来了:

如果您希望它们不是整数并且您对将输入转换为整数不感兴趣,请查看下面的内容,我使用了上述 isnumeric() 函数:

Python 3 回答如下:

enter_num=input('Please Enter a number: \n') # I am prompting the user #for input and the \n means new line so the user would enter a value on #the new line
if enter_num.isnumeric(): #if the value the user entered is a number #proceed into the if statement
    print('You must have entered an integer value') # print this #statement out if the if statement conditon is true

我不确定你是否熟悉 try 块,所以我不会进入它,但这里有另一种方法(我也不确定你是否熟悉 isinstance() 函数):

number=int(input('Please Enter a number: \n')) #prompting the user for #a number

if isinstance(number,int): # if the vlaue is a integer enter the if #statement
    print('this is an integer') #enters the if statement if its true

如果我的解决方案有帮助,我很抱歉。但也有这个问题可能会有所帮助: 如何在 python 2.7 中检查原始输入是否为整数?


推荐阅读