【问题标题】:Check if input is a string in a loop检查输入是否是循环中的字符串
【发布时间】:2013-01-25 11:23:07
【问题描述】:

我目前正在用 Python 3.3.0 编写一个程序,它打印出 n 个第一个平方数,最后打印出它们的总和。条件是用户只能计算大于零的整数项。代码如下:

print("WELCOME!")

n = input("How many numbers to sum up?: ")

while n <= 0:
    print("You have to write a positive integer; try again!")
    n = input("How many numbers to sum up?: ")

i = 1
sum = 0
while 0 < i <= n:
    print(i,"*",i,"=", i**2)
    sum += i**2
    i += 1
print("Sum:", sum)

现在,我设法为用户输入负数时的错误消息编写代码。但是,当用户键入字符串(例如“十五”)时,我很难为错误消息编码。

我希望程序允许用户一次又一次地尝试分配“n”一个值,就像他们输入了一个负数一样;基本上,如果用户输入字符串,我想编写一个循环,一遍又一遍地询问相同的事情。

问题是 input() 总是将字符串分配给任意变量,所以我尝试编写代码将字符串转换为整数。当用户输入一个整数值时它可以正常工作,但是如果 'n' 不是整数,它就不能定义 int(n)。

我在谷歌上搜索了很多关于这个问题的信息,我发现了一些使用 try 和除了 ValueError 的示例,但似乎没有一个能够从中创建循环。

有人有想法吗?

【问题讨论】:

标签: python string loops input integer


【解决方案1】:

try/except 放入循环中。

while True:
    try:
        n = int(input("How many numbers to sum up?: "))
        if n <= 0:
            print("You have to write a positive integer; try again!")
            continue
        break
    except ValueError:
        print("You have to write a positive integer; try again!")

您还可以将代码的最后一部分(第一个循环之后的部分)替换为:

squares = lambda x: [print('{0} * {0} = {1}'.format(x, x**2)), x**2][1]

print("Sum:", sum(squares(i) for i in range(1, n+1))

虽然 ;) 不推荐使用 lambda。您当然可以使用普通函数:

def squares(x):
    print('{0} * {0} = {1}'.format(x, x**2))
    return x**2

【讨论】:

    【解决方案2】:

    您可以使用str.isdigit() 来完成此操作。根据文档, isdigit() 接受兼容性上标数字,例如 \u0660123。但是 python 3 的 input() 为这种类型的输入转义了反斜杠,因此这些字符串不会引起任何问题。

    while True:
      n = input("How many numbers to sum up?: ")
      if n.isdigit() and int(n) > 0:
        break
      else:
        print("You have to write a positive integer; try again!")
    
    squares = (i**2 for i in range(1,int(n)+1))
    s = 0
    for integer in range(1,int(n)+1):
      nextsquare = next(squares)
      s += nextsquare
      print(integer, "*", integer, '=', nextsquare, sep='')
    
    print('Sum', s)
    

    【讨论】:

      【解决方案3】:

      我猜是这样的?伪蟒蛇:

      n = None
      while n is None:
          try:
              n = int(input("How many numbers to sum up?: "))
          except ValueError:
              pass
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-14
        • 2014-03-15
        • 1970-01-01
        • 2021-04-18
        • 1970-01-01
        • 2017-08-27
        • 1970-01-01
        • 2011-08-12
        相关资源
        最近更新 更多