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

2020-02-07 05:09发布

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条回答
叛逆
2楼-- · 2020-02-07 05:57

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.

查看更多
登录 后发表回答