How to force integer input in Python 3.x?

This question already has an answer here:

  • How do I parse a string to a float or int in Python? 22 answers

  • You could try to cast to an int, and repeat the question if it fails.

    i = 1
    while True:
        timeNum = input("How many times do you want to repeat the sequence?")
        try:
            timeNum = int(timeNum)
            break
        except ValueError:
            pass
    
    while i <= timeNum:
        ...
        i += 1
    

    Though using try-catch for handling is taboo in some languages, Python tends to embrace the "ask for forgiveness, not permission approach". To quote the section on EAFP in the Python glossary:

    Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements.

    链接地址: http://www.djcxy.com/p/48428.html

    上一篇: 如何使原始输入数字?

    下一篇: 如何在Python 3.x中强制整数输入?