你如何在 Python 中使用 input 输入整数 [英] How do you input integers using input in Python

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

问题描述

我正在尝试自学如何用 Python 编写代码,这是我第一次在 Stack Overflow 上发帖,所以请原谅这篇文章中的任何不当之处.但让我们开始吧.

I'm trying to teach myself how to code in Python and this is my first time posting to Stack Overflow, so please excuse any improprieties in this post. But let's get right to it.

我正在尝试使用输入命令返回一个整数.我也做了我的研究,所以下面是我在 Python 3.4 中的多次尝试和以下结果:

I'm trying to use the input command to return an integer. I've done my research, too, so below are my multiple attempts in Python 3.4 and the results that follow:

guess_row = int(input("Guess Row: "))

我得到以下信息:

Traceback (most recent call last):
File "<input>", line 1, in <module> 
ValueError: invalid literal for int() with base 10: 'Guess Row: 2`

尝试#2

guess_row = float(input("Guess Row: "))

我得到以下信息:

Traceback (most recent call last):
File "<input>", line 1, in <module>
ValueError: could not convert string to float: "Guess Row: 2""

尝试 #3

try:
    guess_row=int(input("Guess Row: "))
except ValueError:
    print("Not an integer")

在这里,我得到以下信息:

Here, I get back the following:

Guess Row: 2
Not an integer

虽然它返回了一些东西,但我知道这是错误的,因为一方面,输入作为字符串返回并且它还返回打印命令.

Although it returns something, I know this is wrong because, for one, the input returns as a string and it also returns the print command.

重点是,我尝试过 int、float 和 try,但到目前为止没有任何效果.有什么建议?我只想能够输入一个整数并将其作为一个返回.

Point being, I've tried int, float, and try, and so far nothing has worked. Any suggestions? I just want to be able to input an integer and have it returned as one.

推荐答案

您的第三次尝试是正确的 - 但是在此代码之前/之后 guess_row 发生了什么?例如,请考虑以下内容:

Your third attempt is correct - but what is happening to guess_row before/after this code? For example, consider the following:

a = "Hello"
try:
    a = int(input("Enter a number: "))
except ValueError:
    print("Not an integer value...")
print(str(a))

如果输入有效数字,最后一行将打印出您输入的值.如果不是,将引发异常(在 except 块中显示错误消息)并且 a 将保持不变,因此最后一行将打印Hello".

If you enter a valid number, the final line will print out the value you entered. If not, an exception will be raised (showing the error message in the except block) and a will remain unchanged, so the final line will print "Hello" instead.

您可以优化此设置,以便无效数字会提示用户重新输入值:

You can refine this so that an invalid number will prompt the user to re-enter the value:

a = None
while a is None:
    try:
        a = int(input("Enter a number: "))
    except ValueError:
        print("Not an integer value...")
print(str(a))

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

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