[英]Python - If Statement With input() Not Functioning Inside def() Function
除了def a()
和def b()
都有代码外,代码中的所有内容都可以正常运行,并且如果我在运行代码时检查并input
函数的语句,无论输入内容如何,都会打印出'good for you'
。 例如,如果我在代码中键入False
或Whatever
,这将导致不同的结果,则两者均会导致响应'good for you'
,就好像输入始终是'True'
或'true'
。 我已经很久没有编码了,所以如果这很明显,请原谅。
tsil = ['input',]
while True:
print('Write A Number (Print "done" When Finished)')
num = input()
tsil.append(num)
print()
if num == 'done':
break
if True == True:
print(tsil)
def a():
print('you like short lists? (True or False)')
ans = input()
if ans == 'True' or 'true':
return '\ngood for you'
elif ans == 'False' or 'false':
return '\nstop making short lists then'
else:
return '\nstop printing the wrong things loser'
def b():
print('you like long lists? (True or False)')
ans = input()
if ans == 'True' or 'true':
return '\ngood for you'
elif ans == 'False' or 'false':
return '\nstop making short lists then'
else:
return '\nstop printing the wrong things loser'
if len(tsil) < 10:
print('^ short list large gorge')
print()
print(a())
else:
print('^ big boy list')
print()
print(b())
您需要将if语句从if ans == 'True' or 'true':
更改为if ans == 'True' or ans == 'true':
请参阅以下代码:
def a():
print('you like short lists? (True or False)')
ans = input()
if ans == 'True' or ans == 'true': # if ans.lower() == 'true':
return '\ngood for you'
elif ans == 'False' or 'false':
return '\nstop making short lists then'
else:
return '\nstop printing the wrong things loser'
推理
如果您检查ans == 'True' or 'true
将始终生成'True'
,这是OR
条件下的第一个值。
bool('any value')
始终为True
仔细看这行ans == 'True' or 'true'
这将始终返回True
你可以试试
print(bool('False' == 'True' or 'true'))
print(bool(-999 == 'True' or 'true'))
print(bool('Unicorn' == 'True' or 'true'))
看看它的真实价值。
要解决此问题,您可以将ans == 'True' or 'true'
替换为
if ans in ['True', 'true']:
要么
if ans.lower() == 'true':
希望这可以帮助。
if ans == 'True' or 'true'
应该
if ans == 'True' or ans == 'true'
与其他类似情况相同,因为if 'non-empty string'
值为True
您的问题是函数中的条件如下:
ans == 'True' or 'true'
python解释器将其视为:
(ans == 'True') or ('true')
在if语句中使用时,非空字符串的计算结果为true。
更改为此:
ans == 'True' or ans == 'true'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.