2024-04-26 05:10:06 发布
网友
我的代码有问题。当我输入数字时,它仍然显示“只允许数字”。我该怎么修?你知道吗
代码如下:
age = input("What's your age? ") while age != age.isdigit(): print("only numbers are allowed") age = input("What's your age? ") age = int(age)
表达式age.isdigit()不返回数字。它返回True或False。因此,条件age != age.isdigit()是将age中的字符串值与布尔值True或False进行比较,这将永远不会计算为true。你知道吗
age.isdigit()
True
False
age != age.isdigit()
age
如果希望循环在年龄不是全数字字符串时继续,可以使用while not age.isdigit()。你知道吗
while not age.isdigit()
你也可以这样写:
while true: age = input("What's your age? ") if age.isdigit(): break age = int(age)
我发现这更容易理解,因为你不必重复输入提示,也不需要使用否定条件。你知道吗
表达式
age.isdigit()
不返回数字。它返回True
或False
。因此,条件age != age.isdigit()
是将age
中的字符串值与布尔值True
或False
进行比较,这将永远不会计算为true。你知道吗如果希望循环在年龄不是全数字字符串时继续,可以使用
while not age.isdigit()
。你知道吗你也可以这样写:
我发现这更容易理解,因为你不必重复输入提示,也不需要使用否定条件。你知道吗
相关问题 更多 >
编程相关推荐