【Validation】Type Check on Input

274 阅读1分钟

Method

Problem

Check if a user-input variable is a number.

Solution

a.isdigit()

Example

a = input('Please enter a number: ')
while not a.isdigit():
    a = input('Not a number. Please enter a number: ')

Relative information

  1. 在Python 中isdigit () 检测字符串是否只由数字组成。

  2. no need for a separate presence check when using .isdigit. 使用 .isdigit 时不需要单独的有无检测(检查输入是否为空)。

References

see other is...() functions:

English original version Python String isdigit() Method - W3School

中文版 Python isdigit () 方法 - 菜鸟教程

Useful websites

English original website W3Schools

中文版 菜鸟教程