如何在Python 3.x中强制输入整数? [英] How to force integer input in Python 3.x?

查看:210
本文介绍了如何在Python 3.x中强制输入整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Python中创建一个程序,该程序接受重复Fibonacci序列多少次的输入。

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

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

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.

推荐答案

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

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

虽然使用试试在一些语言中,用于处理的句子是禁忌,Python倾向于接受请求宽恕,而不是许可方法。在 Python词汇表中引用EAFP部分:

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:


比许可更容易请求宽恕。这种常见的Python编码风格假定存在有效的键或属性,并且如果假设被证明是错误则捕获异常。这种干净,快速的风格的特点是存在许多try和except语句。

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.

这篇关于如何在Python 3.x中强制输入整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆