gpt4 book ai didi

Python - 测试 Raw-Input 是否没有条目

转载 作者:太空狗 更新时间:2023-10-30 00:49:35 24 4
gpt4 key购买 nike

我可能遇到了最愚蠢的问题......

我如何判断 raw_input 是否从未输入过任何内容? (空)

final = raw_input("We will only cube numbers that are divisible by 3?")
if len(final)==0:
print "You need to type something in..."
else:
def cube(n):
return n**3
def by_three(n):
if n%3==0:
return cube(n)
else:
return "Sorry Bro. Please enter a number divisible by 3"
print by_three(int(final))

特别是第 2 行...如果 final 没有输入,我将如何测试?该代码适用于输入的任何内容,但如果未提供任何条目,则会中断....

我确信这非常简单,但我们非常感谢任何帮助。

最佳答案

没有输入导致空字符串;空字符串(如空容器和数字零)测试为 bool 值 false;简单地测试 not final:

if not final:
print "You need to type something in..."

您可能希望去除字符串中的所有空格以避免在仅输入空格或制表符时中断:

if not final.strip():
print "You need to type something in..."

但是,您仍然需要验证用户输入的整数是否有效。您可以捕获 ValueError 异常:

final = raw_input("We will only cube numbers that are divisible by 3?")
try:
final = int(final)
except ValueError:
print "You need to type in a valid integer number!"
else:
# code to execute when `final` was correctly interpreted as an integer.

关于Python - 测试 Raw-Input 是否没有条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18542107/

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