【问题标题】:If statement to take input and accept integer [duplicate]If语句接受输入并接受整数[重复]
【发布时间】:2018-08-21 22:02:28
【问题描述】:

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

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

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

【问题讨论】:

  • 试试if next.IsNumeric():
  • 您描述了一种情况并发布了一些代码。您想问我们什么问题?
  • @emsimpson92:没有IsNumeric方法,isnumeric表示错误的东西。
  • @user2357112 而且在 Python 2.7 中也不存在。
  • 关键是try: 做那个how_much = int(next), except ValueError: 在这种情况下做任何你想做的事情。

标签: python


【解决方案1】:

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

如果您希望它们不是整数并且您对将输入转换为整数不感兴趣,请查看下面的内容,我使用了上述 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

如果我的解决方案有帮助,我很抱歉。但也有这个问题可能会有所帮助: How do I check if raw input is integer in python 2.7?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-03
    • 1970-01-01
    • 1970-01-01
    • 2022-11-28
    • 2019-07-24
    • 1970-01-01
    • 2020-02-21
    • 1970-01-01
    相关资源
    最近更新 更多