s = True
while s == True:
#taking input from the user
num1 = int(input("enter a number: "))
sign = input("enter a sign from :+ , - , * , /")
num2 = int(input("enter a second number: "))
#calculation
if sign == "+" :
print(f'the sum of {num1} and {num2} is {num1+num2}')
elif sign == "-" :
print(f'the difference of {num1} and {num2} is {num1-num2}')
elif sign == "*" :
print(f'the multiplication of {num1} and {num2} is {num1*num2}')
elif sign == "/" :
print(f'the difference of {num1} and {num2} is {num1/num2}')
else:
print('invalid sign')
s = bool(input("type True to start the calculater and False to stop the calculater: "))
无论用户的输入是什么,它都会被转换为True,我怎样才能将输入转换为False,这样我就可以脱离循环了。
不要为布尔字面数而烦恼。只需进行显式字符串比较。另外,使用infinite-loope-explicit-break模式而不是布尔标志。
while True:
...
s = input("type True...")
if s != "True":
break
你可以用 s != "True"
与任何更多涉及的检查,忽略大小写的区别,允许 "真 "或 "假 "的同义词,如 "是""否","T""F "等,或其他检查。
你的问题的根源在于 bool
不解析一个 str
寻欢作乐 bool
字面意思。空字符串是 False
所有其他字符串都是 True
:
>>> bool("")
False
>>> bool("True")
True
>>> bool("False")
True
>>> bool("not True")
True