如何将浮子字符串转换为Python 3中的整数
我是整个编码的新手...所以这里是。 只是试图编写一个简单的猜测游戏,但也要进行输入验证。因此,只有整数被接受为输入。我已经弄清楚了如何淘汰字母字符,因此我可以将数字转换为整数。放入浮子号码时,我遇到了麻烦。我无法将其转换为整数。任何帮助都将受到赞赏。正如我所说的那样,我大约在编码的第3天,所以请尝试了解我的小知识。提前致谢。
这是我的主要程序的功能。
def validateInput():
while True:
global userGuess
userGuess = input("Please enter a number from 1 to 100. ")
if userGuess.isalpha() == False:
userGuess = int(userGuess)
print(type(userGuess), "at 'isalpha() == False'")
break
elif userGuess.isalpha() == True:
print("Please enter whole numbers only, no words.")
print(type(userGuess), "at 'isalpha() == True'")
return userGuess
这是如果使用4.3(或任何浮点)作为输入,我会遇到的错误。
Traceback (most recent call last):
File "C:\\*******.py\line 58, in <module>
validateInput()
File "C:\\*******.py\line 28, in validateInput
userGuess = int(userGuess)
ValueError: invalid literal for int() with base 10: '4.3'
I'm new to the whole coding thing...so here goes.
Just trying to write a simple number guess game, but also do input validation. So that only integers are accepted as input. I've figured out how to weed out alphabetic characters, so I can convert the numbers into an integer. I'm having trouble when I put in a float number. I can't get it to convert the float number over to an integer. Any help is appreciated. As I said I'm on about day 3 of this coding thing so try to be understanding of my little knowledge. Thanks in advance.
Here's the function from my main program.
def validateInput():
while True:
global userGuess
userGuess = input("Please enter a number from 1 to 100. ")
if userGuess.isalpha() == False:
userGuess = int(userGuess)
print(type(userGuess), "at 'isalpha() == False'")
break
elif userGuess.isalpha() == True:
print("Please enter whole numbers only, no words.")
print(type(userGuess), "at 'isalpha() == True'")
return userGuess
Here's the error I'm getting if I use 4.3 (or any float) as input.
Traceback (most recent call last):
File "C:\\*******.py\line 58, in <module>
validateInput()
File "C:\\*******.py\line 28, in validateInput
userGuess = int(userGuess)
ValueError: invalid literal for int() with base 10: '4.3'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
实际
int()
函数期望整数字符串或 float ,而不是 float字符串。如果给出了float字符串,则首先需要将其转换为float
,然后int
as:Actually
int()
function expects an integer string or a float, but not a float string. If a float string is given you need to convert it tofloat
first then toint
as:不要使用
isalpha
筛选输出。 eafp - 转换并处理该例外。要么valueError
正是您想要的,因此您可以处理并告诉用户纠正其输入。或出于某些奇怪的原因,您想默默地纠正其输入从“ 4.3”到“ 4”。Don't use
isalpha
to screen the output. EAFP -- convert it and handle that exception. Either theValueError
is exactly what you want, in that you can handle it and tell the user to correct their input. Or for some odd reason you want to silently correct their input from "4.3" to "4".首先,为什么您想要将浮点字符串转换为整数?您是否要将
4.7
视为用户猜测4
的意思?还是5
?还是合法但自动持续的猜测?还是实际上是值4.7
(在这种情况下,您根本不想要整数)?或者…?其次,您接近这是错误的。
userguess.isalpha()
仅告诉您猜测完全由字母制成。这意味着您仍将对待“您好!”
是一个数字,因为它至少有一个非字母。如果您想知道字符串是否是有效的整数,只需在其上调用
int
,然后使用尝试
/处理情况在哪里:
如果要处理实际单词与其他类型的失败不同,例如,您可以打印更具体的错误消息,那么您可以在
内检查
子句。isalpha
如果要处理,请检查是否是float,以便给出不同的错误,请执行同样的事情 -
尝试
调用float(userguess)
- 内部除
条款除外。或者,如果要截断浮子,请将int(USERGUESS)
更改为int(float(userguess))
。即使在
尝试
零件中,您也可能需要其他检查。例如,如果他们键入-23
或178
怎么办?这些是整数,但它们不是1到100之间的数字。显然,您想要的验证越多,代码越多,因为每个测试都是代码的另一行。因此,您可能需要考虑将验证与循环输入的单独函数转移到单独的功能,以使其更可读。
First, why do you want to convert the float string to an integer? Do you want to treat
4.7
as meaning the user has guessed4
? Or5
? Or a legal but automatically-invalid guess? Or as actually the value4.7
(in which case you don't want integers at all)? Or…?Second, the way you're approaching this is wrong.
userGuess.isalpha()
only tells you that the guess is made entirely of letters. That means you're still going to treat, say,"Hello!"
as a number, because it has at least one non-letter.If you want to know if a string is a valid integer, just call
int
on it, and use atry
/except
to handle the case where it isn't:If you want to handle actual words differently from other kinds of failure, e.g., so you can print a more specific error message, then you can check
isalpha
inside theexcept
clause.If you want to handle check whether it's a float so you can give a different error, do the same thing—
try
to callfloat(userGuess)
—inside theexcept
clause. Or, if you want to truncate floats, change thatint(userGuess)
toint(float(userGuess))
.You may also want some other checks even inside the
try
part. For example, what if they type-23
or178
? Those are integers, but they're not numbers between 1 and 100.Obviously, the more validation you want, the more code it takes, because each test is another line of code. So, you may want to consider moving the validation out to a separate function from the looping over input, to make it more readable.
您可以使用字符串操纵和打字。
You could use string manipulation and typecasting.