如何在 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))
相关文章