大佬教程收集整理的这篇文章主要介绍了Python:如何在 while 循环中满足两个完全不同的条件之一,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我想要一个 while 循环,它接收一个只有数字的字符串、字符串“value”或字符串“v”。我试过:
num = input('type a number,"value",or "v". ')
while num.lower() not in ["value","v"] or num.isdigit() != True:
num = input("Can only input numbers or 'value' or 'v'. please try again ")
if num.lower() == "value" or num.lower() == "v":
print("Great you want a value!")
elif num.isdigit() == True:
print(f"Your number is {num}")
这不起作用,因为它进入了一个无限循环,要求我再次输入。我相信这是因为 while 循环想要满足这两个条件但不能。有什么方法可以重新输入 while 条件或建议使用不同的方法?
您不需要提示两次,而且您需要的是“和”而不是“或”。试试这个:
num = ''
while num.lower() not in ["value","v"] and num.isdigit() != True:
num = input("Can only input numbers or 'value' or 'v'. please try again ")
if num.lower() == "value" or num.lower() == "v":
print("Great you want a value!")
elif num.isdigit() == True:
print(f"Your number is {num}")
,
你的 while 循环需要一些编辑。
我将:while num.lower() not in ["value","v"] or num.isdigit() != True:
更改为 while not ((num.lower() in ["value","v"]) or (num.isdigit() == TruE)):
现在可以了。您可以输入“v”、“value”或任何数字:
num = input('type a number,"value",or "v". ')
while not ((num.lower() in ["value","v"]) or (num.isdigit() == TruE)):
num = input("Can only input numbers or 'value' or 'v'. please try again ")
if num.lower() == "value" or num.lower() == "v":
print("Great you want a value!")
elif num.isdigit() == True:
print(f"Your number is {num}")
,
问题是num.isdigit
。它是一个函数,你不会调用它。因此,您不是在评估函数的返回值,而是在评估函数本身。
在 python 函数中,计算结果为 True
,所以 while num.isdigit != True
永远不会终止。
call
任何方法只是通过了
他们。您必须像这样称呼它们:object.method()
而不是像 object.method
condition
更新为:num.lower() in ["value","v"] or num.isdigit() == True
。现在它会如你所愿。完整代码:
num = "value" #We can start with this value
while num.lower() in ["value","v"] or num.isdigit() == True:
num = input("Can only input numbers or 'value' or 'v'. please try again ")
if num.lower() == "value" or num.lower() == "v":
print("Great you want a value!")
elif num.isdigit() == True:
print(f"Your number is {num}")
,
您的条件设置错误。输入整数时总是满足第一个条件:
这个:
num = input('type a number,or "v". ')
while num.lower() not in ["value","v"] or num.isdigit() != True:
print(num.lower() not in ["value","v"])
print(num.isdigit() != TruE)
num = input("Can only input numbers or 'value' or 'v'. please try again ")
if num.lower == "value" or num.lower == "v":
print("Great you want a value!")
elif num.isdigit == True:
print(f"Your number is {num}")
返回:
type a number,or "v". 4
True
false
Can only input numbers or 'value' or 'v'. please try again
以上是大佬教程为你收集整理的Python:如何在 while 循环中满足两个完全不同的条件之一全部内容,希望文章能够帮你解决Python:如何在 while 循环中满足两个完全不同的条件之一所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。