How to force integer input in Python 3.x? [duplicate]

半腔热情 提交于 2019-12-02 01:49:19

问题


I'm trying to make a program in Python that takes in an input for how many times to repeat the Fibonacci sequence.

...
i=1
timeNum= input("How many times do you want to repeat the sequence?")
while i <= timeNum:
    ...
    i += 1

How can I force that input to be an integer? I can't have people repeating the sequence 'apple' times? I know it involves int() but I don't know how to use it. Any and all help is appreciated.


回答1:


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.



来源:https://stackoverflow.com/questions/38987072/how-to-force-integer-input-in-python-3-x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!