首页 > 解决方案 > 有没有更好的方法来确保变量只包含数字

问题描述

toss_number = input("How many times do you want to toss the coin?\n")

while True:
    if toss_number.isdigit():
        break
    else:
        toss_number = input("Please input NUMBER of times you want to toss a coin.\n")

这些代码行本质上确保了 toss_number 包含一串数字。有没有更好/更有效的方法来做到这一点?

标签: pythonstringpython-3.xinput

解决方案


另一种方法是使用try/ except。如果经常输入一个数字,这将更有效。

while True:
    try:
        toss_number = int(input("How many times do you want to toss the coin?\n"))
        break
    except ValueError:
        print('You have not entered a NUMBER.')

ValueError被引发时,会打印一条消息,但循环没有中断,所以我们返回到while循环的开头和try部分。


推荐阅读