在用Python编程时,我遇到了这样一种情况:while
循环即使在满足条件之后也没有终止
代码如下:
print('--- Alex\'s Calculator ---')
print('1. ADDition')
print('2. SUBstraction')
print('3. MULtiply')
print('4. DIVide')
print('5. EXIT')
x = int(input())
command = ' Enter Your Two numbers To Perform The Operation : '
def ini():
a = int(input())
b = int(input())
return a, b
def resultoo():
result = ' Your Result after Performing The Operation from {} and {} is {}'
print(result.format(a,b,c))
print(' Want To Continue If Yes then Enter Your Choice else Press any number exept 1 - 4')
x = int(input())
while x < 5:
if x == 1:
print(command)
a, b = ini()
c = a + b
resultoo()
elif x < 5:
break
您可以使用
global
var来实现此目的,更改this:分为:
解释:
x
是一个全局参数,它在函数闭包外是相同的,但在闭包内是不同的,函数有自己的参数,因此如果要更改在函数外初始化的全局参数,则需要在前面调用global
语句,这将使x
成为全局x
当输入选项5时,您希望退出。你知道吗
我补充道
改变了
至
并补充道
我还添加了getMenu()函数
以下是在我的编辑器中运行的完整代码:
我还格式化了您的代码(alt+Enter-in-Pycharm)以符合PEP8标准;)
正如kuro在注释中指定的那样,x不能被while循环看到,因为它是resulttoo()的本地对象。你知道吗
要轻松解决此问题,只需添加:
在resultoo()的末尾
以及
在你的while循环中
相关问题 更多 >
编程相关推荐