如何在Python 3.x中强制整数输入?

这个问题已经在这里有了答案:            >            How do I parse a string to a float or int?                                    23个
我正在尝试用Python制作一个程序,该程序接受一个输入以重复斐波那契数列的次数.

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

如何强制输入为整数?我不能让人们重复序列“苹果”时间吗?我知道它涉及int(),但我不知道如何使用它.任何和所有帮助表示赞赏.

解决方法:

您可以尝试将其强制转换为int,如果失败则重复该问题.

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

尽管在某些语言中使用try-catch进行处理是禁忌,但是Python倾向于接受“请求宽恕,而不是许可方法”.引用Python glossary中有关EAFP的部分:

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.

上一篇:java-动态编程斐波那契数列


下一篇:Javascript中的斐波纳契数列