gpt4 book ai didi

python - 如何检查用户输入是否为 float

转载 作者:行者123 更新时间:2023-11-28 21:20:08 26 4
gpt4 key购买 nike

我正在做“艰难地学习 Python”练习 35。下面是原始代码,我们被要求更改它,以便它可以接受不只有 0 和 1 的数字。

def gold_room():
print "This room is full of gold. How much do you take?"

next = raw_input("> ")

if "0" in next or "1" in next:
how_much = int(next)

else:
dead("Man, learn to type a number.")

if how_much < 50:
print "Nice, you're not greedy, you win!"
exit(0)

else:
dead("You greedy bastard!")

这是我的解决方案,可以正常运行并识别浮点值:

def gold_room():
print "This room is full of gold. What percent of it do you take?"

next = raw_input("> ")

try:
how_much = float(next)
except ValueError:
print "Man, learn to type a number."
gold_room()

if how_much <= 50:
print "Nice, you're not greedy, you win!"
exit(0)

else:
dead("You greedy bastard!")

通过搜索类似的问题,我找到了一些帮助我编写另一个解决方案的答案,如下面的代码所示。问题是,使用 isdigit() 不会让用户输入浮点值。所以如果用户说他们想要 50.5%,它会告诉他们学习如何输入一个数字。它适用于整数。我该如何解决这个问题?

def gold_room():
print "This room is full of gold. What percent of it do you take?"

next = raw_input("> ")

while True:
if next.isdigit():
how_much = float(next)

if how_much <= 50:
print "Nice, you're not greedy, you win!"
exit(0)

else:
dead("You greedy bastard!")

else:
print "Man, learn to type a number."
gold_room()

最佳答案

如果 next 已经从字符串转换而来,

isinstance(next, (float, int)) 将简单地执行此操作。在这种情况下不是。因此,如果您想避免使用 try..except,则必须使用 re 进行转换。

我建议使用您之前使用的 try..except block 而不是 if..else block ,但将更多代码放入其中,如图所示下面。

def gold_room():
while True:
print "This room is full of gold. What percent of it do you take?"
try:
how_much = float(raw_input("> "))

if how_much <= 50:
print "Nice, you're not greedy, you win!"
exit(0)

else:
dead("You greedy bastard!")

except ValueError:
print "Man, learn to type a number."

这将尝试将其转换为 float ,如果失败,将引发将被捕获的 ValueError。要了解更多信息,请参阅 Python Tutorial在上面。

关于python - 如何检查用户输入是否为 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23303827/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com