Isa*_*und 3 python global-variables syntax-error python-3.x
首先,我必须告诉你,我对编码完全陌生,所以我遇到的问题可能是由有史以来最愚蠢的错误引起的,如果是这样,我很抱歉!
我正在尝试制作一个能够计算 +、-、*、/ 的计算器。如果收到的操作符号无效,它还应该给出错误消息并要求提供新的操作符号。为了让计算机知道函数“main”是否正在运行,因为它收到了一个无效的函数,或者它是第一次运行,我试图使用一个名为“check”的全局变量。开始时,check设置为1,因此计算机在要求操作时会使用第一个短语。如果输入了一个无效的操作,变量“check”就会加一,当它要求一个新的操作时,这将导致第二个短语(错误信息)。
问题是,当我尝试运行脚本时,在第一行出现语法错误,其中“全局检查 = 1”。我究竟做错了什么?
下面是我的代码:
global check = 1
#returns num1 + num2
def add(num1,num2):
return num1 + num2
#returns num1 - num2
def sub(num1,num2):
return num1 - num2
#returns num1 * num2
def mul (num1,num2):
return num1 * num2
#returns num1 / num2
def div (num1,num2):
return num1 / num2
#Main Function
def main():
if(global check == 1): #checks if "main" has been read before, if it has, then it is read agian because of invalid operation, and the global "check" should be higher than 1.
operation = input("Choose an operation! (+,-,*,/")
else:
operation = input("You must choose a valid operation! (+,-,*,/")
if(operation != "+" and operation != "-" and operation != "*" and operation != "/"):
global check = global check + 1
main()
else:
var1 = int(input("Enter number 1 :"))
var2 = int(input("Enter number 2 :"))
if(operation == "+"):
print(add(var1,var2))
elif(operation == "-"):
print(sub(var1,var2))
elif(operation == "*"):
print(mul(var1,var2))
else:
print(div(var1,var2))
main()
Run Code Online (Sandbox Code Playgroud)
小智 5
你把global它放在不需要的地方:
global check = 1
Run Code Online (Sandbox Code Playgroud)
你不需要global这里,check已经是global在这里了。
if(global check == 1),global check = global check + 1也不是有效的使用global。
相反,在 main() 中声明check为global:
def main():
global check
Run Code Online (Sandbox Code Playgroud)