【问题标题】:Check for a string in if-statement检查 if 语句中的字符串
【发布时间】:2015-12-02 06:52:20
【问题描述】:

我有一个包含一些用户输入的程序,我需要检查用户输入的是字符串还是介于 1 到 1000 万之间的整数值。

我的代码看起来像这样(简化):

while True:
    inp = raw_input("Enter a value between 1 and 10 million: ")
    if inp < 1:
        print "Must be higher than 1"
        continue
    elif inp > 10.000.000:
        print "Must be less than 10.000.000"
        continue
    elif 'inp is a string':                           #here's my problem
        print "Must be an integer value!"
        continue
    else:
        'execute the rest of the code'

我不知道如何解决这个问题。当我输入错误的字符串时,我的程序总是终止。

谢谢!

【问题讨论】:

  • 不要命名变量in。它是 Python 中的保留字。
  • 这只是我输入的缩写

标签: python string input int


【解决方案1】:

我不知道您是如何提出代码的,但这里有不同的建议:

不要使用“in”作为变量名,因为它是一个 python 运算符。

输入后可以判断是int还是string。

您的程序可能如下所示:

while True:    
    try:
        input_int = int(raw_input("Enter a value between 1 and 10 million: "))
        if  input_int < 1 :
            print "Must be higher than 1"
        elif input_int > 10**7:
            print "Must be less than 10.000.000"
    except:
        print "Must be an integer value!"
    else: #You can use else with try/except block
        #'execute the rest of the code'

瞧

【讨论】:

  • 我不知道我怎么错过了in,但是你有它。
  • 但是,我也不推荐使用 input 的名称,因为这是一个内置函数(在 Python 2 和 3 中)。
  • 谢谢你的回答,但Tigers版本首先帮助了我。
【解决方案2】:

首先,您使用的是 Python 2,它会愉快地将字符串与整数进行比较。你不想那样做。其次,raw_input() 将总是返回一个字符串。您希望做的是检查该字符串是否可能表示一个数字。第三,10.000.000 语法不正确。不要使用分隔符。第四,如果你想早进入循环顶部,你只需要continue。如果所有内容都在循环末尾的if..elif..else 块中,则只会执行其中一个,因此您无需在每个分支的末尾放置continue。您可以使用continue 语句或重组您的分支。最后,不要使用 in 作为变量名,因为那是 Python 关键字。

while True:
    inp = raw_input("Enter a value between 1 and 10 million: ")

    if not inp.isdigit():
        print "Must be an integer value!"
        continue # each of these continue statements acts like a "failed, try again"

    inp = int(inp)

    if inp < 1:
        print "Must be higher than 1"
        continue # same for this one

    if inp > 10000000:
        print "Must be less than 10.000.000"
        continue # and this one

    # execute the rest of the code

【讨论】:

  • 谢谢你,帮了我很多。这就是我要找的!并简化了代码以更容易阅读,因此我使用了分隔符:)
【解决方案3】:

您可以使用.isdigit() 检查字符串是否由数字组成,以确保它可以转换为整数:

while True:
    in = raw_input("Enter a value between 1 and 10 million: ")
    if in.isdigit():
        number = int(in)
        if number < 1:
            print "Must be higher than 1"
            continue
        elif number > 10**6:
            print "Must be less than 10.000.000"
            continue
       else:
           'execute the rest of the code'
    else:
        print "Must be an integer value!"
        continue

【讨论】:

  • 谢谢我使用了 Tigerhawk 的 .isdigit() 版本
猜你喜欢
  • 1970-01-01
  • 2017-10-25
  • 1970-01-01
  • 1970-01-01
  • 2013-10-03
  • 2017-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多