测试一个字符串是否代表一个数字

Test if a string represents a number

为我的第一个 Python 项目构建一个简单的计算器并遇到以下评论中显示的问题:

special_keys = ["`", "~", "!", "@", " ", "#", "$"]

while True:
    num1 = input("Enter First Number: ")
    if num1.isalpha():
        print("Invalid, Try Again.")
        continue

     # elif num1 contains an element or part of an
     # element in special_keys do the following:
         # print("Invalid, Try Again.")
         # continue

    else:
    num1 = float(num1)
    break

这一切都没有必要。您可以简单地尝试将输入转换为 float。如果它抛出错误,则意味着输入不是有效数字。您可以使用 try-except 块捕获此错误并打印 Invalid:

while True:
    num1 = input("Enter First Number: ")
    try:
        num1 = float(num1)
        break 
    except ValueError:
        print("Invalid")

输出:

Enter First Number: >? 1`
Invalid
Enter First Number: >? 1-0-0
Invalid
Enter First Number: >? 100

不用检查字符串是否包含字母字符或特殊字符,您可以直接检查它是否代表数字:

def input_number(prompt_msg, err_msg):
  we_got_a_number = False
  while not we_got_a_number:
    num_string = input(prompt_msg)
    try:
      num = int(num_string)
      we_got_a_number = True
    except ValueError:
      print(err_msg)
  return num

num1 = input_number("Enter First Number: ", "Invalid, Try Again.")

如果您想使用 floats 而不是 ints,只需将 int(num_string) 替换为 float(num_string)

您可以针对非数字发出警告,而不是针对 alpha 发出警告:

if !num1.isisdigit():
    print("Invalid, Try Again.")
    continue